git.iko.soy/typeable/pandoc
on master help sign in
Various minor cleanups and refactoring (#6117)

* Use concatMap instead of reimplementing it * Replace an unnecessary multi-way if with a regular if * Use sortOn instead of sortBy and comparing * Use guards instead of lots of indents for if and else * Remove redundant do blocks * Extract common functions from both branches of maybe Whenever both the Nothing and the Just branch of maybe do the same function, do that function on the result of maybe instead. * Use fmap instead of reimplementing it from maybe * Use negative forms instead of negating the positive forms * Use mapMaybe instead of mapping and then using catMaybes * Use zipWith instead of mapping over the result of zip * Use unwords instead of reimplementing it * Use <$ instead of <$> and const * Replace case of Bool with if and else * Use find instead of listToMaybe and filter * Use zipWithM instead of mapM and zip * Inline lambda wrappers into the real functions * We get zipWithM from Text.Pandoc.Writers.Shared * Use maybe instead of fromMaybe and fmap I'm not sure how this one slipped past me. * Increase a bit of indentation

commita5a3ac994618d71ecaf2e8bd40251d792edc9c22 authorJoseph C. Sible <josephcsible@users.noreply.github.com> dateFri 7 Feb 2020, 02:38 (7 years ago) parent013a164
16 files changed+59−66
src/Text/Pandoc/PDF.hs+1−4 src/Text/Pandoc/Readers/CommonMark.hs+1−1 src/Text/Pandoc/Readers/DocBook.hs+1−1 src/Text/Pandoc/Readers/Docx.hs+3−3 src/Text/Pandoc/Readers/Docx/Parse.hs+1−2 src/Text/Pandoc/Readers/DokuWiki.hs+1−1 src/Text/Pandoc/Readers/JATS.hs+1−1 src/Text/Pandoc/Readers/Man.hs+13−13 src/Text/Pandoc/Readers/RST.hs+1−1 src/Text/Pandoc/Readers/Vimwiki.hs+9−9 src/Text/Pandoc/Shared.hs+3−4 src/Text/Pandoc/Writers/Markdown.hs+10−11 src/Text/Pandoc/Writers/Powerpoint/Output.hs+5−5 src/Text/Pandoc/Writers/Powerpoint/Presentation.hs+3−3 src/Text/Pandoc/Writers/XWiki.hs+3−4 test/Tests/Command.hs+3−3
src/Text/Pandoc/PDF.hs+1−4
@@ -440,10 +440,7 @@ html2pdf verbosity program args source = do
440440 -- We read PDF as a strict bytestring to make sure that the
441441 -- temp directory is removed on Windows.
442442 -- See https://github.com/jgm/pandoc/issues/1192.
443− then do
444− res <- Just . BL.fromChunks . (:[]) <$>
445− BS.readFile pdfFile
446− return res
443+ then Just . BL.fromChunks . (:[]) <$> BS.readFile pdfFile
447444 else return Nothing
448445 return $ case (exit, mbPdf) of
449446 (ExitFailure _, _) -> Left out
src/Text/Pandoc/Readers/CommonMark.hs+1−1
@@ -177,7 +177,7 @@ addInlines :: ReaderOptions -> [Node] -> [Inline]
177177addInlines opts = foldr (addInline opts) []
178178
179179addInline :: ReaderOptions -> Node -> [Inline] -> [Inline]
180−addInline opts (Node _ (TEXT t) _) = (foldr ((++) . toinl) [] clumps ++)
180+addInline opts (Node _ (TEXT t) _) = (concatMap toinl clumps ++)
181181 where clumps = T.groupBy samekind t
182182 samekind ' ' ' ' = True
183183 samekind ' ' _ = False
src/Text/Pandoc/Readers/DocBook.hs+1−1
@@ -941,7 +941,7 @@ elementToStr x = x
941941parseInline :: PandocMonad m => Content -> DB m Inlines
942942parseInline (Text (CData _ s _)) = return $ text $ T.pack s
943943parseInline (CRef ref) =
944− return $ maybe (text $ T.toUpper $ T.pack ref) (text . T.pack) $ lookupEntity ref
944+ return $ text $ maybe (T.toUpper $ T.pack ref) T.pack $ lookupEntity ref
945945parseInline (Elem e) =
946946 case qName (elName e) of
947947 "equation" -> equation e displayMath
src/Text/Pandoc/Readers/Docx.hs+3−3
@@ -528,9 +528,9 @@ extraInfo :: (Eq (StyleName a), PandocMonad m, HasStyleName a)
528528 => (Attr -> i -> i) -> a -> DocxContext m (i -> i)
529529extraInfo f s = do
530530 opts <- asks docxOptions
531− return $ if | isEnabled Ext_styles opts
532− -> f ("", [], [("custom-style", fromStyleName $ getStyleName s)])
533− | otherwise -> id
531+ return $ if isEnabled Ext_styles opts
532+ then f ("", [], [("custom-style", fromStyleName $ getStyleName s)])
533+ else id
534534
535535parStyleToTransform :: PandocMonad m => ParagraphStyle -> DocxContext m (Blocks -> Blocks)
536536parStyleToTransform pPr
src/Text/Pandoc/Readers/Docx/Parse.hs+1−2
@@ -347,8 +347,7 @@ getDocumentXmlPath zf = do
347347 entry <- findEntryByPath "_rels/.rels" zf
348348 relsElem <- (parseXMLDoc . UTF8.toStringLazy . fromEntry) entry
349349 let rels = filterChildrenName (\n -> qName n == "Relationship") relsElem
350− rel <- listToMaybe $
351− filter (\e -> findAttr (QName "Type" Nothing Nothing) e ==
350+ rel <- find (\e -> findAttr (QName "Type" Nothing Nothing) e ==
352351 Just "http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument")
353352 rels
354353 fp <- findAttr (QName "Target" Nothing Nothing) rel
src/Text/Pandoc/Readers/DokuWiki.hs+1−1
@@ -472,7 +472,7 @@ table = do
472472 let (headerRow, body) = if firstSeparator == '^'
473473 then (head rows, tail rows)
474474 else ([], rows)
475− let attrs = const (AlignDefault, 0.0) <$> transpose rows
475+ let attrs = (AlignDefault, 0.0) <$ transpose rows
476476 pure $ B.table mempty attrs headerRow body
477477
478478tableRows :: PandocMonad m => DWParser m [[B.Blocks]]
src/Text/Pandoc/Readers/JATS.hs+1−1
@@ -443,7 +443,7 @@ elementToStr x = x
443443parseInline :: PandocMonad m => Content -> JATS m Inlines
444444parseInline (Text (CData _ s _)) = return $ text $ T.pack s
445445parseInline (CRef ref) =
446− return $ maybe (text $ T.toUpper $ T.pack ref) text $ T.pack <$> lookupEntity ref
446+ return . text . maybe (T.toUpper $ T.pack ref) T.pack $ lookupEntity ref
447447parseInline (Elem e) =
448448 case qName (elName e) of
449449 "italic" -> emph <$> innerInlines
src/Text/Pandoc/Readers/Man.hs+13−13
@@ -234,22 +234,22 @@ linePartsToInlines = go False
234234 go mono (RoffStr s : xs)
235235 | mono = code s <> go mono xs
236236 | otherwise = text s <> go mono xs
237− go mono (Font fs: xs) =
238− if litals > 0 && litals >= lbolds && litals >= lmonos
239− then emph (go mono (Font fs{ fontItalic = False } :
237+ go mono (Font fs: xs)
238+ | litals > 0 && litals >= lbolds && litals >= lmonos
239+ = emph (go mono (Font fs{ fontItalic = False } :
240240 map (adjustFontSpec (\s -> s{ fontItalic = False }))
241241 itals)) <>
242242 go mono italsrest
243− else if lbolds > 0 && lbolds >= lmonos
244− then strong (go mono (Font fs{ fontBold = False } :
245− map (adjustFontSpec (\s -> s{ fontBold = False }))
246− bolds)) <>
247− go mono boldsrest
248− else if lmonos > 0
249− then go True (Font fs{ fontMonospace = False } :
250− map (adjustFontSpec (\s -> s { fontMonospace = False }))
251− monos) <> go mono monosrest
252− else go mono xs
243+ | lbolds > 0 && lbolds >= lmonos
244+ = strong (go mono (Font fs{ fontBold = False } :
245+ map (adjustFontSpec (\s -> s{ fontBold = False }))
246+ bolds)) <>
247+ go mono boldsrest
248+ | lmonos > 0
249+ = go True (Font fs{ fontMonospace = False } :
250+ map (adjustFontSpec (\s -> s { fontMonospace = False }))
251+ monos) <> go mono monosrest
252+ | otherwise = go mono xs
253253 where
254254 adjustFontSpec f (Font fspec) = Font (f fspec)
255255 adjustFontSpec _ x = x
src/Text/Pandoc/Readers/RST.hs+1−1
@@ -952,7 +952,7 @@ unicodeTransform t
952952 $ extractUnicodeChar zs
953953
954954extractUnicodeChar :: Text -> Maybe (Char, Text)
955−extractUnicodeChar s = maybe Nothing (\c -> Just (c,rest)) mbc
955+extractUnicodeChar s = fmap (\c -> (c,rest)) mbc
956956 where (ds,rest) = T.span isHexDigit s
957957 mbc = safeRead ("'\\x" <> ds <> "'")
958958
src/Text/Pandoc/Readers/Vimwiki.hs+9−9
@@ -546,21 +546,21 @@ link :: PandocMonad m => VwParser m Inlines
546546link = try $ do
547547 string "[["
548548 contents <- lookAhead $ manyTillChar anyChar (string "]]")
549− case T.any (== '|') contents of
550− False -> do
551− manyTill anyChar (string "]]")
552−-- not using try here because [[hell]o]] is not rendered as a link in vimwiki
553− let tit = if isURI contents
554− then ""
555− else "wikilink"
556− return $ B.link (procLink contents) tit (B.str contents)
557− True -> do
549+ if T.any (== '|') contents
550+ then do
558551 url <- manyTillChar anyChar $ char '|'
559552 lab <- mconcat <$> manyTill inline (string "]]")
560553 let tit = if isURI url
561554 then ""
562555 else "wikilink"
563556 return $ B.link (procLink url) tit lab
557+ else do
558+ manyTill anyChar (string "]]")
559+-- not using try here because [[hell]o]] is not rendered as a link in vimwiki
560+ let tit = if isURI contents
561+ then ""
562+ else "wikilink"
563+ return $ B.link (procLink contents) tit (B.str contents)
564564
565565image :: PandocMonad m => VwParser m Inlines
566566image = try $ do
src/Text/Pandoc/Shared.hs+3−4
@@ -115,8 +115,7 @@ import qualified Data.Bifunctor as Bifunctor
115115import Data.Char (isAlpha, isLower, isSpace, isUpper, toLower, isAlphaNum,
116116 generalCategory, GeneralCategory(NonSpacingMark,
117117 SpacingCombiningMark, EnclosingMark, ConnectorPunctuation))
118−import Data.List (find, intercalate, intersperse, stripPrefix, sortBy)
119−import Data.Ord (comparing)
118+import Data.List (find, intercalate, intersperse, stripPrefix, sortOn)
120119import qualified Data.Map as M
121120import Data.Maybe (mapMaybe, fromMaybe)
122121import Data.Monoid (Any (..))
@@ -621,7 +620,7 @@ headerLtEq _ _ = False
621620uniqueIdent :: Extensions -> [Inline] -> Set.Set T.Text -> T.Text
622621uniqueIdent exts title' usedIdents =
623622 if baseIdent `Set.member` usedIdents
624− then case find (\x -> not $ numIdent x `Set.member` usedIdents)
623+ then case find (\x -> numIdent x `Set.notMember` usedIdents)
625624 ([1..60000] :: [Int]) of
626625 Just x -> numIdent x
627626 Nothing -> baseIdent
@@ -799,7 +798,7 @@ filterIpynbOutput mode = walk go
799798 -> Div (ident, ("output":os), kvs) bs
800799 | otherwise -> Div (ident, ("output":os), kvs) $
801800 walk removeANSI $
802− take 1 $ sortBy (comparing rank) bs
801+ take 1 $ sortOn rank bs
803802 where
804803 rank (RawBlock (Format "html") _)
805804 | fmt == Format "html" = (1 :: Int)
src/Text/Pandoc/Writers/Markdown.hs+10−11
@@ -25,7 +25,7 @@ import Data.Char (isAlphaNum)
2525import Data.Default
2626import Data.List (find, intersperse, sortBy, transpose)
2727import qualified Data.Map as M
28−import Data.Maybe (fromMaybe, catMaybes)
28+import Data.Maybe (fromMaybe, mapMaybe)
2929import Data.Ord (comparing)
3030import qualified Data.Set as Set
3131import Data.Text (Text)
@@ -121,7 +121,7 @@ mmdTitleBlock (Context hashmap) =
121121 | null xs -> empty
122122 | otherwise -> k' <> ":" <> space <>
123123 hcat (intersperse "; " $
124− catMaybes $ map fromVal xs)
124+ mapMaybe fromVal xs)
125125 (k', SimpleVal x)
126126 | isEmpty x -> empty
127127 | otherwise -> k' <> ":" <> space <>
@@ -256,7 +256,7 @@ keyToMarkdown opts (label', (src, tit), attr) = do
256256notesToMarkdown :: PandocMonad m => WriterOptions -> [[Block]] -> MD m (Doc Text)
257257notesToMarkdown opts notes = do
258258 n <- gets stNoteNum
259− notes' <- mapM (\(num, note) -> noteToMarkdown opts num note) (zip [n..] notes)
259+ notes' <- zipWithM (noteToMarkdown opts) [n..] notes
260260 modify $ \st -> st { stNoteNum = stNoteNum st + length notes }
261261 return $ vsep notes'
262262
@@ -647,8 +647,7 @@ blockToMarkdown' opts (OrderedList (start,sty,delim) items) = do
647647 then m <> T.replicate (3 - T.length m) " "
648648 else m) markers
649649 contents <- inList $
650− mapM (\(item, num) -> orderedListItemToMarkdown opts item num) $
651− zip markers' items
650+ zipWithM (orderedListItemToMarkdown opts) markers' items
652651 return $ (if isTightList items then vcat else vsep) contents <> blankline
653652blockToMarkdown' opts (DefinitionList items) = do
654653 contents <- inList $ mapM (definitionListItemToMarkdown opts) items
@@ -680,11 +679,11 @@ pipeTable headless aligns rawHeaders rawRows = do
680679 hcat (intersperse (literal "|") $
681680 zipWith3 blockFor aligns widths (map chomp cs))
682681 <> literal "|"
683− let toborder (a, w) = literal $ case a of
684− AlignLeft -> ":" <> T.replicate (w + 1) "-"
685− AlignCenter -> ":" <> T.replicate w "-" <> ":"
686− AlignRight -> T.replicate (w + 1) "-" <> ":"
687− AlignDefault -> T.replicate (w + 2) "-"
682+ let toborder a w = literal $ case a of
683+ AlignLeft -> ":" <> T.replicate (w + 1) "-"
684+ AlignCenter -> ":" <> T.replicate w "-" <> ":"
685+ AlignRight -> T.replicate (w + 1) "-" <> ":"
686+ AlignDefault -> T.replicate (w + 2) "-"
688687 -- note: pipe tables can't completely lack a
689688 -- header; for a headerless table, we need a header of empty cells.
690689 -- see jgm/pandoc#1996.
@@ -692,7 +691,7 @@ pipeTable headless aligns rawHeaders rawRows = do
692691 then torow (replicate (length aligns) empty)
693692 else torow rawHeaders
694693 let border = nowrap $ literal "|" <> hcat (intersperse (literal "|") $
695− map toborder $ zip aligns widths) <> literal "|"
694+ zipWith toborder aligns widths) <> literal "|"
696695 let body = vcat $ map torow rawRows
697696 return $ header $$ border $$ body
698697
src/Text/Pandoc/Writers/Powerpoint/Output.hs+5−5
@@ -249,7 +249,7 @@ presentationToArchiveP p@(Presentation docProps slides) = do
249249 filePaths <- patternsToFilePaths $ inheritedPatterns p
250250
251251 -- make sure all required files are available:
252− let missingFiles = filter (\fp -> not (fp `elem` filePaths)) requiredFiles
252+ let missingFiles = filter (`notElem` filePaths) requiredFiles
253253 unless (null missingFiles)
254254 (throwError $
255255 PandocSomeError $
@@ -1539,15 +1539,15 @@ slideToSlideRelEntry slide = do
15391539 element <- slideToSlideRelElement slide
15401540 elemToEntry ("ppt/slides/_rels/" <> idNumToFilePath idNum <> ".rels") element
15411541
1542−linkRelElement :: PandocMonad m => Int -> LinkTarget -> P m Element
1543−linkRelElement rIdNum (InternalTarget targetId) = do
1542+linkRelElement :: PandocMonad m => (Int, LinkTarget) -> P m Element
1543+linkRelElement (rIdNum, InternalTarget targetId) = do
15441544 targetIdNum <- getSlideIdNum targetId
15451545 return $
15461546 mknode "Relationship" [ ("Id", "rId" <> show rIdNum)
15471547 , ("Type", "http://schemas.openxmlformats.org/officeDocument/2006/relationships/slide")
15481548 , ("Target", "slide" <> show targetIdNum <> ".xml")
15491549 ] ()
1550−linkRelElement rIdNum (ExternalTarget (url, _)) = do
1550+linkRelElement (rIdNum, ExternalTarget (url, _)) = do
15511551 return $
15521552 mknode "Relationship" [ ("Id", "rId" <> show rIdNum)
15531553 , ("Type", "http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink")
@@ -1556,7 +1556,7 @@ linkRelElement rIdNum (ExternalTarget (url, _)) = do
15561556 ] ()
15571557
15581558linkRelElements :: PandocMonad m => M.Map Int LinkTarget -> P m [Element]
1559−linkRelElements mp = mapM (\(n, lnk) -> linkRelElement n lnk) (M.toList mp)
1559+linkRelElements mp = mapM linkRelElement (M.toList mp)
15601560
15611561mediaRelElement :: MediaInfo -> Element
15621562mediaRelElement mInfo =
src/Text/Pandoc/Writers/Powerpoint/Presentation.hs+3−3
@@ -712,8 +712,8 @@ blocksToSlide blks = do
712712 slideLevel <- asks envSlideLevel
713713 blocksToSlide' slideLevel blks' spkNotes
714714
715−makeNoteEntry :: Int -> [Block] -> [Block]
716−makeNoteEntry n blks =
715+makeNoteEntry :: (Int, [Block]) -> [Block]
716+makeNoteEntry (n, blks) =
717717 let enum = Str (tshow n <> ".")
718718 in
719719 case blks of
@@ -742,7 +742,7 @@ makeEndNotesSlideBlocks = do
742742 ls -> ls
743743 ident = Shared.uniqueIdent exts title anchorSet
744744 hdr = Header slideLevel (ident, [], []) title
745− blks = concatMap (\(n, bs) -> makeNoteEntry n bs) $
745+ blks = concatMap makeNoteEntry $
746746 M.toList noteIds
747747 in return $ hdr : blks
748748
src/Text/Pandoc/Writers/XWiki.hs+3−4
@@ -54,10 +54,9 @@ type XWikiReader m = ReaderT WriterState m
5454
5555-- | Convert Pandoc to XWiki.
5656writeXWiki :: PandocMonad m => WriterOptions -> Pandoc -> m Text
57−writeXWiki _ (Pandoc _ blocks) = do
57+writeXWiki _ (Pandoc _ blocks) =
5858 let env = WriterState { listLevel = "" }
59− body <- runReaderT (blockListToXWiki blocks) env
60− return $ body
59+ in runReaderT (blockListToXWiki blocks) env
6160
6261-- | Concatenates strings with line breaks between them.
6362vcat :: [Text] -> Text
@@ -219,7 +218,7 @@ inlineToXWiki (Link (id', _, _) txt (src, _)) = do
219218inlineToXWiki (Image _ alt (source, tit)) = do
220219 alt' <- inlineListToXWiki alt
221220 let
222− params = intercalate " " $ filter (not . Text.null) [
221+ params = Text.unwords $ filter (not . Text.null) [
223222 if Text.null alt' then "" else "alt=\"" <> alt' <> "\"",
224223 if Text.null tit then "" else "title=\"" <> tit <> "\""
225224 ]
test/Tests/Command.hs+3−3
@@ -85,8 +85,8 @@ dropPercent :: String -> String
8585dropPercent ('%':xs) = dropWhile (== ' ') xs
8686dropPercent xs = xs
8787
88−runCommandTest :: FilePath -> (Int, String) -> TestTree
89−runCommandTest pandocpath (num, code) =
88+runCommandTest :: FilePath -> Int -> String -> TestTree
89+runCommandTest pandocpath num code =
9090 let codelines = lines code
9191 (continuations, r1) = span ("\\" `isSuffixOf`) codelines
9292 (cmd, r2) = (dropPercent (unwords (map init continuations ++ take 1 r1)),
@@ -104,5 +104,5 @@ extractCommandTest pandocpath fp = unsafePerformIO $ do
104104 Pandoc _ blocks <- runIOorExplode (readMarkdown
105105 def{ readerExtensions = pandocExtensions } contents)
106106 let codeblocks = map extractCode $ filter isCodeBlock blocks
107− let cases = map (runCommandTest pandocpath) $ zip [1..] codeblocks
107+ let cases = zipWith (runCommandTest pandocpath) [1..] codeblocks
108108 return $ testGroup fp cases