git.iko.soy/typeable/pandoc
on 74a180c help sign in
2 files changed+1567−1272
since splitsnapshots
unifiedsplit
src/Text/Pandoc/Parsing.hs+15−10 src/Text/Pandoc/Readers/LaTeX.hs+1552−1262
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+1552−1262
@@ -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,265 @@ 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+-- we put withMacros in front of satisfyTok, so it works on everything
199+satisfyTok :: PandocMonad m => (Tok -> Bool) -> LP m Tok
200+satisfyTok f =
201+ doMacros *> 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+-- TODO use something other than ParserState
210+doMacros :: PandocMonad m => LP m ()
211+doMacros = do
212+ inp <- getInput
213+ macros <- stateMacros <$> getState
214+ case inp of
215+ t@(Tok spos CtrlSeq txt) : ts
216+ | txt == "\\macro" -> do -- TODO actually check macros
217+ setInput $ map (setpos spos) (tokenize "Hi there") ++ ts
218+ -- TODO loop detection
219+ doMacros
220+ _ -> return ()
221+
222+setpos :: (Line, Column) -> Tok -> Tok
223+setpos spos (Tok _ tt txt) = Tok spos tt txt
224+
225+anyControlSeq :: PandocMonad m => LP m Tok
226+anyControlSeq = satisfyTok isCtrlSeq <* optional sp
227+ where isCtrlSeq (Tok _ CtrlSeq _) = True
228+ isCtrlSeq _ = False
229+
230+anySymbol :: PandocMonad m => LP m Tok
231+anySymbol = satisfyTok isSym
232+ where isSym (Tok _ Symbol _) = True
233+ isSym _ = False
234+
235+spaces :: PandocMonad m => LP m ()
236+spaces = skipMany (satisfyTok (tokTypeIn [Comment, Spaces, Newline]))
237+
238+spaces1 :: PandocMonad m => LP m ()
239+spaces1 = skipMany1 (satisfyTok (tokTypeIn [Comment, Spaces, Newline]))
240+
241+tokTypeIn :: [TokType] -> Tok -> Bool
242+tokTypeIn toktypes (Tok _ tt _) = tt `elem` toktypes
243+
244+controlSeq :: PandocMonad m => Text -> LP m Tok
245+controlSeq name = satisfyTok isNamed
246+ where isNamed (Tok _ CtrlSeq n) = n == T.singleton '\\' <> name
247+ isNamed _ = False
248+
249+symbol :: PandocMonad m => Char -> LP m Tok
250+symbol c = satisfyTok isc
251+ where isc (Tok _ Symbol d) = case T.uncons d of
252+ Just (c',_) -> c == c'
253+ _ -> False
254+ isc _ = False
255+
256+symbolIn :: PandocMonad m => [Char] -> LP m Tok
257+symbolIn cs = satisfyTok isInCs
258+ where isInCs (Tok _ Symbol d) = case T.uncons d of
259+ Just (c,_) -> c `elem` cs
260+ _ -> False
261+ isInCs _ = False
117262
118263sp :: PandocMonad m => LP m ()
119264sp = whitespace <|> endline
120265
121266whitespace :: PandocMonad m => LP m ()
122−whitespace = skipMany1 $ satisfy (\c -> c == ' ' || c == '\t')
123−
124−endline :: PandocMonad m => LP m ()
125−endline = try (newline >> lookAhead anyChar >> notFollowedBy blankline)
267+whitespace = () <$ satisfyTok isSpaceTok
268+ where isSpaceTok (Tok _ Spaces _) = True
269+ isSpaceTok _ = False
126270
127−isLowerHex :: Char -> Bool
128−isLowerHex x = x >= '0' && x <= '9' || x >= 'a' && x <= 'f'
271+newlineTok :: PandocMonad m => LP m ()
272+newlineTok = () <$ satisfyTok isNewlineTok
129273
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)
274+isNewlineTok :: Tok -> Bool
275+isNewlineTok (Tok _ Newline _) = True
276+isNewlineTok _ = False
142277
143278comment :: PandocMonad m => LP m ()
144−comment = do
145− char '%'
146− skipMany (satisfy (/='\n'))
147− optional newline
148− return ()
279+comment = () <$ satisfyTok isCommentTok
280+ where isCommentTok (Tok _ Comment _) = True
281+ isCommentTok _ = False
282+
283+anyTok :: PandocMonad m => LP m Tok
284+anyTok = satisfyTok (const True)
285+
286+endline :: PandocMonad m => LP m ()
287+endline = try $ do
288+ newlineTok
289+ lookAhead anyTok
290+ notFollowedBy blankline
291+
292+blankline :: PandocMonad m => LP m ()
293+blankline = try $ do
294+ skipMany (satisfyTok (tokTypeIn [Spaces, Newline]))
295+ newlineTok
296+
297+primEscape :: PandocMonad m => LP m Char
298+primEscape = do
299+ Tok _ toktype t <- satisfyTok (tokTypeIn [Esc1, Esc2])
300+ case toktype of
301+ Esc1 -> case T.uncons t of
302+ Just (c, _)
303+ | c >= '\64' && c <= '\127' -> return (chr (ord c - 64))
304+ | otherwise -> return (chr (ord c + 64))
305+ Nothing -> fail "Empty content of Esc1"
306+ Esc2 -> case safeRead ('0':'x':T.unpack (T.drop 2 t)) of
307+ Just x -> return (chr x)
308+ Nothing -> fail $ "Could not read: " ++ T.unpack t
309+ _ -> fail "Expected an Esc1 or Esc2 token" -- should not happen
149310
150311bgroup :: PandocMonad m => LP m ()
151312bgroup = try $ do
152− skipMany (spaceChar <|> try (newline <* notFollowedBy blankline))
153− () <$ char '{'
154− <|> () <$ controlSeq "bgroup"
155− <|> () <$ controlSeq "begingroup"
313+ skipMany sp
314+ symbol '{' <|> controlSeq "bgroup" <|> controlSeq "begingroup"
315+ return ()
156316
157317egroup :: PandocMonad m => LP m ()
158−egroup = () <$ char '}'
159− <|> () <$ controlSeq "egroup"
160− <|> () <$ controlSeq "endgroup"
318+egroup = () <$ (symbol '}' <|> controlSeq "egroup" <|> controlSeq "endgroup")
161319
162−grouped :: PandocMonad m => Monoid a => LP m a -> LP m a
320+grouped :: (PandocMonad m, Monoid a) => LP m a -> LP m a
163321grouped parser = try $ do
164322 bgroup
165323 -- first we check for an inner 'grouped', because
166324 -- {{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
325+ try (grouped parser <* egroup) <|> (mconcat <$> manyTill parser egroup)
326+
327+braced :: PandocMonad m => LP m [Tok]
328+braced = try $ do
329+ bgroup
330+ -- {{a,b}} should be parsed the same as {a,b}
331+ try (braced <* egroup) <|> manyTill anyTok egroup
179332
180333bracketed :: 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
334+bracketed parser = try $ do
335+ symbol '['
336+ mconcat <$> manyTill parser (symbol ']')
217337
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 '"')
338+dimenarg :: PandocMonad m => LP m Text
339+dimenarg = try $ do
340+ ch <- option False $ True <$ symbol '='
341+ Tok _ _ s <- satisfyTok isWordTok
342+ guard $ (T.take 2 (T.reverse s)) `elem`
343+ ["pt","pc","in","bp","cm","mm","dd","cc","sp"]
344+ let num = T.take (T.length s - 2) s
345+ guard $ T.length num > 0
346+ guard $ T.all isDigit num
347+ return $ T.pack ['=' | ch] <> s
225348
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 "`\'‘’")
349+-- inline elements:
233350
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])
351+inlineText :: PandocMonad m => LP m Inlines
352+inlineText = (str . T.unpack . untoken) <$> satisfyTok isWordTok
259353
260−inlines :: PandocMonad m => LP m Inlines
261−inlines = mconcat <$> many (notFollowedBy (char '}') *> inline)
354+isWordTok :: Tok -> Bool
355+isWordTok (Tok _ Word _) = True
356+isWordTok _ = False
262357
263358inlineGroup :: PandocMonad m => LP m Inlines
264359inlineGroup = do
@@ -269,233 +364,466 @@ inlineGroup = do
269364 -- we need the span so we can detitlecase bibtex entries;
270365 -- we need to know when something is {C}apitalized
271366
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
367+doLHSverb :: PandocMonad m => LP m Inlines
368+doLHSverb =
369+ (codeWith ("",["haskell"],[]) . T.unpack . untokenize)
370+ <$> manyTill (satisfyTok (not . isNewlineTok)) (symbol '|')
281371
282−blocks :: PandocMonad m => LP m Blocks
283−blocks = mconcat <$> many block
372+lit :: String -> LP m Inlines
373+lit = pure . str
284374
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
375+doubleQuote :: PandocMonad m => LP m Inlines
376+doubleQuote = do
377+ quoted' doubleQuoted (try $ count 2 $ symbol '`')
378+ (void $ try $ count 2 $ symbol '\'')
379+ <|> quoted' doubleQuoted ((:[]) <$> symbol '“') (void $ symbol '”')
380+ -- the following is used by babel for localized quotes:
381+ <|> quoted' doubleQuoted (try $ sequence [symbol '"', symbol '`'])
382+ (void $ try $ sequence [symbol '"', symbol '\''])
383+ <|> quoted' doubleQuoted ((:[]) <$> symbol '"')
384+ (void $ symbol '"')
291385
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
386+singleQuote :: PandocMonad m => LP m Inlines
387+singleQuote = do
388+ quoted' singleQuoted ((:[]) <$> symbol '`')
389+ (try $ symbol '\'' >>
390+ notFollowedBy (satisfyTok startsWithLetter))
391+ <|> quoted' singleQuoted ((:[]) <$> symbol '‘')
392+ (try $ symbol '’' >>
393+ notFollowedBy (satisfyTok startsWithLetter))
394+ where startsWithLetter (Tok _ Word t) =
395+ case T.uncons t of
396+ Just (c, _) | isLetter c -> True
397+ _ -> False
398+ startsWithLetter _ = False
399+
400+quoted' :: PandocMonad m
401+ => (Inlines -> Inlines)
402+ -> LP m [Tok]
403+ -> LP m ()
404+ -> LP m Inlines
405+quoted' f starter ender = do
406+ startchs <- (T.unpack . untokenize) <$> starter
407+ smart <- extensionEnabled Ext_smart <$> getOption readerExtensions
408+ if smart
409+ then do
410+ ils <- many (notFollowedBy ender >> inline)
411+ (ender >> return (f (mconcat ils))) <|>
412+ (<> mconcat ils) <$>
413+ lit (case startchs of
414+ "``" -> "“"
415+ "`" -> "‘"
416+ cs -> cs)
417+ else lit startchs
296418
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
419+enquote :: PandocMonad m => LP m Inlines
420+enquote = do
421+ skipopts
422+ context <- stateQuoteContext <$> getState
423+ if context == InDoubleQuote
424+ then singleQuoted <$> withQuoteContext InSingleQuote tok
425+ else doubleQuoted <$> withQuoteContext InDoubleQuote tok
310426
311−inBrackets :: Inlines -> Inlines
312−inBrackets x = str "[" <> x <> str "]"
427+doverb :: PandocMonad m => LP m Inlines
428+doverb = do
429+ Tok _ Symbol t <- anySymbol
430+ marker <- case T.uncons t of
431+ Just (c, ts) | T.null ts -> return c
432+ _ -> mzero
433+ (code . T.unpack . untokenize) <$> manyTill (verbTok marker) (symbol marker)
434+
435+verbTok :: PandocMonad m => Char -> LP m Tok
436+verbTok stopchar = do
437+ t@(Tok (lin, col) toktype txt) <- satisfyTok (not . isNewlineTok)
438+ case T.findIndex (== stopchar) txt of
439+ Nothing -> return t
440+ Just i -> do
441+ let (t1, t2) = T.splitAt i txt
442+ inp <- getInput
443+ setInput $ Tok (lin, col + i) Symbol (T.singleton stopchar)
444+ : (totoks (lin, col + i + 1) (T.drop 1 t2)) ++ inp
445+ return $ Tok (lin, col) toktype t1
313446
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
447+dolstinline :: PandocMonad m => LP m Inlines
448+dolstinline = do
449+ options <- option [] keyvals
450+ let classes = maybeToList $ lookup "language" options >>= fromListingsLanguage
451+ Tok _ Symbol t <- anySymbol
452+ marker <- case T.uncons t of
453+ Just (c, ts) | T.null ts -> return c
454+ _ -> mzero
455+ let stopchar = if marker == '{' then '}' else marker
456+ (codeWith ("",classes,[]) . T.unpack . untokenize) <$>
457+ manyTill (verbTok stopchar) (symbol stopchar)
322458
323−guardRaw :: PandocMonad m => LP m ()
324−guardRaw = getOption readerExtensions >>= guard . extensionEnabled Ext_raw_tex
459+keyval :: PandocMonad m => LP m (String, String)
460+keyval = try $ do
461+ Tok _ Word key <- satisfyTok isWordTok
462+ let isSpecSym (Tok _ Symbol t) = t `elem` [".",":","-","|","\\"]
463+ isSpecSym _ = False
464+ val <- option [] $ do
465+ symbol '='
466+ braced <|> (many1 (satisfyTok isWordTok <|> satisfyTok isSpecSym))
467+ optional sp
468+ optional (symbol ',')
469+ optional sp
470+ return (T.unpack key, T.unpack . untokenize $ val)
325471
326−optargs :: PandocMonad m => LP m String
327−optargs = snd <$> withRaw (skipopts *> skipMany (try $ optional sp *> braced))
472+keyvals :: PandocMonad m => LP m [(String, String)]
473+keyvals = try $ symbol '[' >> manyTill keyval (symbol ']')
328474
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
475+accent :: (Char -> String) -> Inlines -> LP m Inlines
476+accent f ils =
477+ case toList ils of
478+ (Str (x:xs) : ys) -> return $ fromList (Str (f x ++ xs) : ys)
479+ [] -> mzero
480+ _ -> return ils
334481
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
482+grave :: Char -> String
483+grave 'A' = "À"
484+grave 'E' = "È"
485+grave 'I' = "Ì"
486+grave 'O' = "Ò"
487+grave 'U' = "Ù"
488+grave 'a' = "à"
489+grave 'e' = "è"
490+grave 'i' = "ì"
491+grave 'o' = "ò"
492+grave 'u' = "ù"
493+grave c = [c]
342494
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− ]
495+acute :: Char -> String
496+acute 'A' = "Á"
497+acute 'E' = "É"
498+acute 'I' = "Í"
499+acute 'O' = "Ó"
500+acute 'U' = "Ú"
501+acute 'Y' = "Ý"
502+acute 'a' = "á"
503+acute 'e' = "é"
504+acute 'i' = "í"
505+acute 'o' = "ó"
506+acute 'u' = "ú"
507+acute 'y' = "ý"
508+acute 'C' = "Ć"
509+acute 'c' = "ć"
510+acute 'L' = "Ĺ"
511+acute 'l' = "ĺ"
512+acute 'N' = "Ń"
513+acute 'n' = "ń"
514+acute 'R' = "Ŕ"
515+acute 'r' = "ŕ"
516+acute 'S' = "Ś"
517+acute 's' = "ś"
518+acute 'Z' = "Ź"
519+acute 'z' = "ź"
520+acute c = [c]
416521
417−graphicsPath :: PandocMonad m => LP m Blocks
418−graphicsPath = do
419− ps <- bgroup *> (manyTill braced egroup)
420− getResourcePath >>= setResourcePath . (++ ps)
421− return mempty
522+circ :: Char -> String
523+circ 'A' = "Â"
524+circ 'E' = "Ê"
525+circ 'I' = "Î"
526+circ 'O' = "Ô"
527+circ 'U' = "Û"
528+circ 'a' = "â"
529+circ 'e' = "ê"
530+circ 'i' = "î"
531+circ 'o' = "ô"
532+circ 'u' = "û"
533+circ 'C' = "Ĉ"
534+circ 'c' = "ĉ"
535+circ 'G' = "Ĝ"
536+circ 'g' = "ĝ"
537+circ 'H' = "Ĥ"
538+circ 'h' = "ĥ"
539+circ 'J' = "Ĵ"
540+circ 'j' = "ĵ"
541+circ 'S' = "Ŝ"
542+circ 's' = "ŝ"
543+circ 'W' = "Ŵ"
544+circ 'w' = "ŵ"
545+circ 'Y' = "Ŷ"
546+circ 'y' = "ŷ"
547+circ c = [c]
422548
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
549+tilde :: Char -> String
550+tilde 'A' = "Ã"
551+tilde 'a' = "ã"
552+tilde 'O' = "Õ"
553+tilde 'o' = "õ"
554+tilde 'I' = "Ĩ"
555+tilde 'i' = "ĩ"
556+tilde 'U' = "Ũ"
557+tilde 'u' = "ũ"
558+tilde 'N' = "Ñ"
559+tilde 'n' = "ñ"
560+tilde c = [c]
441561
442−resetCaption :: PandocMonad m => LP m ()
443−resetCaption = updateState $ \st -> st{ stateCaption = Nothing }
562+umlaut :: Char -> String
563+umlaut 'A' = "Ä"
564+umlaut 'E' = "Ë"
565+umlaut 'I' = "Ï"
566+umlaut 'O' = "Ö"
567+umlaut 'U' = "Ü"
568+umlaut 'a' = "ä"
569+umlaut 'e' = "ë"
570+umlaut 'i' = "ï"
571+umlaut 'o' = "ö"
572+umlaut 'u' = "ü"
573+umlaut c = [c]
444574
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)
575+hungarumlaut :: Char -> String
576+hungarumlaut 'A' = "A̋"
577+hungarumlaut 'E' = "E̋"
578+hungarumlaut 'I' = "I̋"
579+hungarumlaut 'O' = "Ő"
580+hungarumlaut 'U' = "Ű"
581+hungarumlaut 'Y' = "ӳ"
582+hungarumlaut 'a' = "a̋"
583+hungarumlaut 'e' = "e̋"
584+hungarumlaut 'i' = "i̋"
585+hungarumlaut 'o' = "ő"
586+hungarumlaut 'u' = "ű"
587+hungarumlaut 'y' = "ӳ"
588+hungarumlaut c = [c]
455589
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
590+dot :: Char -> String
591+dot 'C' = "Ċ"
592+dot 'c' = "ċ"
593+dot 'E' = "Ė"
594+dot 'e' = "ė"
595+dot 'G' = "Ġ"
596+dot 'g' = "ġ"
597+dot 'I' = "İ"
598+dot 'Z' = "Ż"
599+dot 'z' = "ż"
600+dot c = [c]
601+
602+macron :: Char -> String
603+macron 'A' = "Ā"
604+macron 'E' = "Ē"
605+macron 'I' = "Ī"
606+macron 'O' = "Ō"
607+macron 'U' = "Ū"
608+macron 'a' = "ā"
609+macron 'e' = "ē"
610+macron 'i' = "ī"
611+macron 'o' = "ō"
612+macron 'u' = "ū"
613+macron c = [c]
614+
615+cedilla :: Char -> String
616+cedilla 'c' = "ç"
617+cedilla 'C' = "Ç"
618+cedilla 's' = "ş"
619+cedilla 'S' = "Ş"
620+cedilla 't' = "ţ"
621+cedilla 'T' = "Ţ"
622+cedilla 'e' = "ȩ"
623+cedilla 'E' = "Ȩ"
624+cedilla 'h' = "ḩ"
625+cedilla 'H' = "Ḩ"
626+cedilla 'o' = "o̧"
627+cedilla 'O' = "O̧"
628+cedilla c = [c]
629+
630+hacek :: Char -> String
631+hacek 'A' = "Ǎ"
632+hacek 'a' = "ǎ"
633+hacek 'C' = "Č"
634+hacek 'c' = "č"
635+hacek 'D' = "Ď"
636+hacek 'd' = "ď"
637+hacek 'E' = "Ě"
638+hacek 'e' = "ě"
639+hacek 'G' = "Ǧ"
640+hacek 'g' = "ǧ"
641+hacek 'H' = "Ȟ"
642+hacek 'h' = "ȟ"
643+hacek 'I' = "Ǐ"
644+hacek 'i' = "ǐ"
645+hacek 'j' = "ǰ"
646+hacek 'K' = "Ǩ"
647+hacek 'k' = "ǩ"
648+hacek 'L' = "Ľ"
649+hacek 'l' = "ľ"
650+hacek 'N' = "Ň"
651+hacek 'n' = "ň"
652+hacek 'O' = "Ǒ"
653+hacek 'o' = "ǒ"
654+hacek 'R' = "Ř"
655+hacek 'r' = "ř"
656+hacek 'S' = "Š"
657+hacek 's' = "š"
658+hacek 'T' = "Ť"
659+hacek 't' = "ť"
660+hacek 'U' = "Ǔ"
661+hacek 'u' = "ǔ"
662+hacek 'Z' = "Ž"
663+hacek 'z' = "ž"
664+hacek c = [c]
665+
666+breve :: Char -> String
667+breve 'A' = "Ă"
668+breve 'a' = "ă"
669+breve 'E' = "Ĕ"
670+breve 'e' = "ĕ"
671+breve 'G' = "Ğ"
672+breve 'g' = "ğ"
673+breve 'I' = "Ĭ"
674+breve 'i' = "ĭ"
675+breve 'O' = "Ŏ"
676+breve 'o' = "ŏ"
677+breve 'U' = "Ŭ"
678+breve 'u' = "ŭ"
679+breve c = [c]
463680
464−inlineCommand :: PandocMonad m => LP m Inlines
465−inlineCommand = try $ do
466− (name, raw') <- withRaw anyControlSeq
681+toksToString :: [Tok] -> String
682+toksToString = T.unpack . untokenize
683+
684+mathDisplay :: String -> Inlines
685+mathDisplay = displayMath . trim
686+-- TODO we shouldn't need applyMacros
687+-- mathDisplay p = displayMath <$> (try p >>= applyMacros' . trim)
688+
689+mathInline :: String -> Inlines
690+mathInline = math . trim
691+-- TODO we shouldn't need applyMacros
692+-- mathInline p = math <$> (try p >>= applyMacros')
693+
694+dollarsMath :: PandocMonad m => LP m Inlines
695+dollarsMath = do
696+ symbol '$'
697+ display <- option False (True <$ symbol '$')
698+ contents <- many1Till anyTok (symbol '$')
699+ when display (() <$ symbol '$')
700+ let constructor = if display then mathDisplay else mathInline
701+ return $ constructor $ toksToString contents
702+
703+inlineCommand' :: PandocMonad m => LP m Inlines
704+inlineCommand' = try $ do
705+ cs@(Tok _ CtrlSeq t) <- anyControlSeq
706+ let name = T.drop 1 t
467707 guard $ name /= "begin" && name /= "end"
468− star <- option "" (string "*")
469− let name' = name ++ star
708+ mbstar <- option Nothing (Just <$> symbol '*')
709+ let names = name : maybe [] (const [name <> "*"]) mbstar
710+ optional $ try $ symbol '{' >> symbol '}'
470711 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
712+ guard $ not (isBlockCommand name)
713+ (_, rawargs) <- withRaw
714+ (skipangles *> skipopts *> option "" dimenarg *> many braced)
715+ let rawcommand = T.unpack $ untokenize $
716+ cs : maybe [] (:[]) mbstar ++ rawargs
717+ (guardEnabled Ext_raw_tex >> return (rawInline "latex" rawcommand))
718+ <|> ignore rawcommand
719+ -- transformed <- applyMacros' rawcommand -- TODO or get rid of
720+ -- exts <- getOption readerExtensions
721+ -- if transformed /= rawcommand
722+ -- then parseFromString' inlines transformed
723+ -- else if extensionEnabled Ext_raw_tex exts
724+ -- then return $ rawInline "latex" rawcommand
725+ -- else ignore rawcommand
726+ lookupListDefault raw names inlineCommands
727+
728+tok :: PandocMonad m => LP m Inlines
729+tok = try $ grouped inline <|> inlineCommand' <|> singleChar
730+ where singleChar = do
731+ Tok (lin,col) toktype t <- satisfyTok (tokTypeIn [Word, Symbol])
732+ if T.length t > 1
733+ then do
734+ let (t1, t2) = (T.take 1 t, T.drop 1 t)
735+ inp <- getInput
736+ setInput $ (Tok (lin, col + 1) toktype t2) : inp
737+ return $ str (T.unpack t1)
738+ else return $ str (T.unpack t)
739+
740+opt :: PandocMonad m => LP m Inlines
741+opt = bracketed inline
742+
743+rawopt :: PandocMonad m => LP m Text
744+rawopt = do
745+ symbol '['
746+ inner <- untokenize <$> manyTill anyTok (symbol ']')
747+ optional sp
748+ return $ "[" <> inner <> "]"
749+
750+skipopts :: PandocMonad m => LP m ()
751+skipopts = skipMany rawopt
752+
753+-- eat an optional argument and one or more arguments in braces
754+ignoreInlines :: PandocMonad m => Text -> (Text, LP m Inlines)
755+ignoreInlines name = (name, p)
756+ where p = do oa <- optargs
757+ let rawCommand = '\\' : T.unpack (name <> oa)
758+ let doraw = guardRaw >> return (rawInline "latex" rawCommand)
759+ doraw <|> ignore rawCommand
760+
761+guardRaw :: PandocMonad m => LP m ()
762+guardRaw = getOption readerExtensions >>= guard . extensionEnabled Ext_raw_tex
763+
764+optargs :: PandocMonad m => LP m Text
765+optargs = do
766+ (_, raw) <- withRaw (skipopts *> skipMany (try $ optional sp *> braced))
767+ return $ untokenize raw
768+
769+-- opts in angle brackets are used in beamer
770+rawangle :: PandocMonad m => LP m ()
771+rawangle = try $ do
772+ symbol '<'
773+ () <$ manyTill anyTok (symbol '>')
774+
775+skipangles :: PandocMonad m => LP m ()
776+skipangles = skipMany rawangle
777+
778+ignore :: (Monoid a, PandocMonad m) => String -> ParserT s u m a
779+ignore raw = do
780+ pos <- getPosition
781+ report $ SkippedContent raw pos
782+ return mempty
783+
784+withRaw :: PandocMonad m => LP m a -> LP m (a, [Tok])
785+withRaw parser = do
786+ inp <- getInput
787+ result <- parser
788+ nxt <- option (Tok (0,0) Word "") (lookAhead anyTok)
789+ let raw = takeWhile (/= nxt) inp
790+ return (result, raw)
791+
792+inBrackets :: Inlines -> Inlines
793+inBrackets x = str "[" <> x <> str "]"
794+
795+unescapeURL :: String -> String
796+unescapeURL ('\\':x:xs) | isEscapable x = x:unescapeURL xs
797+ where isEscapable c = c `elem` ("#$%&~_^\\{}" :: String)
798+unescapeURL (x:xs) = x:unescapeURL xs
799+unescapeURL [] = ""
491800
492−isBlockCommand :: String -> Bool
493−isBlockCommand s = s `M.member` (blockCommands :: M.Map String (LP PandocPure Blocks))
801+mathEnvWith :: PandocMonad m
802+ => (Inlines -> a) -> Maybe String -> String -> LP m a
803+mathEnvWith f innerEnv name = f . mathDisplay . inner <$> mathEnv name
804+ where inner x = case innerEnv of
805+ Nothing -> x
806+ Just y -> "\\begin{" ++ y ++ "}\n" ++ x ++
807+ "\\end{" ++ y ++ "}"
808+
809+mathEnv :: PandocMonad m => String -> LP m String
810+mathEnv name = do
811+ skipopts
812+ optional blankline
813+ let endEnv = try $ controlSeq "end" *>
814+ (T.unpack . untokenize <$> braced) >>= guard . (== name)
815+ res <- manyTill anyTok endEnv
816+ return $ stripTrailingNewlines $ T.unpack $ untokenize res
494817
818+inlineEnvironment :: PandocMonad m => LP m Inlines
819+inlineEnvironment = try $ do
820+ controlSeq "begin"
821+ name <- untokenize <$> braced
822+ M.findWithDefault mzero name inlineEnvironments
495823
496−inlineEnvironments :: PandocMonad m => M.Map String (LP m Inlines)
497−inlineEnvironments = M.fromList
498− [ ("displaymath", mathEnvWith id Nothing "displaymath")
824+inlineEnvironments :: PandocMonad m => M.Map Text (LP m Inlines)
825+inlineEnvironments = M.fromList [
826+ ("displaymath", mathEnvWith id Nothing "displaymath")
499827 , ("math", math <$> mathEnv "math")
500828 , ("equation", mathEnvWith id Nothing "equation")
501829 , ("equation*", mathEnvWith id Nothing "equation*")
@@ -511,7 +839,7 @@ inlineEnvironments = M.fromList
511839 , ("alignat*", mathEnvWith id (Just "aligned") "alignat*")
512840 ]
513841
514−inlineCommands :: PandocMonad m => M.Map String (LP m Inlines)
842+inlineCommands :: PandocMonad m => M.Map Text (LP m Inlines)
515843inlineCommands = M.fromList $
516844 [ ("emph", extractSpaces emph <$> tok)
517845 , ("textit", extractSpaces emph <$> tok)
@@ -540,9 +868,9 @@ inlineCommands = M.fromList $
540868 , ("textgreek", tok)
541869 , ("sep", lit ",")
542870 , ("cref", rawInlineOr "cref" (inBrackets <$> tok)) -- from cleveref.sty
543− , ("(", mathInline $ manyTill anyChar (try $ string "\\)"))
544− , ("[", mathDisplay $ manyTill anyChar (try $ string "\\]"))
545− , ("ensuremath", mathInline braced)
871+ , ("(", mathInline . toksToString <$> manyTill anyTok (controlSeq ")"))
872+ , ("[", mathDisplay . toksToString <$> manyTill anyTok (controlSeq "]"))
873+ , ("ensuremath", mathInline . toksToString <$> braced)
546874 , ("texorpdfstring", (\_ x -> x) <$> tok <*> tok)
547875 , ("P", lit "¶")
548876 , ("S", lit "§")
@@ -592,7 +920,7 @@ inlineCommands = M.fromList $
592920 , ("v", option (str "v") $ try $ tok >>= accent hacek)
593921 , ("u", option (str "u") $ try $ tok >>= accent breve)
594922 , ("i", lit "i")
595− , ("\\", linebreak <$ (optional (bracketed inline) *> spaces'))
923+ , ("\\", linebreak <$ (optional (bracketed inline) *> spaces))
596924 , (",", lit "\8198")
597925 , ("@", pure mempty)
598926 , (" ", lit "\160")
@@ -607,73 +935,73 @@ inlineCommands = M.fromList $
607935 , ("verb", doverb)
608936 , ("lstinline", dolstinline)
609937 , ("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)
938+ , ("url", ((unescapeURL . T.unpack . untokenize) <$> braced) >>= \url ->
939+ pure (link url "" (str url)))
940+-- , ("href", (unescapeURL <$> braced <* optional sp) >>= \url ->
941+-- tok >>= \lab ->
942+-- pure (link url "" lab))
943+-- , ("includegraphics", do options <- option [] keyvals
944+-- src <- unescapeURL . removeDoubleQuotes <$> braced
945+-- mkImage options src)
618946 , ("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"))
947+-- , ("cite", citation "cite" NormalCitation False)
948+-- , ("Cite", citation "Cite" NormalCitation False)
949+-- , ("citep", citation "citep" NormalCitation False)
950+-- , ("citep*", citation "citep*" NormalCitation False)
951+-- , ("citeal", citation "citeal" NormalCitation False)
952+-- , ("citealp", citation "citealp" NormalCitation False)
953+-- , ("citealp*", citation "citealp*" NormalCitation False)
954+-- , ("autocite", citation "autocite" NormalCitation False)
955+-- , ("smartcite", citation "smartcite" NormalCitation False)
956+-- , ("footcite", inNote <$> citation "footcite" NormalCitation False)
957+-- , ("parencite", citation "parencite" NormalCitation False)
958+-- , ("supercite", citation "supercite" NormalCitation False)
959+-- , ("footcitetext", inNote <$> citation "footcitetext" NormalCitation False)
960+-- , ("citeyearpar", citation "citeyearpar" SuppressAuthor False)
961+-- , ("citeyear", citation "citeyear" SuppressAuthor False)
962+-- , ("autocite*", citation "autocite*" SuppressAuthor False)
963+-- , ("cite*", citation "cite*" SuppressAuthor False)
964+-- , ("parencite*", citation "parencite*" SuppressAuthor False)
965+-- , ("textcite", citation "textcite" AuthorInText False)
966+-- , ("citet", citation "citet" AuthorInText False)
967+-- , ("citet*", citation "citet*" AuthorInText False)
968+-- , ("citealt", citation "citealt" AuthorInText False)
969+-- , ("citealt*", citation "citealt*" AuthorInText False)
970+-- , ("textcites", citation "textcites" AuthorInText True)
971+-- , ("cites", citation "cites" NormalCitation True)
972+-- , ("autocites", citation "autocites" NormalCitation True)
973+-- , ("footcites", inNote <$> citation "footcites" NormalCitation True)
974+-- , ("parencites", citation "parencites" NormalCitation True)
975+-- , ("supercites", citation "supercites" NormalCitation True)
976+-- , ("footcitetexts", inNote <$> citation "footcitetexts" NormalCitation True)
977+-- , ("Autocite", citation "Autocite" NormalCitation False)
978+-- , ("Smartcite", citation "Smartcite" NormalCitation False)
979+-- , ("Footcite", citation "Footcite" NormalCitation False)
980+-- , ("Parencite", citation "Parencite" NormalCitation False)
981+-- , ("Supercite", citation "Supercite" NormalCitation False)
982+-- , ("Footcitetext", inNote <$> citation "Footcitetext" NormalCitation False)
983+-- , ("Citeyearpar", citation "Citeyearpar" SuppressAuthor False)
984+-- , ("Citeyear", citation "Citeyear" SuppressAuthor False)
985+-- , ("Autocite*", citation "Autocite*" SuppressAuthor False)
986+-- , ("Cite*", citation "Cite*" SuppressAuthor False)
987+-- , ("Parencite*", citation "Parencite*" SuppressAuthor False)
988+-- , ("Textcite", citation "Textcite" AuthorInText False)
989+-- , ("Textcites", citation "Textcites" AuthorInText True)
990+-- , ("Cites", citation "Cites" NormalCitation True)
991+-- , ("Autocites", citation "Autocites" NormalCitation True)
992+-- , ("Footcites", citation "Footcites" NormalCitation True)
993+-- , ("Parencites", citation "Parencites" NormalCitation True)
994+-- , ("Supercites", citation "Supercites" NormalCitation True)
995+-- , ("Footcitetexts", inNote <$> citation "Footcitetexts" NormalCitation True)
996+-- , ("citetext", complexNatbibCitation NormalCitation)
997+-- , ("citeauthor", (try (tok *> optional sp *> controlSeq "citetext") *>
998+-- complexNatbibCitation AuthorInText)
999+-- <|> citation "citeauthor" AuthorInText False)
1000+-- , ("nocite", mempty <$ (citation "nocite" NormalCitation False >>=
1001+-- addMeta "nocite"))
6741002 , ("hypertarget", braced >> tok)
675− -- siuntix
676− , ("SI", dosiunitx)
1003+-- -- siuntix
1004+-- , ("SI", dosiunitx)
6771005 -- hyphenat
6781006 , ("bshyp", lit "\\\173")
6791007 , ("fshyp", lit "/\173")
@@ -700,543 +1028,135 @@ inlineCommands = M.fromList $
7001028ttfamily :: PandocMonad m => LP m Inlines
7011029ttfamily = (code . stringify . toList) <$> tok
7021030
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 "."
720−
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 [] = ""
1031+rawInlineOr :: PandocMonad m => Text -> LP m Inlines -> LP m Inlines
1032+rawInlineOr name' fallback = do
1033+ parseRaw <- extensionEnabled Ext_raw_tex <$> getOption readerExtensions
1034+ if parseRaw
1035+ then rawInline "latex" <$> getRawCommand name'
1036+ else fallback
7261037
727−enquote :: PandocMonad m => LP m Inlines
728−enquote = do
729− skipopts
730− context <- stateQuoteContext <$> getState
731− if context == InDoubleQuote
732− then singleQuoted <$> withQuoteContext InSingleQuote tok
733− else doubleQuoted <$> withQuoteContext InDoubleQuote tok
1038+getRawCommand :: PandocMonad m => Text -> LP m String
1039+getRawCommand name' = do
1040+ (_, rawargs) <- withRaw
1041+ (many (try (optional sp *> opt)) *>
1042+ option "" (try (optional sp *> dimenarg)) *>
1043+ many braced)
1044+ return $ '\\' : T.unpack (name' <> untokenize rawargs)
7341045
735−doverb :: PandocMonad m => LP m Inlines
736−doverb = do
737− marker <- anyChar
738− code <$> manyTill (satisfy (/='\n')) (char marker)
1046+isBlockCommand :: Text -> Bool
1047+isBlockCommand s =
1048+ s `M.member` (blockCommands :: M.Map Text (LP PandocPure Blocks))
7391049
740−dolstinline :: PandocMonad m => LP m Inlines
741−dolstinline = do
742− options <- option [] keyvals
743− let classes = maybeToList $ lookup "language" options >>= fromListingsLanguage
744− marker <- char '{' <|> anyChar
745− codeWith ("",classes,[]) <$> manyTill (satisfy (/='\n')) (char '}' <|> char marker)
1050+lookupListDefault :: (Ord k) => v -> [k] -> M.Map k v -> v
1051+lookupListDefault d = (fromMaybe d .) . lookupList
1052+ where
1053+ lookupList l m = msum $ map (`M.lookup` m) l
7461054
747−doLHSverb :: PandocMonad m => LP m Inlines
748−doLHSverb = codeWith ("",["haskell"],[]) <$> manyTill (satisfy (/='\n')) (char '|')
1055+inline :: PandocMonad m => LP m Inlines
1056+inline = (mempty <$ comment)
1057+ <|> (space <$ whitespace)
1058+ <|> (softbreak <$ endline)
1059+ <|> inlineText
1060+ <|> inlineCommand'
1061+ <|> inlineEnvironment
1062+ <|> inlineGroup
1063+ <|> (symbol '-' *>
1064+ option (str "-") (symbol '-' *>
1065+ option (str "–") (str "—" <$ symbol '-')))
1066+ <|> doubleQuote
1067+ <|> singleQuote
1068+ <|> (str "”" <$ try (symbol '\'' >> symbol '\''))
1069+ <|> (str "”" <$ symbol '”')
1070+ <|> (str "’" <$ symbol '\'')
1071+ <|> (str "’" <$ symbol '’')
1072+ <|> (str "\160" <$ symbol '~')
1073+ <|> dollarsMath
1074+ <|> (guardEnabled Ext_literate_haskell *> symbol '|' *> doLHSverb)
1075+ <|> (str . (:[]) <$> primEscape)
1076+ <|> (do res <- symbolIn "#&~^'`\"[]"
1077+ pos <- getPosition
1078+ let s = T.unpack (untoken res)
1079+ report $ ParsingUnescaped s pos
1080+ return $ str s)
7491081
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]
1082+inlines :: PandocMonad m => LP m Inlines
1083+inlines = mconcat <$> many inline
7641084
765−lit :: String -> LP m Inlines
766−lit = pure . str
1085+-- block elements:
7671086
768−accent :: (Char -> String) -> Inlines -> LP m Inlines
769−accent f ils =
770− case toList ils of
771− (Str (x:xs) : ys) -> return $ fromList (Str (f x ++ xs) : ys)
772− [] -> mzero
773− _ -> return ils
1087+paragraph :: PandocMonad m => LP m Blocks
1088+paragraph = do
1089+ x <- trimInlines . mconcat <$> many1 inline
1090+ if x == mempty
1091+ then return mempty
1092+ else return $ para x
7741093
775−grave :: Char -> String
776−grave 'A' = "À"
777−grave 'E' = "È"
778−grave 'I' = "Ì"
779−grave 'O' = "Ò"
780−grave 'U' = "Ù"
781−grave 'a' = "à"
782−grave 'e' = "è"
783−grave 'i' = "ì"
784−grave 'o' = "ò"
785−grave 'u' = "ù"
786−grave c = [c]
1094+include :: PandocMonad m => LP m Blocks
1095+include = do
1096+ (Tok _ _ name) <- controlSeq "include" <|> controlSeq "input" <|>
1097+ controlSeq "subfile" <|> controlSeq "usepackage"
1098+ skipMany $ bracketed inline -- skip options
1099+ fs <- (map trim . splitBy (==',') . T.unpack . untokenize) <$> braced
1100+ let fs' = if name == "\\usepackage"
1101+ then map (maybeAddExtension ".sty") fs
1102+ else map (maybeAddExtension ".tex") fs
1103+ dirs <- (splitBy (==':') . fromMaybe ".") <$> lookupEnv "TEXINPUTS"
1104+ mconcat <$> mapM (insertIncludedFile blocks (tokenize . T.pack) dirs) fs'
7871105
788−acute :: Char -> String
789−acute 'A' = "Á"
790−acute 'E' = "É"
791−acute 'I' = "Í"
792−acute 'O' = "Ó"
793−acute 'U' = "Ú"
794−acute 'Y' = "Ý"
795−acute 'a' = "á"
796−acute 'e' = "é"
797−acute 'i' = "í"
798−acute 'o' = "ó"
799−acute 'u' = "ú"
800−acute 'y' = "ý"
801−acute 'C' = "Ć"
802−acute 'c' = "ć"
803−acute 'L' = "Ĺ"
804−acute 'l' = "ĺ"
805−acute 'N' = "Ń"
806−acute 'n' = "ń"
807−acute 'R' = "Ŕ"
808−acute 'r' = "ŕ"
809−acute 'S' = "Ś"
810−acute 's' = "ś"
811−acute 'Z' = "Ź"
812−acute 'z' = "ź"
813−acute c = [c]
1106+maybeAddExtension :: String -> FilePath -> FilePath
1107+maybeAddExtension ext fp =
1108+ if null (takeExtension fp)
1109+ then addExtension fp ext
1110+ else fp
8141111
815−circ :: Char -> String
816−circ 'A' = "Â"
817−circ 'E' = "Ê"
818−circ 'I' = "Î"
819−circ 'O' = "Ô"
820−circ 'U' = "Û"
821−circ 'a' = "â"
822−circ 'e' = "ê"
823−circ 'i' = "î"
824−circ 'o' = "ô"
825−circ 'u' = "û"
826−circ 'C' = "Ĉ"
827−circ 'c' = "ĉ"
828−circ 'G' = "Ĝ"
829−circ 'g' = "ĝ"
830−circ 'H' = "Ĥ"
831−circ 'h' = "ĥ"
832−circ 'J' = "Ĵ"
833−circ 'j' = "ĵ"
834−circ 'S' = "Ŝ"
835−circ 's' = "ŝ"
836−circ 'W' = "Ŵ"
837−circ 'w' = "ŵ"
838−circ 'Y' = "Ŷ"
839−circ 'y' = "ŷ"
840−circ c = [c]
841−
842−tilde :: Char -> String
843−tilde 'A' = "Ã"
844−tilde 'a' = "ã"
845−tilde 'O' = "Õ"
846−tilde 'o' = "õ"
847−tilde 'I' = "Ĩ"
848−tilde 'i' = "ĩ"
849−tilde 'U' = "Ũ"
850−tilde 'u' = "ũ"
851−tilde 'N' = "Ñ"
852−tilde 'n' = "ñ"
853−tilde c = [c]
854−
855−umlaut :: Char -> String
856−umlaut 'A' = "Ä"
857−umlaut 'E' = "Ë"
858−umlaut 'I' = "Ï"
859−umlaut 'O' = "Ö"
860−umlaut 'U' = "Ü"
861−umlaut 'a' = "ä"
862−umlaut 'e' = "ë"
863−umlaut 'i' = "ï"
864−umlaut 'o' = "ö"
865−umlaut 'u' = "ü"
866−umlaut c = [c]
867−
868−hungarumlaut :: Char -> String
869−hungarumlaut 'A' = "A̋"
870−hungarumlaut 'E' = "E̋"
871−hungarumlaut 'I' = "I̋"
872−hungarumlaut 'O' = "Ő"
873−hungarumlaut 'U' = "Ű"
874−hungarumlaut 'Y' = "ӳ"
875−hungarumlaut 'a' = "a̋"
876−hungarumlaut 'e' = "e̋"
877−hungarumlaut 'i' = "i̋"
878−hungarumlaut 'o' = "ő"
879−hungarumlaut 'u' = "ű"
880−hungarumlaut 'y' = "ӳ"
881−hungarumlaut c = [c]
882−
883−dot :: Char -> String
884−dot 'C' = "Ċ"
885−dot 'c' = "ċ"
886−dot 'E' = "Ė"
887−dot 'e' = "ė"
888−dot 'G' = "Ġ"
889−dot 'g' = "ġ"
890−dot 'I' = "İ"
891−dot 'Z' = "Ż"
892−dot 'z' = "ż"
893−dot c = [c]
894−
895−macron :: Char -> String
896−macron 'A' = "Ā"
897−macron 'E' = "Ē"
898−macron 'I' = "Ī"
899−macron 'O' = "Ō"
900−macron 'U' = "Ū"
901−macron 'a' = "ā"
902−macron 'e' = "ē"
903−macron 'i' = "ī"
904−macron 'o' = "ō"
905−macron 'u' = "ū"
906−macron c = [c]
907−
908−cedilla :: Char -> String
909−cedilla 'c' = "ç"
910−cedilla 'C' = "Ç"
911−cedilla 's' = "ş"
912−cedilla 'S' = "Ş"
913−cedilla 't' = "ţ"
914−cedilla 'T' = "Ţ"
915−cedilla 'e' = "ȩ"
916−cedilla 'E' = "Ȩ"
917−cedilla 'h' = "ḩ"
918−cedilla 'H' = "Ḩ"
919−cedilla 'o' = "o̧"
920−cedilla 'O' = "O̧"
921−cedilla c = [c]
922−
923−hacek :: Char -> String
924−hacek 'A' = "Ǎ"
925−hacek 'a' = "ǎ"
926−hacek 'C' = "Č"
927−hacek 'c' = "č"
928−hacek 'D' = "Ď"
929−hacek 'd' = "ď"
930−hacek 'E' = "Ě"
931−hacek 'e' = "ě"
932−hacek 'G' = "Ǧ"
933−hacek 'g' = "ǧ"
934−hacek 'H' = "Ȟ"
935−hacek 'h' = "ȟ"
936−hacek 'I' = "Ǐ"
937−hacek 'i' = "ǐ"
938−hacek 'j' = "ǰ"
939−hacek 'K' = "Ǩ"
940−hacek 'k' = "ǩ"
941−hacek 'L' = "Ľ"
942−hacek 'l' = "ľ"
943−hacek 'N' = "Ň"
944−hacek 'n' = "ň"
945−hacek 'O' = "Ǒ"
946−hacek 'o' = "ǒ"
947−hacek 'R' = "Ř"
948−hacek 'r' = "ř"
949−hacek 'S' = "Š"
950−hacek 's' = "š"
951−hacek 'T' = "Ť"
952−hacek 't' = "ť"
953−hacek 'U' = "Ǔ"
954−hacek 'u' = "ǔ"
955−hacek 'Z' = "Ž"
956−hacek 'z' = "ž"
957−hacek c = [c]
958−
959−breve :: Char -> String
960−breve 'A' = "Ă"
961−breve 'a' = "ă"
962−breve 'E' = "Ĕ"
963−breve 'e' = "ĕ"
964−breve 'G' = "Ğ"
965−breve 'g' = "ğ"
966−breve 'I' = "Ĭ"
967−breve 'i' = "ĭ"
968−breve 'O' = "Ŏ"
969−breve 'o' = "ŏ"
970−breve 'U' = "Ŭ"
971−breve 'u' = "ŭ"
972−breve c = [c]
973−
974−tok :: PandocMonad m => LP m Inlines
975−tok = try $ grouped inline <|> inlineCommand <|> str <$> count 1 inlineChar
976−
977−opt :: PandocMonad m => LP m Inlines
978−opt = bracketed inline
979−
980−rawopt :: PandocMonad m => LP m String
981−rawopt = do
982− contents <- bracketed (many1 (noneOf "[]") <|> try (string "\\]") <|>
983− try (string "\\[") <|> rawopt)
984− optional sp
985− return $ "[" ++ contents ++ "]"
986−
987−skipopts :: PandocMonad m => LP m ()
988−skipopts = skipMany rawopt
989−
990−-- opts in angle brackets are used in beamer
991−rawangle :: PandocMonad m => LP m ()
992−rawangle = try $ do
993− char '<'
994− skipMany (noneOf ">")
995− char '>'
996− return ()
997−
998−skipangles :: PandocMonad m => LP m ()
999−skipangles = skipMany rawangle
1000−
1001−inlineText :: PandocMonad m => LP m Inlines
1002−inlineText = str <$> many1 inlineChar
1003−
1004−inlineChar :: PandocMonad m => LP m Char
1005−inlineChar = noneOf "\\$%&~#{}^'`\"‘’“”-[] \t\n"
1006−
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
1013−
1014−inlineEnvironment :: PandocMonad m => LP m Inlines
1015−inlineEnvironment = try $ do
1016− controlSeq "begin"
1017− name <- braced
1018− M.findWithDefault mzero name inlineEnvironments
1019−
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
1052−
1053−----
1054−
1055−maybeAddExtension :: String -> FilePath -> FilePath
1056−maybeAddExtension ext fp =
1057− if null (takeExtension fp)
1058− then addExtension fp ext
1059− else fp
1060−
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'
1077−
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−----
1113−
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)
1112+ignoreBlocks :: PandocMonad m => Text -> (Text, LP m Blocks)
1113+ignoreBlocks name = (name, p)
1114+ where
1115+ p = do oa <- optargs
1116+ let rawCommand = '\\' : T.unpack (name <> oa)
1117+ let doraw = guardRaw >> return (rawBlock "latex" rawCommand)
1118+ doraw <|> ignore rawCommand
11221119
1120+addMeta :: PandocMonad m => ToMetaValue a => String -> a -> LP m ()
1121+addMeta field val = updateState $ \st ->
1122+ st{ stateMeta = addMetaField field val $ stateMeta st }
11231123
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− ]
1124+authors :: PandocMonad m => LP m ()
1125+authors = try $ do
1126+ bgroup
1127+ let oneAuthor = mconcat <$>
1128+ many1 (notFollowedBy' (controlSeq "and") >>
1129+ (inline <|> mempty <$ blockCommand))
1130+ -- skip e.g. \vspace{10pt}
1131+ auths <- sepBy oneAuthor (controlSeq "and")
1132+ egroup
1133+ addMeta "author" (map trimInlines auths)
12241134
1225−figure :: PandocMonad m => LP m Blocks
1226−figure = try $ do
1227− resetCaption
1228− blocks >>= addImageCaption
1135+section :: PandocMonad m => Attr -> Int -> LP m Blocks
1136+section (ident, classes, kvs) lvl = do
1137+ skipopts
1138+ contents <- grouped inline
1139+ lab <- option ident $
1140+ try (spaces >> controlSeq "label"
1141+ >> spaces >> toksToString <$> braced)
1142+ attr' <- registerHeader (lab, classes, kvs) contents
1143+ return $ headerWith attr' lvl contents
12291144
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
1145+blockCommand :: PandocMonad m => LP m Blocks
1146+blockCommand = try $ do
1147+ Tok _ CtrlSeq name <- anyControlSeq
1148+ guard $ name /= "\\begin" && name /= "\\end"
1149+ star <- option "" ("*" <$ symbol '*' <* optional sp)
1150+ let name' = name <> star
1151+ let names = name : [name' | name' /= name]
1152+ let raw = rawBlock "latex" <$> getRawCommand name'
1153+ -- TODO do we still need this?
1154+ -- rawcommand <- getRawCommand name'
1155+ -- transformed <- applyMacros' rawcommand
1156+ -- guard $ transformed /= rawcommand
1157+ -- notFollowedBy $ parseFromString' inlines transformed
1158+ -- parseFromString' blocks transformed
1159+ lookupListDefault raw names blockCommands
12401160
12411161closing :: PandocMonad m => LP m Blocks
12421162closing = do
@@ -1252,321 +1172,691 @@ closing = do
12521172 _ -> mempty
12531173 return $ para (trimInlines contents) <> sigs
12541174
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
1175+blockCommands :: PandocMonad m => M.Map Text (LP m Blocks)
1176+blockCommands = M.fromList $
1177+ [ ("par", mempty <$ skipopts)
1178+ , ("parbox", braced >> grouped blocks)
1179+ , ("title", mempty <$ (skipopts *>
1180+ (grouped inline >>= addMeta "title")
1181+ <|> (grouped block >>= addMeta "title")))
1182+ , ("subtitle", mempty <$ (skipopts *> tok >>= addMeta "subtitle"))
1183+ , ("author", mempty <$ (skipopts *> authors))
1184+ -- -- in letter class, temp. store address & sig as title, author
1185+ , ("address", mempty <$ (skipopts *> tok >>= addMeta "address"))
1186+ , ("signature", mempty <$ (skipopts *> authors))
1187+ , ("date", mempty <$ (skipopts *> tok >>= addMeta "date"))
1188+ -- Koma-script metadata commands
1189+ , ("dedication", mempty <$ (skipopts *> tok >>= addMeta "dedication"))
1190+ -- sectioning
1191+ , ("part", section nullAttr (-1))
1192+ , ("part*", section nullAttr (-1))
1193+ , ("chapter", section nullAttr 0)
1194+ , ("chapter*", section ("",["unnumbered"],[]) 0)
1195+ , ("section", section nullAttr 1)
1196+ , ("section*", section ("",["unnumbered"],[]) 1)
1197+ , ("subsection", section nullAttr 2)
1198+ , ("subsection*", section ("",["unnumbered"],[]) 2)
1199+ , ("subsubsection", section nullAttr 3)
1200+ , ("subsubsection*", section ("",["unnumbered"],[]) 3)
1201+ , ("paragraph", section nullAttr 4)
1202+ , ("paragraph*", section ("",["unnumbered"],[]) 4)
1203+ , ("subparagraph", section nullAttr 5)
1204+ , ("subparagraph*", section ("",["unnumbered"],[]) 5)
1205+ -- beamer slides
1206+ , ("frametitle", section nullAttr 3)
1207+ , ("framesubtitle", section nullAttr 4)
1208+ -- letters
1209+ , ("opening", (para . trimInlines) <$> (skipopts *> tok))
1210+ , ("closing", skipopts *> closing)
1211+ --
1212+ , ("hrule", pure horizontalRule)
1213+ , ("strut", pure mempty)
1214+ , ("rule", skipopts *> tok *> tok *> pure horizontalRule)
1215+-- , ("item", skipopts *> looseItem)
1216+-- , ("documentclass", skipopts *> braced *> preamble)
1217+ , ("centerline", (para . trimInlines) <$> (skipopts *> tok))
1218+-- , ("caption", skipopts *> setCaption)
1219+-- , ("bibliography", mempty <$ (skipopts *> braced >>=
1220+-- addMeta "bibliography" . splitBibs))
1221+-- , ("addbibresource", mempty <$ (skipopts *> braced >>=
1222+-- addMeta "bibliography" . splitBibs))
1223+-- -- includes
1224+-- , ("lstinputlisting", inputListing)
1225+-- , ("graphicspath", graphicsPath)
1226+-- -- hyperlink
1227+ , ("hypertarget", braced >> grouped block)
1228+ ] ++ map ignoreBlocks
1229+ -- these commands will be ignored unless --parse-raw is specified,
1230+ -- in which case they will appear as raw latex blocks
1231+ [ "newcommand", "renewcommand", "newenvironment", "renewenvironment"
1232+ -- newcommand, etc. should be parsed by macro, but we need this
1233+ -- here so these aren't parsed as inline commands to ignore
1234+ , "special", "pdfannot", "pdfstringdef"
1235+ , "bibliographystyle"
1236+ , "maketitle", "makeindex", "makeglossary"
1237+ , "addcontentsline", "addtocontents", "addtocounter"
1238+ -- \ignore{} is used conventionally in literate haskell for definitions
1239+ -- that are to be processed by the compiler but not printed.
1240+ , "ignore"
1241+ , "hyperdef"
1242+ , "markboth", "markright", "markleft"
1243+ , "hspace", "vspace"
1244+ , "newpage"
1245+ , "clearpage"
1246+ , "pagebreak"
1247+ ]
1248+
1249+environments :: PandocMonad m => M.Map Text (LP m Blocks)
1250+environments = M.fromList
1251+ [ ("document", env "document" blocks)
1252+-- , ("abstract", mempty <$ (env "abstract" blocks >>= addMeta "abstract"))
1253+-- , ("letter", env "letter" letterContents)
1254+-- , ("minipage", env "minipage" $
1255+-- skipopts *> spaces' *> optional braced *> spaces' *> blocks)
1256+-- , ("figure", env "figure" $ skipopts *> figure)
1257+-- , ("subfigure", env "subfigure" $ skipopts *> tok *> figure)
1258+-- , ("center", env "center" blocks)
1259+-- , ("longtable", env "longtable" $
1260+-- resetCaption *> simpTable "longtable" False >>= addTableCaption)
1261+-- , ("table", env "table" $
1262+-- resetCaption *> skipopts *> blocks >>= addTableCaption)
1263+-- , ("tabular*", env "tabular" $ simpTable "tabular*" True)
1264+-- , ("tabularx", env "tabularx" $ simpTable "tabularx" True)
1265+-- , ("tabular", env "tabular" $ simpTable "tabular" False)
1266+-- , ("quote", blockQuote <$> env "quote" blocks)
1267+-- , ("quotation", blockQuote <$> env "quotation" blocks)
1268+-- , ("verse", blockQuote <$> env "verse" blocks)
1269+-- , ("itemize", bulletList <$> listenv "itemize" (many item))
1270+-- , ("description", definitionList <$> listenv "description" (many descItem))
1271+-- , ("enumerate", orderedList')
1272+-- , ("alltt", alltt =<< verbEnv "alltt")
1273+-- , ("code", guardEnabled Ext_literate_haskell *>
1274+-- (codeBlockWith ("",["sourceCode","literate","haskell"],[]) <$>
1275+-- verbEnv "code"))
1276+-- , ("comment", mempty <$ verbEnv "comment")
1277+-- , ("verbatim", codeBlock <$> verbEnv "verbatim")
1278+-- , ("Verbatim", fancyverbEnv "Verbatim")
1279+-- , ("BVerbatim", fancyverbEnv "BVerbatim")
1280+-- , ("lstlisting", do attr <- parseListingsOptions <$> option [] keyvals
1281+-- codeBlockWith attr <$> verbEnv "lstlisting")
1282+-- , ("minted", do options <- option [] keyvals
1283+-- lang <- grouped (many1 $ satisfy (/='}'))
1284+-- let kvs = [ (if k == "firstnumber"
1285+-- then "startFrom"
1286+-- else k, v) | (k,v) <- options ]
1287+-- let classes = [ lang | not (null lang) ] ++
1288+-- [ "numberLines" |
1289+-- lookup "linenos" options == Just "true" ]
1290+-- let attr = ("",classes,kvs)
1291+-- codeBlockWith attr <$> verbEnv "minted")
1292+-- , ("obeylines", parseFromString
1293+-- (para . trimInlines . mconcat <$> many inline) =<<
1294+-- intercalate "\\\\\n" . lines <$> verbEnv "obeylines")
1295+-- , ("displaymath", mathEnvWith para Nothing "displaymath")
1296+-- , ("equation", mathEnvWith para Nothing "equation")
1297+-- , ("equation*", mathEnvWith para Nothing "equation*")
1298+-- , ("gather", mathEnvWith para (Just "gathered") "gather")
1299+-- , ("gather*", mathEnvWith para (Just "gathered") "gather*")
1300+-- , ("multline", mathEnvWith para (Just "gathered") "multline")
1301+-- , ("multline*", mathEnvWith para (Just "gathered") "multline*")
1302+-- , ("eqnarray", mathEnvWith para (Just "aligned") "eqnarray")
1303+-- , ("eqnarray*", mathEnvWith para (Just "aligned") "eqnarray*")
1304+-- , ("align", mathEnvWith para (Just "aligned") "align")
1305+-- , ("align*", mathEnvWith para (Just "aligned") "align*")
1306+-- , ("alignat", mathEnvWith para (Just "aligned") "alignat")
1307+-- , ("alignat*", mathEnvWith para (Just "aligned") "alignat*")
1308+-- , ("tikzpicture", rawVerbEnv "tikzpicture")
1309+ ]
12641310
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])
1311+environment :: PandocMonad m => LP m Blocks
1312+environment = do
1313+ controlSeq "begin"
1314+ name <- untokenize <$> braced
1315+ M.findWithDefault mzero name environments
1316+ <|> rawEnv name
12731317
1274−env :: PandocMonad m => String -> LP m a -> LP m a
1318+env :: PandocMonad m => Text -> LP m a -> LP m a
12751319env 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
1320+ (try (controlSeq "end" *> braced >>= guard . (== name) . untokenize)
1321+ <?> ("\\end{" ++ T.unpack name ++ "}"))
13141322
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
1323+rawEnv :: PandocMonad m => Text -> LP m Blocks
1324+rawEnv name = do
1325+ exts <- getOption readerExtensions
1326+ let parseRaw = extensionEnabled Ext_raw_tex exts
1327+ rawOptions <- mconcat <$> many rawopt
1328+ let beginCommand = "\\begin{" <> name <> "}" <> rawOptions
1329+ pos1 <- getPosition
1330+ (bs, raw) <- withRaw $ env name blocks
1331+ if parseRaw
1332+ then return $ rawBlock "latex"
1333+ $ T.unpack $ beginCommand <> untokenize raw
1334+ else do
1335+ unless parseRaw $ do
1336+ report $ SkippedContent (T.unpack beginCommand) pos1
1337+ pos2 <- getPosition
1338+ report $ SkippedContent ("\\end{" ++ T.unpack name ++ "}") pos2
1339+ return bs
1340+
1341+ -- raw' <- applyMacros' $ beginCommand <> untokenize raw
1342+ -- if raw' /= beginCommand ++ raw
1343+ -- then parseFromString' blocks raw'
1344+ -- else if parseRaw
1345+ -- then return $ rawBlock "latex" $ beginCommand ++ raw'
1346+ -- else do
1347+ -- unless parseRaw $ do
1348+ -- report $ SkippedContent beginCommand pos1
1349+ -- pos2 <- getPosition
1350+ -- report $ SkippedContent ("\\end{" ++ name ++ "}") pos2
1351+ -- return bs
13421352
1343−paragraph :: PandocMonad m => LP m Blocks
1344−paragraph = do
1345− x <- trimInlines . mconcat <$> many1 inline
1346− if x == mempty
1347− then return mempty
1348− else return $ para x
1353+block :: PandocMonad m => LP m Blocks
1354+block = (mempty <$ spaces1)
1355+ <|> environment
1356+ <|> include
1357+ -- <|> macro
1358+ <|> blockCommand
1359+ <|> paragraph
1360+ <|> grouped block
13491361
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 ()
1362+blocks :: PandocMonad m => LP m Blocks
1363+blocks = mconcat <$> many block
14991364
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
1365+{-
1366+-- graphicsPath :: PandocMonad m => LP m Blocks
1367+-- graphicsPath = do
1368+-- ps <- bgroup *> (manyTill braced egroup)
1369+-- getResourcePath >>= setResourcePath . (++ ps)
1370+-- return mempty
1371+--
1372+-- addMeta :: PandocMonad m => ToMetaValue a => String -> a -> LP m ()
1373+-- addMeta field val = updateState $ \st ->
1374+-- st{ stateMeta = addMetaField field val $ stateMeta st }
1375+--
1376+-- splitBibs :: String -> [Inlines]
1377+-- splitBibs = map (str . flip replaceExtension "bib" . trim) . splitBy (==',')
1378+--
1379+-- setCaption :: PandocMonad m => LP m Blocks
1380+-- setCaption = do
1381+-- ils <- tok
1382+-- mblabel <- option Nothing $
1383+-- try $ spaces' >> controlSeq "label" >> (Just <$> tok)
1384+-- let ils' = case mblabel of
1385+-- Just lab -> ils <> spanWith
1386+-- ("",[],[("data-label", stringify lab)]) mempty
1387+-- Nothing -> ils
1388+-- updateState $ \st -> st{ stateCaption = Just ils' }
1389+-- return mempty
1390+--
1391+-- resetCaption :: PandocMonad m => LP m ()
1392+-- resetCaption = updateState $ \st -> st{ stateCaption = Nothing }
1393+--
1394+-- mkImage :: PandocMonad m => [(String, String)] -> String -> LP m Inlines
1395+-- mkImage options src = do
1396+-- let replaceTextwidth (k,v) = case numUnit v of
1397+-- Just (num, "\\textwidth") -> (k, showFl (num * 100) ++ "%")
1398+-- _ -> (k, v)
1399+-- let kvs = map replaceTextwidth $ filter (\(k,_) -> k `elem` ["width", "height"]) options
1400+-- let attr = ("",[], kvs)
1401+-- let alt = str "image"
1402+-- case takeExtension src of
1403+-- "" -> do
1404+-- defaultExt <- getOption readerDefaultImageExtension
1405+-- return $ imageWith attr (addExtension src defaultExt) "" alt
1406+-- _ -> return $ imageWith attr src "" alt
1407+--
1408+-- inNote :: Inlines -> Inlines
1409+-- inNote ils =
1410+-- note $ para $ ils <> str "."
1411+--
1412+-
1413+-- -- converts e.g. \SI{1}[\$]{} to "$ 1" or \SI{1}{\euro} to "1 €"
1414+-- dosiunitx :: PandocMonad m => LP m Inlines
1415+-- dosiunitx = do
1416+-- skipopts
1417+-- value <- tok
1418+-- valueprefix <- option "" $ char '[' >> (mconcat <$> manyTill tok (char ']'))
1419+-- unit <- tok
1420+-- let emptyOr160 "" = ""
1421+-- emptyOr160 _ = "\160"
1422+-- return . mconcat $ [valueprefix,
1423+-- emptyOr160 valueprefix,
1424+-- value,
1425+-- emptyOr160 unit,
1426+-- unit]
1427+--
1428+-- skipangles :: PandocMonad m => LP m ()
1429+-- skipangles = skipMany rawangle
1430+--
1431+-- inlineText :: PandocMonad m => LP m Inlines
1432+-- inlineText = str <$> many1 inlineChar
1433+--
1434+-- inlineChar :: PandocMonad m => LP m Char
1435+-- inlineChar = noneOf "\\$%&~#{}^'`\"‘’“”-[] \t\n"
1436+--
1437+--
1438+-- inlineEnvironment :: PandocMonad m => LP m Inlines
1439+-- inlineEnvironment = try $ do
1440+-- controlSeq "begin"
1441+-- name <- braced
1442+-- M.findWithDefault mzero name inlineEnvironments
1443+--
1444+--
1445+-- rawVerbEnv :: PandocMonad m => String -> LP m Blocks
1446+-- rawVerbEnv name = do
1447+-- pos <- getPosition
1448+-- (_, raw) <- withRaw $ verbEnv name
1449+-- let raw' = "\\begin{tikzpicture}" ++ raw
1450+-- exts <- getOption readerExtensions
1451+-- let parseRaw = extensionEnabled Ext_raw_tex exts
1452+-- if parseRaw
1453+-- then return $ rawBlock "latex" raw'
1454+-- else do
1455+-- report $ SkippedContent raw' pos
1456+-- return mempty
1457+--
1458+-- ----
1459+--
1460+-- alltt :: PandocMonad m => String -> LP m Blocks
1461+-- alltt t = walk strToCode <$> parseFromString' blocks
1462+-- (substitute " " "\\ " $ substitute "%" "\\%" $
1463+-- intercalate "\\\\\n" $ lines t)
1464+-- where strToCode (Str s) = Code nullAttr s
1465+-- strToCode x = x
1466+--
1467+-- rawLaTeXBlock :: PandocMonad m => ParserT String ParserState String
1468+-- rawLaTeXBlock = snd <$> try (withRaw (environment <|> blockCommand))
1469+--
1470+-- rawLaTeXInline :: PandocMonad m => ParserT String ParserState Inline
1471+-- rawLaTeXInline = do
1472+-- raw <- (snd <$> withRaw inlineCommand)
1473+-- <|> (snd <$> withRaw inlineEnvironment)
1474+-- <|> (snd <$> withRaw blockCommand)
1475+-- RawInline "latex" <$> applyMacros' raw
1476+--
1477+-- addImageCaption :: PandocMonad m => Blocks -> LP m Blocks
1478+-- addImageCaption = walkM go
1479+-- where go (Image attr alt (src,tit))
1480+-- | not ("fig:" `isPrefixOf` tit) = do
1481+-- mbcapt <- stateCaption <$> getState
1482+-- return $ case mbcapt of
1483+-- Just ils -> Image attr (toList ils) (src, "fig:" ++ tit)
1484+-- Nothing -> Image attr alt (src,tit)
1485+-- go x = return x
1486+--
1487+-- addTableCaption :: PandocMonad m => Blocks -> LP m Blocks
1488+-- addTableCaption = walkM go
1489+-- where go (Table c als ws hs rs) = do
1490+-- mbcapt <- stateCaption <$> getState
1491+-- return $ case mbcapt of
1492+-- Just ils -> Table (toList ils) als ws hs rs
1493+-- Nothing -> Table c als ws hs rs
1494+-- go x = return x
1495+--
1496+--
1497+-- figure :: PandocMonad m => LP m Blocks
1498+-- figure = try $ do
1499+-- resetCaption
1500+-- blocks >>= addImageCaption
1501+--
1502+-- letterContents :: PandocMonad m => LP m Blocks
1503+-- letterContents = do
1504+-- bs <- blocks
1505+-- st <- getState
1506+-- -- add signature (author) and address (title)
1507+-- let addr = case lookupMeta "address" (stateMeta st) of
1508+-- Just (MetaBlocks [Plain xs]) ->
1509+-- para $ trimInlines $ fromList xs
1510+-- _ -> mempty
1511+-- return $ addr <> bs -- sig added by \closing
1512+--
1513+--
1514+-- item :: PandocMonad m => LP m Blocks
1515+-- item = blocks *> controlSeq "item" *> skipopts *> blocks
1516+--
1517+-- looseItem :: PandocMonad m => LP m Blocks
1518+-- looseItem = do
1519+-- ctx <- stateParserContext `fmap` getState
1520+-- if ctx == ListItemState
1521+-- then mzero
1522+-- else return mempty
1523+--
1524+-- descItem :: PandocMonad m => LP m (Inlines, [Blocks])
1525+-- descItem = do
1526+-- blocks -- skip blocks before item
1527+-- controlSeq "item"
1528+-- optional sp
1529+-- ils <- opt
1530+-- bs <- blocks
1531+-- return (ils, [bs])
1532+--
1533+--
1534+-- listenv :: PandocMonad m => String -> LP m a -> LP m a
1535+-- listenv name p = try $ do
1536+-- oldCtx <- stateParserContext `fmap` getState
1537+-- updateState $ \st -> st{ stateParserContext = ListItemState }
1538+-- res <- env name p
1539+-- updateState $ \st -> st{ stateParserContext = oldCtx }
1540+-- return res
1541+--
1542+-- mathEnvWith :: PandocMonad m
1543+-- => (Inlines -> a) -> Maybe String -> String -> LP m a
1544+-- mathEnvWith f innerEnv name = f <$> mathDisplay (inner <$> mathEnv name)
1545+-- where inner x = case innerEnv of
1546+-- Nothing -> x
1547+-- Just y -> "\\begin{" ++ y ++ "}\n" ++ x ++
1548+-- "\\end{" ++ y ++ "}"
1549+--
1550+-- mathEnv :: PandocMonad m => String -> LP m String
1551+-- mathEnv name = do
1552+-- skipopts
1553+-- optional blankline
1554+-- let endEnv = try $ controlSeq "end" *> braced >>= guard . (== name)
1555+-- charMuncher = skipMany comment *>
1556+-- (many1 (noneOf "\\%") <|> try (string "\\%")
1557+-- <|> try (string "\\\\") <|> count 1 anyChar)
1558+-- res <- concat <$> manyTill charMuncher endEnv
1559+-- return $ stripTrailingNewlines res
1560+--
1561+-- verbEnv :: PandocMonad m => String -> LP m String
1562+-- verbEnv name = do
1563+-- skipopts
1564+-- optional blankline
1565+-- let endEnv = try $ controlSeq "end" *> braced >>= guard . (== name)
1566+-- charMuncher = anyChar
1567+-- res <- manyTill charMuncher endEnv
1568+-- return $ stripTrailingNewlines res
1569+--
1570+-- fancyverbEnv :: PandocMonad m => String -> LP m Blocks
1571+-- fancyverbEnv name = do
1572+-- options <- option [] keyvals
1573+-- let kvs = [ (if k == "firstnumber"
1574+-- then "startFrom"
1575+-- else k, v) | (k,v) <- options ]
1576+-- let classes = [ "numberLines" |
1577+-- lookup "numbers" options == Just "left" ]
1578+-- let attr = ("",classes,kvs)
1579+-- codeBlockWith attr <$> verbEnv name
1580+--
1581+-- orderedList' :: PandocMonad m => LP m Blocks
1582+-- orderedList' = try $ do
1583+-- optional sp
1584+-- (_, style, delim) <- option (1, DefaultStyle, DefaultDelim) $
1585+-- try $ char '[' *> anyOrderedListMarker <* char ']'
1586+-- spaces
1587+-- optional $ try $ controlSeq "setlength" *> grouped (controlSeq "itemindent") *> braced
1588+-- spaces
1589+-- start <- option 1 $ try $ do controlSeq "setcounter"
1590+-- grouped (string "enum" *> many1 (oneOf "iv"))
1591+-- optional sp
1592+-- num <- grouped (many1 digit)
1593+-- spaces
1594+-- return (read num + 1 :: Int)
1595+-- bs <- listenv "enumerate" (many item)
1596+-- return $ orderedListWith (start, style, delim) bs
1597+--
1598+-- paragraph :: PandocMonad m => LP m Blocks
1599+-- paragraph = do
1600+-- x <- trimInlines . mconcat <$> many1 inline
1601+-- if x == mempty
1602+-- then return mempty
1603+-- else return $ para x
1604+--
1605+-- preamble :: PandocMonad m => LP m Blocks
1606+-- preamble = mempty <$> manyTill preambleBlock beginDoc
1607+-- where beginDoc = lookAhead $ try $ controlSeq "begin" *> string "{document}"
1608+-- preambleBlock = void comment
1609+-- <|> void sp
1610+-- <|> void blanklines
1611+-- <|> void include
1612+-- <|> void macro
1613+-- <|> void blockCommand
1614+-- <|> void anyControlSeq
1615+-- <|> void braced
1616+-- <|> void anyChar
1617+--
1618+-- -------
1619+--
1620+-- -- citations
1621+--
1622+-- addPrefix :: [Inline] -> [Citation] -> [Citation]
1623+-- addPrefix p (k:ks) = k {citationPrefix = p ++ citationPrefix k} : ks
1624+-- addPrefix _ _ = []
1625+--
1626+-- addSuffix :: [Inline] -> [Citation] -> [Citation]
1627+-- addSuffix s ks@(_:_) =
1628+-- let k = last ks
1629+-- in init ks ++ [k {citationSuffix = citationSuffix k ++ s}]
1630+-- addSuffix _ _ = []
1631+--
1632+-- simpleCiteArgs :: PandocMonad m => LP m [Citation]
1633+-- simpleCiteArgs = try $ do
1634+-- first <- optionMaybe $ toList <$> opt
1635+-- second <- optionMaybe $ toList <$> opt
1636+-- keys <- try $ bgroup *> (manyTill citationLabel egroup)
1637+-- let (pre, suf) = case (first , second ) of
1638+-- (Just s , Nothing) -> (mempty, s )
1639+-- (Just s , Just t ) -> (s , t )
1640+-- _ -> (mempty, mempty)
1641+-- conv k = Citation { citationId = k
1642+-- , citationPrefix = []
1643+-- , citationSuffix = []
1644+-- , citationMode = NormalCitation
1645+-- , citationHash = 0
1646+-- , citationNoteNum = 0
1647+-- }
1648+-- return $ addPrefix pre $ addSuffix suf $ map conv keys
1649+--
1650+-- citationLabel :: PandocMonad m => LP m String
1651+-- citationLabel = optional sp *>
1652+-- (many1 (satisfy isBibtexKeyChar)
1653+-- <* optional sp
1654+-- <* optional (char ',')
1655+-- <* optional sp)
1656+-- where isBibtexKeyChar c = isAlphaNum c || c `elem` (".:;?!`'()/*@_+=-[]" :: String)
1657+--
1658+-- cites :: PandocMonad m => CitationMode -> Bool -> LP m [Citation]
1659+-- cites mode multi = try $ do
1660+-- cits <- if multi
1661+-- then many1 simpleCiteArgs
1662+-- else count 1 simpleCiteArgs
1663+-- let cs = concat cits
1664+-- return $ case mode of
1665+-- AuthorInText -> case cs of
1666+-- (c:rest) -> c {citationMode = mode} : rest
1667+-- [] -> []
1668+-- _ -> map (\a -> a {citationMode = mode}) cs
1669+--
1670+-- citation :: PandocMonad m => String -> CitationMode -> Bool -> LP m Inlines
1671+-- citation name mode multi = do
1672+-- (c,raw) <- withRaw $ cites mode multi
1673+-- return $ cite c (rawInline "latex" $ "\\" ++ name ++ raw)
1674+--
1675+-- complexNatbibCitation :: PandocMonad m => CitationMode -> LP m Inlines
1676+-- complexNatbibCitation mode = try $ do
1677+-- let ils = (toList . trimInlines . mconcat) <$>
1678+-- many (notFollowedBy (oneOf "\\};") >> inline)
1679+-- let parseOne = try $ do
1680+-- skipSpaces
1681+-- pref <- ils
1682+-- cit' <- inline -- expect a citation
1683+-- let citlist = toList cit'
1684+-- cits' <- case citlist of
1685+-- [Cite cs _] -> return cs
1686+-- _ -> mzero
1687+-- suff <- ils
1688+-- skipSpaces
1689+-- optional $ char ';'
1690+-- return $ addPrefix pref $ addSuffix suff cits'
1691+-- (c:cits, raw) <- withRaw $ grouped parseOne
1692+-- return $ cite (c{ citationMode = mode }:cits)
1693+-- (rawInline "latex" $ "\\citetext" ++ raw)
1694+--
1695+-- -- tables
1696+--
1697+-- parseAligns :: PandocMonad m => LP m [(Alignment, Double, (String, String))]
1698+-- parseAligns = try $ do
1699+-- bgroup
1700+-- let maybeBar = skipMany $ sp <|> () <$ char '|' <|> () <$ (char '@' >> braced)
1701+-- maybeBar
1702+-- let cAlign = AlignCenter <$ char 'c'
1703+-- let lAlign = AlignLeft <$ char 'l'
1704+-- let rAlign = AlignRight <$ char 'r'
1705+-- let parAlign = AlignLeft <$ char 'p'
1706+-- -- algins from tabularx
1707+-- let xAlign = AlignLeft <$ char 'X'
1708+-- let mAlign = AlignLeft <$ char 'm'
1709+-- let bAlign = AlignLeft <$ char 'b'
1710+-- let alignChar = cAlign <|> lAlign <|> rAlign <|> parAlign
1711+-- <|> xAlign <|> mAlign <|> bAlign
1712+-- let alignPrefix = char '>' >> braced
1713+-- let alignSuffix = char '<' >> braced
1714+-- let colWidth = try $ do
1715+-- char '{'
1716+-- ds <- many1 (oneOf "0123456789.")
1717+-- spaces
1718+-- string "\\linewidth"
1719+-- char '}'
1720+-- case safeRead ds of
1721+-- Just w -> return w
1722+-- Nothing -> return 0.0
1723+-- let alignSpec = do
1724+-- spaces
1725+-- pref <- option "" alignPrefix
1726+-- spaces
1727+-- al <- alignChar
1728+-- width <- colWidth <|> option 0.0 (do s <- braced
1729+-- pos <- getPosition
1730+-- report $ SkippedContent s pos
1731+-- return 0.0)
1732+-- spaces
1733+-- suff <- option "" alignSuffix
1734+-- return (al, width, (pref, suff))
1735+-- aligns' <- sepEndBy alignSpec maybeBar
1736+-- spaces
1737+-- egroup
1738+-- spaces
1739+-- return $ aligns'
1740+--
1741+-- hline :: PandocMonad m => LP m ()
1742+-- hline = try $ do
1743+-- spaces'
1744+-- controlSeq "hline" <|>
1745+-- -- booktabs rules:
1746+-- controlSeq "toprule" <|>
1747+-- controlSeq "bottomrule" <|>
1748+-- controlSeq "midrule" <|>
1749+-- controlSeq "endhead" <|>
1750+-- controlSeq "endfirsthead"
1751+-- spaces'
1752+-- optional $ bracketed (many1 (satisfy (/=']')))
1753+-- return ()
1754+--
1755+-- lbreak :: PandocMonad m => LP m ()
1756+-- lbreak = () <$ try (spaces' *>
1757+-- (controlSeq "\\" <|> controlSeq "tabularnewline") <*
1758+-- spaces')
1759+--
1760+-- amp :: PandocMonad m => LP m ()
1761+-- amp = () <$ try (spaces' *> char '&' <* spaces')
1762+--
1763+-- parseTableRow :: PandocMonad m
1764+-- => String -- ^ table environment name
1765+-- -> [(String, String)] -- ^ pref/suffixes
1766+-- -> LP m [Blocks]
1767+-- parseTableRow envname prefsufs = try $ do
1768+-- let cols = length prefsufs
1769+-- let tableCellRaw = concat <$> many
1770+-- (do notFollowedBy amp
1771+-- notFollowedBy lbreak
1772+-- notFollowedBy $ () <$ try (string ("\\end{" ++ envname ++ "}"))
1773+-- many1 (noneOf "&%\n\r\\")
1774+-- <|> try (string "\\&")
1775+-- <|> count 1 anyChar)
1776+-- let plainify bs = case toList bs of
1777+-- [Para ils] -> plain (fromList ils)
1778+-- _ -> bs
1779+-- rawcells <- sepBy1 tableCellRaw amp
1780+-- guard $ length rawcells == cols
1781+-- let rawcells' = zipWith (\c (p, s) -> p ++ trim c ++ s) rawcells prefsufs
1782+-- let tableCell = plainify <$> blocks
1783+-- cells' <- mapM (parseFromString' tableCell) rawcells'
1784+-- let numcells = length cells'
1785+-- guard $ numcells <= cols && numcells >= 1
1786+-- guard $ cells' /= [mempty]
1787+-- -- note: a & b in a three-column table leaves an empty 3rd cell:
1788+-- let cells'' = cells' ++ replicate (cols - numcells) mempty
1789+-- spaces'
1790+-- return cells''
1791+--
1792+-- spaces' :: PandocMonad m => LP m ()
1793+-- spaces' = spaces *> skipMany (comment *> spaces)
1794+--
1795+-- simpTable :: PandocMonad m => String -> Bool -> LP m Blocks
1796+-- simpTable envname hasWidthParameter = try $ do
1797+-- when hasWidthParameter $ () <$ (spaces' >> tok)
1798+-- skipopts
1799+-- colspecs <- parseAligns
1800+-- let (aligns, widths, prefsufs) = unzip3 colspecs
1801+-- let cols = length colspecs
1802+-- optional $ controlSeq "caption" *> skipopts *> setCaption
1803+-- optional lbreak
1804+-- spaces'
1805+-- skipMany hline
1806+-- spaces'
1807+-- header' <- option [] $ try (parseTableRow envname prefsufs <*
1808+-- lbreak <* many1 hline)
1809+-- spaces'
1810+-- rows <- sepEndBy (parseTableRow envname prefsufs)
1811+-- (lbreak <* optional (skipMany hline))
1812+-- spaces'
1813+-- optional $ controlSeq "caption" *> skipopts *> setCaption
1814+-- optional lbreak
1815+-- spaces'
1816+-- let header'' = if null header'
1817+-- then replicate cols mempty
1818+-- else header'
1819+-- lookAhead $ controlSeq "end" -- make sure we're at end
1820+-- return $ table mempty (zip aligns widths) header'' rows
1821+--
1822+-- removeDoubleQuotes :: String -> String
1823+-- removeDoubleQuotes ('"':xs) =
1824+-- case reverse xs of
1825+-- '"':ys -> reverse ys
1826+-- _ -> '"':xs
1827+-- removeDoubleQuotes xs = xs
1828+--
1829+-- inputListing :: PandocMonad m => LP m Blocks
1830+-- inputListing = do
1831+-- pos <- getPosition
1832+-- options <- option [] keyvals
1833+-- f <- filter (/='"') <$> braced
1834+-- dirs <- (splitBy (==':') . fromMaybe ".") <$> lookupEnv "TEXINPUTS"
1835+-- mbCode <- readFileFromDirs dirs f
1836+-- codeLines <- case mbCode of
1837+-- Just s -> return $ lines s
1838+-- Nothing -> do
1839+-- report $ CouldNotLoadIncludeFile f pos
1840+-- return []
1841+-- let (ident,classes,kvs) = parseListingsOptions options
1842+-- let language = case lookup "language" options >>= fromListingsLanguage of
1843+-- Just l -> [l]
1844+-- Nothing -> take 1 $ languagesByExtension (takeExtension f)
1845+-- let firstline = fromMaybe 1 $ lookup "firstline" options >>= safeRead
1846+-- let lastline = fromMaybe (length codeLines) $
1847+-- lookup "lastline" options >>= safeRead
1848+-- let codeContents = intercalate "\n" $ take (1 + lastline - firstline) $
1849+-- drop (firstline - 1) codeLines
1850+-- return $ codeBlockWith (ident,ordNub (classes ++ language),kvs) codeContents
1851+--
1852+-- parseListingsOptions :: [(String, String)] -> Attr
1853+-- parseListingsOptions options =
1854+-- let kvs = [ (if k == "firstnumber"
1855+-- then "startFrom"
1856+-- else k, v) | (k,v) <- options ]
1857+-- classes = [ "numberLines" |
1858+-- lookup "numbers" options == Just "left" ]
1859+-- ++ maybeToList (lookup "language" options
1860+-- >>= fromListingsLanguage)
1861+-- in (fromMaybe "" (lookup "label" options), classes, kvs)
1862+-}