From 18d71d83e98aaeb803359a0bdd98cac8b653309a Mon Sep 17 00:00:00 2001 From: Nikolay Yakimov Date: Sun, 17 Dec 2017 18:33:29 +0300 Subject: [PATCH 001/134] [any-prefix]: inital proof of concept --- lib/Text/Pandoc/CrossRef/References/Blocks.hs | 296 +++++++++--------- lib/Text/Pandoc/CrossRef/References/List.hs | 25 +- lib/Text/Pandoc/CrossRef/References/Refs.hs | 139 ++++---- lib/Text/Pandoc/CrossRef/References/Types.hs | 15 +- lib/Text/Pandoc/CrossRef/Util/CustomLabels.hs | 21 +- lib/Text/Pandoc/CrossRef/Util/Meta.hs | 46 ++- lib/Text/Pandoc/CrossRef/Util/ModifyMeta.hs | 12 +- lib/Text/Pandoc/CrossRef/Util/Options.hs | 67 ++-- lib/Text/Pandoc/CrossRef/Util/Prefixes.hs | 64 ++++ lib/Text/Pandoc/CrossRef/Util/Settings.hs | 79 +++-- lib/Text/Pandoc/CrossRef/Util/Settings/Gen.hs | 20 +- .../Pandoc/CrossRef/Util/Settings/Template.hs | 10 +- lib/Text/Pandoc/CrossRef/Util/Template.hs | 15 +- lib/Text/Pandoc/CrossRef/Util/Util.hs | 7 +- pandoc-crossref.cabal | 4 +- 15 files changed, 458 insertions(+), 362 deletions(-) create mode 100644 lib/Text/Pandoc/CrossRef/Util/Prefixes.hs diff --git a/lib/Text/Pandoc/CrossRef/References/Blocks.hs b/lib/Text/Pandoc/CrossRef/References/Blocks.hs index 7c6443e4..93865fdf 100644 --- a/lib/Text/Pandoc/CrossRef/References/Blocks.hs +++ b/lib/Text/Pandoc/CrossRef/References/Blocks.hs @@ -24,7 +24,7 @@ module Text.Pandoc.CrossRef.References.Blocks ) where import Text.Pandoc.Definition -import qualified Text.Pandoc.Builder as B +import Text.Pandoc.Builder import Text.Pandoc.Shared (stringify) import Control.Monad.State hiding (get, modify) import Data.List @@ -32,15 +32,14 @@ import Data.Maybe import Data.Monoid import qualified Data.Map as M -import Data.Accessor import Data.Accessor.Monad.Trans.State import Text.Pandoc.CrossRef.References.Types import Text.Pandoc.CrossRef.Util.Util import Text.Pandoc.CrossRef.Util.Options +import Text.Pandoc.CrossRef.Util.Prefixes import Text.Pandoc.CrossRef.Util.Template import Control.Applicative import Prelude -import Data.Default replaceAll :: (Data a) => Options -> a -> WS a replaceAll opts = @@ -60,123 +59,124 @@ replaceBlock opts (Header n (label, cls, attrs) text') then "sec:"++label else label unless ("unnumbered" `elem` cls) $ do + -- TODO: Rework this horribleness that is curChap modify curChap $ \cc -> let ln = length cc cl = lookup "label" attrs - inc l = init l ++ [(fst (last l) + 1, cl)] + inc l = let incd = fst (last l) + 1 + in init l ++ [(incd, fromMaybe (show incd) cl)] cc' | ln > n = inc $ take n cc | ln == n = inc cc - | otherwise = cc ++ take (n-ln-1) (zip [1,1..] $ repeat Nothing) ++ [(1,cl)] + | otherwise = cc ++ take (n-ln-1) (zip (repeat 1) (repeat "1")) ++ [(1, fromMaybe "1" cl)] in cc' when ("sec:" `isPrefixOf` label') $ do index <- get curChap - modify secRefs $ M.insert label' RefRec { + modify referenceData $ M.insert label' RefRec { refIndex=index - , refTitle= text' + , refTitle= fromList text' , refSubfigure = Nothing } cc <- get curChap let textCC | numberSections opts , sectionsDepth opts < 0 || n <= if sectionsDepth opts == 0 then chaptersDepth opts else sectionsDepth opts , "unnumbered" `notElem` cls - = Str (intercalate "." $ map show' cc) : Space : text' + = Str (intercalate "." $ map snd cc) : Space : text' | otherwise = text' - show' (_, Just s) = s - show' (i, Nothing) = show i replaceNoRecurse $ Header n (label', cls, attrs) textCC -- subfigures -replaceBlock opts (Div (label,cls,attrs) images) - | "fig:" `isPrefixOf` label - , Para caption <- last images - = do - idxStr <- replaceAttr opts (Right label) (lookup "label" attrs) caption imgRefs - let (cont, st) = runState (runReplace (mkRR $ replaceSubfigs opts') $ init images) def - collectedCaptions = B.toList $ - intercalate' (B.fromList $ ccsDelim opts) - $ map (B.fromList . collectCaps . snd) - $ sortOn (refIndex . snd) - $ filter (not . null . refTitle . snd) - $ M.toList - $ imgRefs_ st - collectCaps v = - applyTemplate - (chapPrefix (chapDelim opts) (refIndex v)) - (refTitle v) - (ccsTemplate opts) - vars = M.fromDistinctAscList - [ ("ccs", collectedCaptions) - , ("i", idxStr) - , ("t", caption) - ] - capt = applyTemplate' vars $ subfigureTemplate opts - lastRef <- fromJust . M.lookup label <$> get imgRefs - modify imgRefs $ \old -> - M.union - old - (M.map (\v -> v{refIndex = refIndex lastRef, refSubfigure = Just $ refIndex v}) - $ imgRefs_ st) - case outFormat opts of - f | isFormat "latex" f -> - replaceNoRecurse $ Div nullAttr $ - [ RawBlock (Format "latex") "\\begin{figure}\n\\centering" ] - ++ cont ++ - [ Para [RawInline (Format "latex") "\\caption" - , Span nullAttr caption] - , RawBlock (Format "latex") $ mkLaTeXLabel label - , RawBlock (Format "latex") "\\end{figure}"] - _ -> replaceNoRecurse $ Div (label, "subfigures":cls, attrs) $ toTable cont capt - where - opts' = opts - { figureTemplate = subfigureChildTemplate opts - , customLabel = \r i -> customLabel opts ("sub"++r) i - } - toTable :: [Block] -> [Inline] -> [Block] - toTable blks capt - | subfigGrid opts = [Table [] align widths [] $ map blkToRow blks, mkCaption opts "Image Caption" capt] - | otherwise = blks ++ [mkCaption opts "Image Caption" capt] - where - align | Para ils:_ <- blks = replicate (length $ mapMaybe getWidth ils) AlignCenter - | otherwise = error "Misformatted subfigures block" - widths | Para ils:_ <- blks - = fixZeros $ mapMaybe getWidth ils - | otherwise = error "Misformatted subfigures block" - getWidth (Image (_id, _class, as) _ _) - = Just $ maybe 0 percToDouble $ lookup "width" as - getWidth _ = Nothing - fixZeros :: [Double] -> [Double] - fixZeros ws - = let nz = length $ filter (== 0) ws - rzw = (0.99 - sum ws) / fromIntegral nz - in if nz>0 - then map (\x -> if x == 0 then rzw else x) ws - else ws - percToDouble :: String -> Double - percToDouble percs - | '%' <- last percs - , perc <- read $ init percs - = perc/100.0 - | otherwise = error "Only percent allowed in subfigure width!" - blkToRow :: Block -> [[Block]] - blkToRow (Para inls) = mapMaybe inlToCell inls - blkToRow x = [[x]] - inlToCell :: Inline -> Maybe [Block] - inlToCell (Image (id', cs, as) txt tgt) = Just [Para [Image (id', cs, setW as) txt tgt]] - inlToCell _ = Nothing - setW as = ("width", "100%"):filter ((/="width") . fst) as +-- replaceBlock opts (Div (label,cls,attrs) images) +-- | "fig:" `isPrefixOf` label +-- , Para caption <- last images +-- = do +-- idxStr <- replaceAttr opts (Right label) (lookup "label" attrs) caption imgRefs +-- let (cont, st) = runState (runReplace (mkRR $ replaceSubfigs opts') $ init images) def +-- collectedCaptions = B.toList $ +-- intercalate' (B.fromList $ ccsDelim opts) +-- $ map (B.fromList . collectCaps . snd) +-- $ sortOn (refIndex . snd) +-- $ filter (not . null . refTitle . snd) +-- $ M.toList +-- $ imgRefs_ st +-- collectCaps v = +-- applyTemplate +-- (chapPrefix (chapDelim opts) (refIndex v)) +-- (refTitle v) +-- (ccsTemplate opts) +-- vars = M.fromDistinctAscList +-- [ ("ccs", collectedCaptions) +-- , ("i", idxStr) +-- , ("t", caption) +-- ] +-- capt = applyTemplate' vars $ subfigureTemplate opts +-- lastRef <- fromJust . M.lookup label <$> get imgRefs +-- modify imgRefs $ \old -> +-- M.union +-- old +-- (M.map (\v -> v{refIndex = refIndex lastRef, refSubfigure = Just $ refIndex v}) +-- $ imgRefs_ st) +-- case outFormat opts of +-- f | isFormat "latex" f -> +-- replaceNoRecurse $ Div nullAttr $ +-- [ RawBlock (Format "latex") "\\begin{figure}\n\\centering" ] +-- ++ cont ++ +-- [ Para [RawInline (Format "latex") "\\caption" +-- , Span nullAttr caption] +-- , RawBlock (Format "latex") $ mkLaTeXLabel label +-- , RawBlock (Format "latex") "\\end{figure}"] +-- _ -> replaceNoRecurse $ Div (label, "subfigures":cls, attrs) $ toTable cont capt +-- where +-- opts' = opts +-- { figureTemplate = subfigureChildTemplate opts +-- , customLabel = \r i -> customLabel opts ("sub"++r) i +-- } +-- toTable :: [Block] -> [Inline] -> [Block] +-- toTable blks capt +-- | subfigGrid opts = [Table [] align widths [] $ map blkToRow blks, mkCaption opts "Image Caption" capt] +-- | otherwise = blks ++ [mkCaption opts "Image Caption" capt] +-- where +-- align | Para ils:_ <- blks = replicate (length $ mapMaybe getWidth ils) AlignCenter +-- | otherwise = error "Misformatted subfigures block" +-- widths | Para ils:_ <- blks +-- = fixZeros $ mapMaybe getWidth ils +-- | otherwise = error "Misformatted subfigures block" +-- getWidth (Image (_id, _class, as) _ _) +-- = Just $ maybe 0 percToDouble $ lookup "width" as +-- getWidth _ = Nothing +-- fixZeros :: [Double] -> [Double] +-- fixZeros ws +-- = let nz = length $ filter (== 0) ws +-- rzw = (0.99 - sum ws) / fromIntegral nz +-- in if nz>0 +-- then map (\x -> if x == 0 then rzw else x) ws +-- else ws +-- percToDouble :: String -> Double +-- percToDouble percs +-- | '%' <- last percs +-- , perc <- read $ init percs +-- = perc/100.0 +-- | otherwise = error "Only percent allowed in subfigure width!" +-- blkToRow :: Block -> [[Block]] +-- blkToRow (Para inls) = mapMaybe inlToCell inls +-- blkToRow x = [[x]] +-- inlToCell :: Inline -> Maybe [Block] +-- inlToCell (Image (id', cs, as) txt tgt) = Just [Para [Image (id', cs, setW as) txt tgt]] +-- inlToCell _ = Nothing +-- setW as = ("width", "100%"):filter ((/="width") . fst) as replaceBlock opts (Div divOps@(label,_,attrs) [Table title align widths header cells]) | not $ null title - , "tbl:" `isPrefixOf` label + , Just pfx <- getRefPrefix opts label = do - idxStr <- replaceAttr opts (Right label) (lookup "label" attrs) title tblRefs - let title' = + let ititle = fromList title + idxStr <- replaceAttr opts (Right label) (lookup "label" attrs) ititle pfx + let title' = toList $ case outFormat opts of f | isFormat "latex" f -> - RawInline (Format "latex") (mkLaTeXLabel label) : title - _ -> applyTemplate idxStr title $ tableTemplate opts + rawInline "latex" (mkLaTeXLabel label) <> ititle + _ -> applyTemplate idxStr ititle $ fromJust $ pfxCaptionTemplate opts pfx replaceNoRecurse $ Div divOps [Table title' align widths header cells] replaceBlock opts cb@(CodeBlock (label, classes, attrs) code) | not $ null label - , "lst:" `isPrefixOf` label + , Just pfx <- getRefPrefix opts label , Just caption <- lookup "caption" attrs = case outFormat opts of f @@ -191,9 +191,9 @@ replaceBlock opts cb@(CodeBlock (label, classes, attrs) code) , RawBlock (Format "latex") "\\end{codelisting}" ] _ -> do - let cap = B.toList $ B.text caption - idxStr <- replaceAttr opts (Right label) (lookup "label" attrs) cap lstRefs - let caption' = applyTemplate idxStr cap $ listingTemplate opts + let cap = text caption + idxStr <- replaceAttr opts (Right label) (lookup "label" attrs) cap pfx + let caption' = applyTemplate idxStr cap $ fromJust $ pfxCaptionTemplate opts pfx replaceNoRecurse $ Div (label, "listing":classes, []) [ mkCaption opts "Caption" caption' , CodeBlock ([], classes, attrs \\ [("caption", caption)]) code @@ -202,7 +202,7 @@ replaceBlock opts (Div (label,"listing":_, []) [Para caption, CodeBlock ([],classes,attrs) code]) | not $ null label - , "lst:" `isPrefixOf` label + , Just pfx <- getRefPrefix opts label = case outFormat opts of f --if used with listings package, return code block with caption @@ -220,69 +220,84 @@ replaceBlock opts , RawBlock (Format "latex") "\\end{codelisting}" ] _ -> do - idxStr <- replaceAttr opts (Right label) (lookup "label" attrs) caption lstRefs - let caption' = applyTemplate idxStr caption $ listingTemplate opts + let icaption = fromList caption + idxStr <- replaceAttr opts (Right label) (lookup "label" attrs) icaption pfx + let caption' = applyTemplate idxStr icaption $ fromJust $ pfxCaptionTemplate opts pfx replaceNoRecurse $ Div (label, "listing":classes, []) [ mkCaption opts "Caption" caption' , CodeBlock ([], classes, attrs) code ] -replaceBlock opts (Para [Span attrs [Math DisplayMath eq]]) +replaceBlock opts (Para [Span attrs@(label, _, _) [Math DisplayMath eq]]) | not $ isFormat "latex" (outFormat opts) , tableEqns opts + , pfx <- getRefPrefix opts label = do - (eq', idx) <- replaceEqn opts attrs eq + (eq', idx) <- replaceEqn opts attrs eq pfx replaceNoRecurse $ Div attrs [Table [] [AlignCenter, AlignRight] [0.9, 0.09] [] [[[Plain [Math DisplayMath eq']], [Plain [Math DisplayMath $ "(" ++ idx ++ ")"]]]]] replaceBlock _ _ = noReplaceRecurse -replaceEqn :: Options -> Attr -> String -> WS (String, String) -replaceEqn opts (label, _, attrs) eq = do +getRefPrefix :: Options -> String -> Maybe String +getRefPrefix opts label + | ':' `notElem` label = Nothing + | otherwise = + let pfx = takeWhile (/=':') label + in if pfx `elem` prefixList opts + then Just pfx + else Nothing + +replaceEqn :: Options -> Attr -> String -> Maybe String -> WS (String, String) +replaceEqn opts (label, _, attrs) eq pfx = do let label' | null label = Left "eq" | otherwise = Right label - idxStr <- replaceAttr opts label' (lookup "label" attrs) [] eqnRefs + idxStr <- replaceAttr opts label' (lookup "label" attrs) mempty (fromMaybe "eq" pfx) let eq' | tableEqns opts = eq | otherwise = eq++"\\qquad("++stringify idxStr++")" return (eq', stringify idxStr) replaceInline :: Options -> Inline -> WS (ReplacedResult Inline) replaceInline opts (Span attrs@(label,_,_) [Math DisplayMath eq]) - | "eq:" `isPrefixOf` label || null label && autoEqnLabels opts + | pfx <- getRefPrefix opts label + , isJust pfx || null label && autoEqnLabels opts = case outFormat opts of f | isFormat "latex" f -> let eqn = "\\begin{equation}"++eq++mkLaTeXLabel label++"\\end{equation}" in replaceNoRecurse $ RawInline (Format "latex") eqn _ -> do - (eq', _) <- replaceEqn opts attrs eq + (eq', _) <- replaceEqn opts attrs eq pfx replaceNoRecurse $ Span attrs [Math DisplayMath eq'] replaceInline opts (Image attr@(label,_,attrs) alt img@(_, tit)) - | "fig:" `isPrefixOf` label && "fig:" `isPrefixOf` tit + | Just pfx <- getRefPrefix opts label + , "fig:" `isPrefixOf` tit = do - idxStr <- replaceAttr opts (Right label) (lookup "label" attrs) alt imgRefs - let alt' = case outFormat opts of - f | isFormat "latex" f -> alt - _ -> applyTemplate idxStr alt $ figureTemplate opts + let ialt = fromList alt + idxStr <- replaceAttr opts (Right label) (lookup "label" attrs) ialt pfx + let alt' = toList $ case outFormat opts of + f | isFormat "latex" f -> ialt + _ -> applyTemplate idxStr ialt $ fromJust $ pfxCaptionTemplate opts pfx replaceNoRecurse $ Image attr alt' img replaceInline _ _ = noReplaceRecurse -replaceSubfigs :: Options -> [Inline] -> WS (ReplacedResult [Inline]) -replaceSubfigs opts = (replaceNoRecurse . concat =<<) . mapM (replaceSubfig opts) +-- replaceSubfigs :: Options -> [Inline] -> WS (ReplacedResult [Inline]) +-- replaceSubfigs opts = (replaceNoRecurse . concat =<<) . mapM (replaceSubfig opts) -replaceSubfig :: Options -> Inline -> WS [Inline] -replaceSubfig opts x@(Image (label,cls,attrs) alt (src, tit)) - = do - let label' | "fig:" `isPrefixOf` label = Right label - | null label = Left "fig" - | otherwise = Right $ "fig:" ++ label - idxStr <- replaceAttr opts label' (lookup "label" attrs) alt imgRefs - case outFormat opts of - f | isFormat "latex" f -> - return $ latexSubFigure x label - _ -> - let alt' = applyTemplate idxStr alt $ figureTemplate opts - tit' | "nocaption" `elem` cls = fromMaybe tit $ stripPrefix "fig:" tit - | "fig:" `isPrefixOf` tit = tit - | otherwise = "fig:" ++ tit - in return [Image (label, cls, attrs) alt' (src, tit')] -replaceSubfig _ x = return [x] +-- replaceSubfig :: Options -> Inline -> WS [Inline] +-- replaceSubfig opts x@(Image (label,cls,attrs) alt (src, tit)) +-- = do +-- let label' | "fig:" `isPrefixOf` label = Right label +-- | null label = Left "fig" +-- | otherwise = Right $ "fig:" ++ label +-- let ialt = fromList alt +-- idxStr <- replaceAttr opts label' (lookup "label" attrs) ialt +-- case outFormat opts of +-- f | isFormat "latex" f -> +-- return $ latexSubFigure x label +-- _ -> +-- let alt' = toList $ applyTemplate idxStr ialt $ fromJust $ pfxCaptionTemplate opts pfx +-- tit' | "nocaption" `elem` cls = fromMaybe tit $ stripPrefix "fig:" tit +-- | "fig:" `isPrefixOf` tit = tit +-- | otherwise = "fig:" ++ tit +-- in return [Image (label, cls, attrs) alt' (src, tit')] +-- replaceSubfig _ x = return [x] divBlocks :: Block -> Block divBlocks (Table title align widths header cells) @@ -314,17 +329,18 @@ spanInlines opts (math@(Math DisplayMath _eq):ils) = Span nullAttr [math]:ils spanInlines _ x = x -replaceAttr :: Options -> Either String String -> Maybe String -> [Inline] -> Accessor References RefMap -> WS [Inline] -replaceAttr o label refLabel title prop +replaceAttr :: Options -> Either String String -> Maybe String -> Inlines -> String -> WS Inlines +replaceAttr o label refLabel title pfx = do chap <- take (chaptersDepth o) `fmap` get curChap - i <- (1+) `fmap` (M.size . M.filter (\x -> (chap == init (refIndex x)) && isNothing (refSubfigure x)) <$> get prop) - let index = chap ++ [(i, refLabel <> customLabel o label' i)] + i <- (1+) `fmap` (M.size . M.filter (\x -> (chap == init (refIndex x)) && isNothing (refSubfigure x)) <$> get referenceData) + let customLabel = prefixNumbering $ fromJust $ M.lookup pfx (prefixes o) + let index = chap ++ [(i, fromMaybe (customLabel i) refLabel)] label' = either (++ ':':show index) id label - hasLabel <- M.member label' <$> get prop + hasLabel <- M.member label' <$> get referenceData when hasLabel $ error $ "Duplicate label: " ++ label' - modify prop $ M.insert label' RefRec { + modify referenceData $ M.insert label' RefRec { refIndex= index , refTitle= title , refSubfigure = Nothing @@ -351,7 +367,7 @@ latexSubFigure (Image (_, cls, attrs) alt (src, title)) label = ] latexSubFigure x _ = [x] -mkCaption :: Options -> String -> [Inline] -> Block +mkCaption :: Options -> String -> Inlines -> Block mkCaption opts style - | outFormat opts == Just (Format "docx") = Div ([], [], [("custom-style", style)]) . return . Para - | otherwise = Para + | outFormat opts == Just (Format "docx") = Div ([], [], [("custom-style", style)]) . toList . para + | otherwise = Para . toList diff --git a/lib/Text/Pandoc/CrossRef/References/List.hs b/lib/Text/Pandoc/CrossRef/References/List.hs index 1290530b..4ee8687a 100644 --- a/lib/Text/Pandoc/CrossRef/References/List.hs +++ b/lib/Text/Pandoc/CrossRef/References/List.hs @@ -21,6 +21,7 @@ with this program; if not, write to the Free Software Foundation, Inc., module Text.Pandoc.CrossRef.References.List (listOf) where import Text.Pandoc.Definition +import Text.Pandoc.Builder import Data.Accessor.Monad.Trans.State import Control.Arrow import Data.List @@ -33,25 +34,27 @@ import Text.Pandoc.CrossRef.Util.Options listOf :: Options -> [Block] -> WS [Block] listOf Options{outFormat=f} x | isFormat "latex" f = return x listOf opts (RawBlock (Format "latex") "\\listoffigures":xs) - = get imgRefs >>= makeList opts lofTitle xs + = undefined -- get imgRefs >>= makeList opts lofTitle xs listOf opts (RawBlock (Format "latex") "\\listoftables":xs) - = get tblRefs >>= makeList opts lotTitle xs + = undefined -- get tblRefs >>= makeList opts lotTitle xs listOf opts (RawBlock (Format "latex") "\\listoflistings":xs) - = get lstRefs >>= makeList opts lolTitle xs + = undefined -- get lstRefs >>= makeList opts lolTitle xs listOf _ x = return x -makeList :: Options -> (Options -> [Block]) -> [Block] -> M.Map String RefRec -> WS [Block] +makeList :: Options -> (Options -> Blocks) -> Blocks -> M.Map String RefRec -> WS Blocks makeList opts titlef xs refs = return $ - titlef opts ++ + titlef opts <> (if chaptersDepth opts > 0 - then Div ("", ["list"], []) (itemChap `map` refsSorted) - else OrderedList style (item `map` refsSorted)) - : xs + then divWith ("", ["list"], []) (mconcat $ map itemChap refsSorted) + else orderedList (map item refsSorted)) + <> xs where + refsSorted :: [(String, RefRec)] refsSorted = sortBy compare' $ M.toList refs compare' (_,RefRec{refIndex=i}) (_,RefRec{refIndex=j}) = compare i j - item = (:[]) . Plain . refTitle . snd - itemChap = Para . uncurry ((. (Space :)) . (++)) . (numWithChap . refIndex &&& refTitle) . snd + item = plain . refTitle . snd + itemChap :: (String, RefRec) -> Blocks + itemChap = para . uncurry (\ x x0 -> x <> space <> x0) . ((numWithChap . refIndex) &&& refTitle) . snd + numWithChap :: Index -> Inlines numWithChap = chapPrefix (chapDelim opts) - style = (1,DefaultStyle,DefaultDelim) diff --git a/lib/Text/Pandoc/CrossRef/References/Refs.hs b/lib/Text/Pandoc/CrossRef/References/Refs.hs index 5464c59e..d3beec98 100644 --- a/lib/Text/Pandoc/CrossRef/References/Refs.hs +++ b/lib/Text/Pandoc/CrossRef/References/Refs.hs @@ -30,32 +30,32 @@ import Data.Function import qualified Data.Map as M import Control.Arrow as A -import Data.Accessor import Data.Accessor.Monad.Trans.State import Text.Pandoc.CrossRef.References.Types import Text.Pandoc.CrossRef.Util.Template import Text.Pandoc.CrossRef.Util.Util import Text.Pandoc.CrossRef.Util.Options +import Text.Pandoc.CrossRef.Util.Prefixes import Control.Applicative import Debug.Trace import Prelude replaceRefs :: Options -> [Inline] -> WS [Inline] -replaceRefs opts (Cite cits _:xs) - = toList . (<> fromList xs) . intercalate' (text ", ") . map fromList <$> mapM replaceRefs' (groupBy eqPrefix cits) +replaceRefs opts ils + | Cite cits _:xs <- ils + = toList . (<> fromList xs) . intercalate' (text ", ") <$> mapM replaceRefs' (groupBy eqPrefix cits) where eqPrefix a b = uncurry (==) $ - (fmap uncapitalizeFirst . getLabelPrefix . citationId) <***> (a,b) + (fmap uncapitalizeFirst . getLabelPrefix opts . citationId) <***> (a,b) (<***>) = join (***) replaceRefs' cits' - | Just prefix <- allCitsPrefix cits' + | Just prefix <- allCitsPrefix opts cits' = replaceRefs'' prefix opts cits' - | otherwise = return [Cite cits' il'] + | otherwise = return $ cite cits' il' where - il' = toList $ - str "[" - <> intercalate' (text "; ") (map citationToInlines cits') - <> str "]" + il' = str "[" + <> intercalate' (text "; ") (map citationToInlines cits') + <> str "]" citationToInlines c = fromList (citationPrefix c) <> text ("@" ++ citationId c) <> fromList (citationSuffix c) @@ -64,58 +64,34 @@ replaceRefs opts (Cite cits _:xs) _ -> replaceRefsOther replaceRefs _ x = return x --- accessors to state variables -accMap :: M.Map String (Accessor References RefMap) -accMap = M.fromList [("fig:",imgRefs) - ,("eq:" ,eqnRefs) - ,("tbl:",tblRefs) - ,("lst:",lstRefs) - ,("sec:",secRefs) - ] - --- accessors to options -prefMap :: M.Map String (Options -> Bool -> Int -> [Inline], Options -> Template) -prefMap = M.fromList [("fig:",(figPrefix, figPrefixTemplate)) - ,("eq:" ,(eqnPrefix, eqnPrefixTemplate)) - ,("tbl:",(tblPrefix, tblPrefixTemplate)) - ,("lst:",(lstPrefix, lstPrefixTemplate)) - ,("sec:",(secPrefix, secPrefixTemplate)) - ] - -prefixes :: [String] -prefixes = M.keys accMap - -getRefPrefix :: Options -> String -> Bool -> Int -> [Inline] -> [Inline] -getRefPrefix opts prefix capitalize num cit = - applyTemplate' (M.fromDistinctAscList [("i", cit), ("p", refprefix)]) - $ reftempl opts - where (refprefixf, reftempl) = lookupUnsafe prefix prefMap - refprefix = refprefixf opts capitalize num - - -lookupUnsafe :: Ord k => k -> M.Map k v -> v -lookupUnsafe = (fromJust .) . M.lookup - -allCitsPrefix :: [Citation] -> Maybe String -allCitsPrefix cits = find isCitationPrefix prefixes +traceClone :: Show a => a -> a +traceClone x = trace (show x) x + +getRefPrefix :: Options -> String -> Bool -> Int -> Inlines -> Inlines +getRefPrefix opts prefix capitalize num cit = traceClone $ + applyTemplate' (M.fromDistinctAscList [("i", cit), ("p", refprefix)]) reftempl + where Prefix{prefixRef=refprefixf, prefixReferenceTemplate=reftempl} = fromMaybe undefined $ M.lookup prefix $ prefixes opts + refprefix = refprefixf capitalize num + +allCitsPrefix :: Options -> [Citation] -> Maybe String +allCitsPrefix opts cits = find isCitationPrefix $ prefixList opts where isCitationPrefix p = all (p `isPrefixOf`) $ map (uncapitalizeFirst . citationId) cits -replaceRefsLatex :: String -> Options -> [Citation] -> WS [Inline] +replaceRefsLatex :: String -> Options -> [Citation] -> WS Inlines replaceRefsLatex prefix opts cits | cref opts = replaceRefsLatex' prefix opts cits | otherwise - = toList . intercalate' (text ", ") . map fromList <$> + = intercalate' (text ", ") <$> mapM (replaceRefsLatex' prefix opts) (groupBy citationGroupPred cits) -replaceRefsLatex' :: String -> Options -> [Citation] -> WS [Inline] +replaceRefsLatex' :: String -> Options -> [Citation] -> WS Inlines replaceRefsLatex' prefix opts cits = - return $ p [texcit] + return $ p texcit where - texcit = - RawInline (Format "tex") $ + texcit = rawInline "tex" $ if cref opts then cref'++"{"++listLabels prefix "" "," "" cits++"}" else @@ -127,76 +103,73 @@ replaceRefsLatex' prefix opts cits = = id | noPrefix = getRefPrefix opts prefix cap (length cits - 1) - | otherwise = ((citationPrefix (head cits) ++ [Space]) ++) - cap = maybe False isFirstUpper $ getLabelPrefix . citationId . head $ cits + | otherwise = ((fromList (citationPrefix (head cits)) <> space) <>) + cap = maybe False isFirstUpper $ getLabelPrefix opts . citationId . head $ cits cref' | suppressAuthor = "\\labelcref" | cap = "\\Cref" | otherwise = "\\cref" listLabels :: String -> String -> String -> String -> [Citation] -> String listLabels prefix p sep s = - intercalate sep . map ((p ++) . (++ s) . mkLaTeXLabel' . (prefix++) . getLabelWithoutPrefix . citationId) - -getLabelWithoutPrefix :: String -> String -getLabelWithoutPrefix = drop 1 . dropWhile (/=':') + intercalate sep . map ((p ++) . (++ s) . mkLaTeXLabel' . citationId) -getLabelPrefix :: String -> Maybe String -getLabelPrefix lab - | uncapitalizeFirst p `elem` prefixes = Just p +getLabelPrefix :: Options -> String -> Maybe String +getLabelPrefix opts lab + | uncapitalizeFirst p `elem` prefixList opts = Just p | otherwise = Nothing - where p = (++ ":") . takeWhile (/=':') $ lab + where p = takeWhile (/=':') lab -replaceRefsOther :: String -> Options -> [Citation] -> WS [Inline] -replaceRefsOther prefix opts cits = toList . intercalate' (text ", ") . map fromList <$> +replaceRefsOther :: String -> Options -> [Citation] -> WS Inlines +replaceRefsOther prefix opts cits = intercalate' (text ", ") <$> mapM (replaceRefsOther' prefix opts) (groupBy citationGroupPred cits) citationGroupPred :: Citation -> Citation -> Bool citationGroupPred = (==) `on` liftM2 (,) citationPrefix citationMode -replaceRefsOther' :: String -> Options -> [Citation] -> WS [Inline] +replaceRefsOther' :: String -> Options -> [Citation] -> WS Inlines replaceRefsOther' prefix opts cits = do indices <- mapM (getRefIndex prefix opts) cits let - cap = maybe False isFirstUpper $ getLabelPrefix . citationId . head $ cits + cap = maybe False isFirstUpper $ getLabelPrefix opts . citationId . head $ cits writePrefix | all (==SuppressAuthor) $ map citationMode cits = id | all null $ map citationPrefix cits = cmap $ getRefPrefix opts prefix cap (length cits - 1) | otherwise - = cmap $ toList . ((fromList (citationPrefix (head cits)) <> space) <>) . fromList - cmap f [Link attr t w] - | nameInLink opts = [Link attr (f t) w] + = cmap ((fromList (citationPrefix (head cits)) <> space) <>) + cmap f x + | nameInLink opts + , [Link attr t (y, z)] <- toList x = linkWith attr y z (f $ fromList t) cmap f x = f x return $ writePrefix (makeIndices opts indices) data RefData = RefData { rdLabel :: String , rdIdx :: Maybe Index , rdSubfig :: Maybe Index - , rdSuffix :: [Inline] + , rdSuffix :: Inlines } deriving (Eq) instance Ord RefData where (<=) = (<=) `on` rdIdx getRefIndex :: String -> Options -> Citation -> WS RefData -getRefIndex prefix _opts Citation{citationId=cid,citationSuffix=suf} +getRefIndex _prefix _opts Citation{citationId=cid,citationSuffix=suf} = do - ref <- M.lookup lab <$> get prop + ref <- M.lookup lab <$> get referenceData let sub = refSubfigure <$> ref idx = refIndex <$> ref return RefData { rdLabel = lab , rdIdx = idx , rdSubfig = join sub - , rdSuffix = suf + , rdSuffix = fromList suf } where - prop = lookupUnsafe prefix accMap - lab = prefix ++ getLabelWithoutPrefix cid + lab = cid data RefItem = RefRange RefData RefData | RefSingle RefData -makeIndices :: Options -> [RefData] -> [Inline] +makeIndices :: Options -> [RefData] -> Inlines makeIndices o s = format $ concatMap f $ HT.groupBy g $ sort $ nub s where g :: RefData -> RefData -> Bool @@ -217,22 +190,22 @@ makeIndices o s = format $ concatMap f $ HT.groupBy g $ sort $ nub s f [w] = [RefSingle w] -- single value f [w1,w2] = [RefSingle w1, RefSingle w2] -- two values f (x:xs) = [RefRange x (last xs)] -- shorten more than two values - format :: [RefItem] -> [Inline] - format [] = [] - format [x] = toList $ show'' x - format [x, y] = toList $ show'' x <> fromList (pairDelim o) <> show'' y - format xs = toList $ intercalate' (fromList $ refDelim o) init' <> fromList (lastDelim o) <> last' + format :: [RefItem] -> Inlines + format [] = mempty + format [x] = show'' x + format [x, y] = show'' x <> pairDelim o <> show'' y + format xs = intercalate' (refDelim o) init' <> lastDelim o <> last' where initlast [] = error "emtpy list in initlast" initlast [y] = ([], y) initlast (y:ys) = first (y:) $ initlast ys (init', last') = initlast $ map show'' xs show'' :: RefItem -> Inlines show'' (RefSingle x) = show' x - show'' (RefRange x y) = show' x <> fromList (rangeDelim o) <> show' y + show'' (RefRange x y) = show' x <> rangeDelim o <> show' y show' :: RefData -> Inlines show' RefData{rdLabel=l, rdIdx=Just i, rdSubfig = sub, rdSuffix = suf} - | linkReferences o = link ('#':l) "" (fromList txt) - | otherwise = fromList txt + | linkReferences o = link ('#':l) "" txt + | otherwise = txt where txt | Just sub' <- sub @@ -250,4 +223,4 @@ makeIndices o s = format $ concatMap f $ HT.groupBy g $ sort $ nub s in applyTemplate' vars $ refIndexTemplate o show' RefData{rdLabel=l, rdIdx=Nothing, rdSuffix = suf} = trace ("Undefined cross-reference: " ++ l) - (strong (text $ "¿" ++ l ++ "?") <> fromList suf) + (strong (text $ "¿" ++ l ++ "?") <> suf) diff --git a/lib/Text/Pandoc/CrossRef/References/Types.hs b/lib/Text/Pandoc/CrossRef/References/Types.hs index 7cc6713a..49e11ede 100644 --- a/lib/Text/Pandoc/CrossRef/References/Types.hs +++ b/lib/Text/Pandoc/CrossRef/References/Types.hs @@ -22,26 +22,22 @@ with this program; if not, write to the Free Software Foundation, Inc., module Text.Pandoc.CrossRef.References.Types where import qualified Data.Map as M -import Text.Pandoc.Definition import Control.Monad.State import Data.Default import Data.Accessor.Template +import Text.Pandoc.Builder -type Index = [(Int, Maybe String)] +type Index = [(Int, String)] data RefRec = RefRec { refIndex :: Index - , refTitle :: [Inline] + , refTitle :: Inlines , refSubfigure :: Maybe Index } deriving (Show, Eq) type RefMap = M.Map String RefRec -- state data type -data References = References { imgRefs_ :: RefMap - , eqnRefs_ :: RefMap - , tblRefs_ :: RefMap - , lstRefs_ :: RefMap - , secRefs_ :: RefMap +data References = References { referenceData_ :: RefMap , curChap_ :: Index } deriving (Show, Eq) @@ -49,7 +45,6 @@ data References = References { imgRefs_ :: RefMap type WS a = State References a instance Default References where - def = References n n n n n [] - where n = M.empty + def = References M.empty [] deriveAccessors ''References diff --git a/lib/Text/Pandoc/CrossRef/Util/CustomLabels.hs b/lib/Text/Pandoc/CrossRef/Util/CustomLabels.hs index 27697471..b9b19604 100644 --- a/lib/Text/Pandoc/CrossRef/Util/CustomLabels.hs +++ b/lib/Text/Pandoc/CrossRef/Util/CustomLabels.hs @@ -18,28 +18,21 @@ with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -} -module Text.Pandoc.CrossRef.Util.CustomLabels (customLabel) where +module Text.Pandoc.CrossRef.Util.CustomLabels where import Text.Pandoc.Definition import Text.Pandoc.CrossRef.Util.Meta import Data.List import Text.Numeral.Roman -customLabel :: Meta -> String -> Int -> Maybe String -customLabel meta ref i - | refLabel <- takeWhile (/=':') ref - , Just cl <- lookupMeta (refLabel++"Labels") meta - = mkLabel i (refLabel++"Labels") cl - | otherwise = Nothing - -mkLabel :: Int -> String -> MetaValue -> Maybe String -mkLabel i n lt +mkLabel :: String -> MetaValue -> Int -> String +mkLabel n lt i | toString n lt == "arabic" - = Nothing + = show i | toString n lt == "roman" - = Just $ toRoman i + = toRoman i | Just (startWith:_) <- stripPrefix "alpha " $ toString n lt - = Just [[startWith..] !! (i-1)] + = [[startWith..] !! (i-1)] | Just val <- toString n <$> getList (i-1) lt - = Just val + = val | otherwise = error $ "Unknown numeration type: " ++ show lt diff --git a/lib/Text/Pandoc/CrossRef/Util/Meta.hs b/lib/Text/Pandoc/CrossRef/Util/Meta.hs index d1f83934..e752a91a 100644 --- a/lib/Text/Pandoc/CrossRef/Util/Meta.hs +++ b/lib/Text/Pandoc/CrossRef/Util/Meta.hs @@ -18,13 +18,14 @@ with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -} -{-# LANGUAGE FlexibleContexts, Rank2Types #-} +{-# LANGUAGE FlexibleContexts, Rank2Types, UndecidableInstances, FlexibleInstances #-} module Text.Pandoc.CrossRef.Util.Meta ( getMetaList , getMetaBool , getMetaInlines , getMetaBlock , getMetaString + , getMetaStringMaybe , getList , toString , toInlines @@ -37,6 +38,7 @@ import Text.Pandoc.Builder import Data.Default import Text.Pandoc.Walk import Text.Pandoc.Shared hiding (capitalize) +import Data.Maybe getMetaList :: (Default a) => (MetaValue -> a) -> String -> Meta -> Int -> a getMetaList f name meta i = maybe def f $ lookupMeta name meta >>= getList i @@ -44,15 +46,18 @@ getMetaList f name meta i = maybe def f $ lookupMeta name meta >>= getList i getMetaBool :: String -> Meta -> Bool getMetaBool = getScalar toBool -getMetaInlines :: String -> Meta -> [Inline] +getMetaInlines :: String -> Meta -> Inlines getMetaInlines = getScalar toInlines -getMetaBlock :: String -> Meta -> [Block] +getMetaBlock :: String -> Meta -> Blocks getMetaBlock = getScalar toBlocks getMetaString :: String -> Meta -> String getMetaString = getScalar toString +getMetaStringMaybe :: String -> Meta -> Maybe String +getMetaStringMaybe = getScalar toMaybeString + getScalar :: Def b => (String -> MetaValue -> b) -> String -> Meta -> b getScalar conv name meta = maybe def' (conv name) $ lookupMeta name meta @@ -62,9 +67,15 @@ class Def a where instance Def Bool where def' = False -instance Def [a] where +instance Def String where def' = [] +instance Def (Maybe a) where + def' = Nothing + +instance (Monoid (Many a)) => Def (Many a) where + def' = mempty + unexpectedError :: forall a. String -> String -> MetaValue -> a unexpectedError e n x = error $ "Expected " <> e <> " in metadata field " <> n <> " but got " <> g x where @@ -75,27 +86,30 @@ unexpectedError e n x = error $ "Expected " <> e <> " in metadata field " <> n < g (MetaMap _) = "map" g (MetaList _) = "list" -toInlines :: String -> MetaValue -> [Inline] -toInlines _ (MetaBlocks s) = blocksToInlines s -toInlines _ (MetaInlines s) = s -toInlines _ (MetaString s) = toList $ text s +toInlines :: String -> MetaValue -> Inlines +toInlines _ (MetaBlocks s) = fromList $ blocksToInlines s +toInlines _ (MetaInlines s) = fromList s +toInlines _ (MetaString s) = text s toInlines n x = unexpectedError "inlines" n x toBool :: String -> MetaValue -> Bool toBool _ (MetaBool b) = b toBool n x = unexpectedError "bool" n x -toBlocks :: String -> MetaValue -> [Block] -toBlocks _ (MetaBlocks bs) = bs -toBlocks _ (MetaInlines ils) = [Plain ils] -toBlocks _ (MetaString s) = toList $ plain $ text s +toBlocks :: String -> MetaValue -> Blocks +toBlocks _ (MetaBlocks bs) = fromList bs +toBlocks _ (MetaInlines ils) = fromList [Plain ils] +toBlocks _ (MetaString s) = plain $ text s toBlocks n x = unexpectedError "blocks" n x toString :: String -> MetaValue -> String -toString _ (MetaString s) = s -toString _ (MetaBlocks b) = stringify b -toString _ (MetaInlines i) = stringify i -toString n x = unexpectedError "string" n x +toString n x = fromMaybe (unexpectedError "string" n x) $ toMaybeString n x + +toMaybeString :: String -> MetaValue -> Maybe String +toMaybeString _ (MetaString s) = Just s +toMaybeString _ (MetaBlocks b) = Just $ stringify b +toMaybeString _ (MetaInlines i) = Just $ stringify i +toMaybeString n x = Nothing getList :: Int -> MetaValue -> Maybe MetaValue getList i (MetaList l) = l !!? i diff --git a/lib/Text/Pandoc/CrossRef/Util/ModifyMeta.hs b/lib/Text/Pandoc/CrossRef/Util/ModifyMeta.hs index e3212740..eca65a94 100644 --- a/lib/Text/Pandoc/CrossRef/Util/ModifyMeta.hs +++ b/lib/Text/Pandoc/CrossRef/Util/ModifyMeta.hs @@ -90,11 +90,11 @@ modifyMeta opts meta ] | otherwise = ["\\newcommand*\\listoflistings{\\listof{codelisting}{"++metaString' "lolTitle"++"}}"] cleveref = [ usepackage cleverefOpts "cleveref" ] - <> crefname "figure" figPrefix - <> crefname "table" tblPrefix - <> crefname "equation" eqnPrefix - <> crefname "listing" lstPrefix - <> crefname "section" secPrefix + -- <> crefname "figure" figPrefix + -- <> crefname "table" tblPrefix + -- <> crefname "equation" eqnPrefix + -- <> crefname "listing" lstPrefix + -- <> crefname "section" secPrefix cleverefCodelisting = [ "\\crefname{codelisting}{\\cref@listing@name}{\\cref@listing@name@plural}" , "\\Crefname{codelisting}{\\Cref@listing@name}{\\Cref@listing@name@plural}" @@ -109,7 +109,7 @@ modifyMeta opts meta usepackage xs p = "\\@ifpackageloaded{"++p++"}{}{\\usepackage"++o++"{"++p++"}}" where o = "[" ++ intercalate "," xs ++ "]" toLatex = either (error . show) T.unpack . runPure . writeLaTeX def . Pandoc nullMeta . return . Plain - metaString s = toLatex $ getMetaInlines s meta + metaString s = toLatex . toList $ getMetaInlines s meta metaString' s = toLatex [Str $ getMetaString s meta] prefix f uc = "{" ++ toLatex (f opts uc 0) ++ "}" ++ "{" ++ toLatex (f opts uc 1) ++ "}" diff --git a/lib/Text/Pandoc/CrossRef/Util/Options.hs b/lib/Text/Pandoc/CrossRef/Util/Options.hs index 1fef365a..b9452588 100644 --- a/lib/Text/Pandoc/CrossRef/Util/Options.hs +++ b/lib/Text/Pandoc/CrossRef/Util/Options.hs @@ -18,9 +18,12 @@ with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -} -module Text.Pandoc.CrossRef.Util.Options (Options(..)) where +module Text.Pandoc.CrossRef.Util.Options where import Text.Pandoc.Definition import Text.Pandoc.CrossRef.Util.Template +import Text.Pandoc.CrossRef.Util.Prefixes +import qualified Data.Map as M +import Text.Pandoc.Builder data Options = Options { cref :: Bool , chaptersDepth :: Int @@ -29,39 +32,47 @@ data Options = Options { cref :: Bool , autoSectionLabels :: Bool , numberSections :: Bool , sectionsDepth :: Int - , figPrefix :: Bool -> Int -> [Inline] - , eqnPrefix :: Bool -> Int -> [Inline] - , tblPrefix :: Bool -> Int -> [Inline] - , lstPrefix :: Bool -> Int -> [Inline] - , secPrefix :: Bool -> Int -> [Inline] - , figPrefixTemplate :: Template - , eqnPrefixTemplate :: Template - , tblPrefixTemplate :: Template - , lstPrefixTemplate :: Template - , secPrefixTemplate :: Template + -- , figPrefix :: Bool -> Int -> [Inline] + -- , eqnPrefix :: Bool -> Int -> [Inline] + -- , tblPrefix :: Bool -> Int -> [Inline] + -- , lstPrefix :: Bool -> Int -> [Inline] + -- , secPrefix :: Bool -> Int -> [Inline] + -- , figPrefixTemplate :: Template + -- , eqnPrefixTemplate :: Template + -- , tblPrefixTemplate :: Template + -- , lstPrefixTemplate :: Template + -- , secPrefixTemplate :: Template , refIndexTemplate :: Template , subfigureRefIndexTemplate :: Template - , chapDelim :: [Inline] - , rangeDelim :: [Inline] - , pairDelim :: [Inline] - , lastDelim :: [Inline] - , refDelim :: [Inline] - , lofTitle :: [Block] - , lotTitle :: [Block] - , lolTitle :: [Block] + , chapDelim :: Inlines + , rangeDelim :: Inlines + , pairDelim :: Inlines + , lastDelim :: Inlines + , refDelim :: Inlines + -- , lofTitle :: [Block] + -- , lotTitle :: [Block] + -- , lolTitle :: [Block] , outFormat :: Maybe Format - , figureTemplate :: Template - , subfigureTemplate :: Template - , subfigureChildTemplate :: Template - , ccsTemplate :: Template - , tableTemplate :: Template - , listingTemplate :: Template - , customLabel :: String -> Int -> Maybe String - , ccsDelim :: [Inline] - , ccsLabelSep :: [Inline] + -- , figureTemplate :: Template + -- , subfigureTemplate :: Template + -- , subfigureChildTemplate :: Template + -- , ccsTemplate :: Template + -- , tableTemplate :: Template + -- , listingTemplate :: Template + -- , customLabel :: String -> Int -> Maybe String + , ccsDelim :: Inlines + , ccsLabelSep :: Inlines , tableEqns :: Bool , autoEqnLabels :: Bool , subfigGrid :: Bool , linkReferences :: Bool , nameInLink :: Bool + , prefixes :: Prefixes + -- TODO: Defaults for prefix settings } + +prefixList :: Options -> [String] +prefixList = M.keys . prefixes + +pfxCaptionTemplate :: Options -> String -> Maybe Template +pfxCaptionTemplate opts pfx = prefixCaptionTemplate <$> M.lookup pfx (prefixes opts) diff --git a/lib/Text/Pandoc/CrossRef/Util/Prefixes.hs b/lib/Text/Pandoc/CrossRef/Util/Prefixes.hs new file mode 100644 index 00000000..03e72610 --- /dev/null +++ b/lib/Text/Pandoc/CrossRef/Util/Prefixes.hs @@ -0,0 +1,64 @@ +{- +pandoc-crossref is a pandoc filter for numbering figures, +equations, tables and cross-references to them. +Copyright (C) 2017 Nikolay Yakimov + +This program is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License along +with this program; if not, write to the Free Software Foundation, Inc., +51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +-} + +{-# LANGUAGE FlexibleInstances #-} +module Text.Pandoc.CrossRef.Util.Prefixes where + +import Text.Pandoc.Definition +import Text.Pandoc.CrossRef.Util.Template +import Text.Pandoc.CrossRef.Util.Util +import Text.Pandoc.CrossRef.Util.Meta +import Text.Pandoc.CrossRef.Util.CustomLabels +import qualified Data.Map as M +import Text.Pandoc.Builder +import Data.Default +import Data.Maybe + +instance Default Inlines where + def = mempty + +getPrefixes :: String -> Meta -> Prefixes +getPrefixes varN dtv + | Just (MetaMap m) <- lookupMeta varN dtv = M.mapWithKey m2p m + | otherwise = error "Prefixes not defined" + where + m2p _ (MetaMap kv') = Prefix { + prefixRef = tryCapitalizeM (flip (getMetaList (toInlines "ref")) kv) "ref" + , prefixTitle = getMetaInlines "title" kv + , prefixCaptionTemplate = makeTemplate kv $ getMetaInlines "captionTemplate" kv + , prefixReferenceTemplate = makeTemplate kv $ getMetaInlines "referenceTemplate" kv + , prefixScope = getMetaStringMaybe "scope" kv + , prefixNumbering = mkLabel (varN <> "." <> "numbering") (fromMaybe (error "...") $ lookupMeta "numbering" kv) + , prefixListOfTitle = getMetaBlock "listOfTitle" kv + } + where kv = Meta kv' + m2p k _ = error $ "Invalid value for prefix " <> k + +type Prefixes = M.Map String Prefix + +data Prefix = Prefix { + prefixRef :: !(Bool -> Int -> Inlines) + , prefixTitle :: !Inlines + , prefixCaptionTemplate :: !Template + , prefixReferenceTemplate :: !Template + , prefixScope :: !(Maybe String) + , prefixNumbering :: !(Int -> String) + , prefixListOfTitle :: !Blocks +} diff --git a/lib/Text/Pandoc/CrossRef/Util/Settings.hs b/lib/Text/Pandoc/CrossRef/Util/Settings.hs index fb188916..6030cfc4 100644 --- a/lib/Text/Pandoc/CrossRef/Util/Settings.hs +++ b/lib/Text/Pandoc/CrossRef/Util/Settings.hs @@ -32,6 +32,7 @@ import System.Directory import System.FilePath import System.IO import qualified Data.Text as T +import qualified Data.Map as M getSettings :: Maybe Format -> Meta -> IO Meta getSettings fmt meta = do @@ -65,49 +66,71 @@ defaultMeta = <> autoSectionLabels False <> numberSections False <> sectionsDepth "0" - <> figLabels "arabic" - <> eqnLabels "arabic" - <> tblLabels "arabic" - <> lstLabels "arabic" - <> secLabels "arabic" - <> figureTitle (str "Figure") - <> tableTitle (str "Table") - <> listingTitle (str "Listing") + -- <> figLabels "arabic" + -- <> eqnLabels "arabic" + -- <> tblLabels "arabic" + -- <> lstLabels "arabic" + -- <> secLabels "arabic" + -- <> figureTitle (str "Figure") + -- <> tableTitle (str "Table") + -- <> listingTitle (str "Listing") <> titleDelim (str ":") <> chapDelim (str ".") <> rangeDelim (str "-") <> pairDelim (str "," <> space) <> lastDelim (str "," <> space) <> refDelim (str "," <> space) - <> figPrefix [str "fig.", str "figs."] - <> eqnPrefix [str "eq." , str "eqns."] - <> tblPrefix [str "tbl.", str "tbls."] - <> lstPrefix [str "lst.", str "lsts."] - <> secPrefix [str "sec.", str "secs."] - <> figPrefixTemplate (var "p" <> str "\160" <> var "i") - <> eqnPrefixTemplate (var "p" <> str "\160" <> var "i") - <> tblPrefixTemplate (var "p" <> str "\160" <> var "i") - <> lstPrefixTemplate (var "p" <> str "\160" <> var "i") - <> secPrefixTemplate (var "p" <> str "\160" <> var "i") + -- <> figPrefix [str "fig.", str "figs."] + -- <> eqnPrefix [str "eq." , str "eqns."] + -- <> tblPrefix [str "tbl.", str "tbls."] + -- <> lstPrefix [str "lst.", str "lsts."] + -- <> secPrefix [str "sec.", str "secs."] + -- <> figPrefixTemplate (var "p" <> str "\160" <> var "i") + -- <> eqnPrefixTemplate (var "p" <> str "\160" <> var "i") + -- <> tblPrefixTemplate (var "p" <> str "\160" <> var "i") + -- <> lstPrefixTemplate (var "p" <> str "\160" <> var "i") + -- <> secPrefixTemplate (var "p" <> str "\160" <> var "i") <> refIndexTemplate (var "i" <> var "suf") <> subfigureRefIndexTemplate (var "i" <> var "suf" <> space <> str "(" <> var "s" <> str ")") - <> lofTitle (header 1 $ text "List of Figures") - <> lotTitle (header 1 $ text "List of Tables") - <> lolTitle (header 1 $ text "List of Listings") - <> figureTemplate (var "figureTitle" <> space <> var "i" <> var "titleDelim" <> space <> var "t") - <> tableTemplate (var "tableTitle" <> space <> var "i" <> var "titleDelim" <> space <> var "t") - <> listingTemplate (var "listingTitle" <> space <> var "i" <> var "titleDelim" <> space <> var "t") + -- <> lofTitle (header 1 $ text "List of Figures") + -- <> lotTitle (header 1 $ text "List of Tables") + -- <> lolTitle (header 1 $ text "List of Listings") + -- <> figureTemplate (var "figureTitle" <> space <> var "i" <> var "titleDelim" <> space <> var "t") + -- <> tableTemplate (var "tableTitle" <> space <> var "i" <> var "titleDelim" <> space <> var "t") + -- <> listingTemplate (var "listingTitle" <> space <> var "i" <> var "titleDelim" <> space <> var "t") <> crossrefYaml "pandoc-crossref.yaml" <> chaptersDepth "1" - <> subfigureChildTemplate (var "i") - <> subfigureTemplate (var "figureTitle" <> space <> var "i" <> var "titleDelim" <> space <> var "t" <> str "." <> space <> var "ccs") - <> subfigLabels "alpha a" + -- <> subfigureChildTemplate (var "i") + -- <> subfigureTemplate (var "figureTitle" <> space <> var "i" <> var "titleDelim" <> space <> var "t" <> str "." <> space <> var "ccs") + -- <> subfigLabels "alpha a" <> ccsDelim (str "," <> space) <> ccsLabelSep (space <> str "—" <> space) - <> ccsTemplate (var "i" <> var "ccsLabelSep" <> var "t") + -- <> ccsTemplate (var "i" <> var "ccsLabelSep" <> var "t") <> tableEqns False <> autoEqnLabels False <> subfigGrid False <> linkReferences False <> nameInLink False + <> prefixes' [ + "eq" .: [ + "ref" .= ["eq.", "eqns."], + "title" .= text "Equation", + "captionTemplate" .= var "i", + "referenceTemplate" .= var "p" <> str "\160" <> var "i", + -- "scope" .= -, + "numbering" .= "arabic", + "listOfTitle" .= header 1 $ text "List of Equations" + ] + ] where var = displayMath + +prefixes' :: [(String, MetaValue)] -> Meta +prefixes' = prefixes . MetaMap . M.fromList + +infixr 0 .: +(.:) :: String -> [(String, MetaValue)] -> (String, MetaValue) +key .: val = (key, MetaMap $ M.fromList val) + +infixr 0 .= +(.=) :: ToMetaValue a => String -> a -> (String, MetaValue) +key .= val = (key, toMetaValue val) diff --git a/lib/Text/Pandoc/CrossRef/Util/Settings/Gen.hs b/lib/Text/Pandoc/CrossRef/Util/Settings/Gen.hs index bb8fac37..c67a9387 100644 --- a/lib/Text/Pandoc/CrossRef/Util/Settings/Gen.hs +++ b/lib/Text/Pandoc/CrossRef/Util/Settings/Gen.hs @@ -31,18 +31,18 @@ import Text.Pandoc.Definition nameDeriveSetters ''Options fmap concat $ mapM (makeAcc . mkName) - [ "figureTitle" - , "tableTitle" - , "listingTitle" - , "titleDelim" + -- [ "figureTitle" + -- , "tableTitle" + -- , "listingTitle" + [ "titleDelim" , "crossrefYaml" - , "subfigLabels" + -- , "subfigLabels" , "chapters" - , "figLabels" - , "eqnLabels" - , "tblLabels" - , "lstLabels" - , "secLabels" + -- , "figLabels" + -- , "eqnLabels" + -- , "tblLabels" + -- , "lstLabels" + -- , "secLabels" ] getOptions :: Meta -> Maybe Format -> Options diff --git a/lib/Text/Pandoc/CrossRef/Util/Settings/Template.hs b/lib/Text/Pandoc/CrossRef/Util/Settings/Template.hs index 08f498a7..98e1bdda 100644 --- a/lib/Text/Pandoc/CrossRef/Util/Settings/Template.hs +++ b/lib/Text/Pandoc/CrossRef/Util/Settings/Template.hs @@ -29,7 +29,7 @@ import Language.Haskell.TH hiding (Inline) import Language.Haskell.TH.Syntax hiding (Inline) import Data.List import Text.Pandoc.CrossRef.Util.Template -import Text.Pandoc.CrossRef.Util.CustomLabels (customLabel) +import Text.Pandoc.CrossRef.Util.Prefixes namedFields :: Con -> [VarStrictType] namedFields (RecC _ fs) = fs @@ -70,14 +70,15 @@ makeCon t cname = fromRecDef t cname makeCon' RecConE makeCon' :: Name -> Name -> Q [(Name, Exp)] makeCon' t accName = do VarI _ t' _ <- reify accName - funT <- [t|$(conT t) -> Bool -> Int -> [Inline]|] - inlT <- [t|$(conT t) -> [Inline]|] - blkT <- [t|$(conT t) -> [Block]|] + funT <- [t|$(conT t) -> Bool -> Int -> Inlines|] + inlT <- [t|$(conT t) -> Inlines|] + blkT <- [t|$(conT t) -> Blocks|] fmtT <- [t|$(conT t) -> Maybe Format|] boolT <- [t|$(conT t) -> Bool|] intT <- [t|$(conT t) -> Int|] tmplT <- [t|$(conT t) -> Template|] clT <- [t|$(conT t) -> String -> Int -> Maybe String|] + pfxT <- [t|$(conT t) -> Prefixes|] let varName | Name (OccName n) _ <- accName = liftString n let dtv = return $ VarE $ mkName "dtv" body <- @@ -90,5 +91,6 @@ makeCon' t accName = do | t' == tmplT -> [|makeTemplate $(dtv) $ getMetaInlines $(varName) $(dtv)|] | t' == clT -> [|customLabel $(dtv)|] | t' == fmtT -> return $ VarE $ mkName "fmt" + | t' == pfxT -> [|getPrefixes $(varName) $(dtv)|] | otherwise -> fail $ show t' return [(accName, body)] diff --git a/lib/Text/Pandoc/CrossRef/Util/Template.hs b/lib/Text/Pandoc/CrossRef/Util/Template.hs index 66c554b1..787c91f9 100644 --- a/lib/Text/Pandoc/CrossRef/Util/Template.hs +++ b/lib/Text/Pandoc/CrossRef/Util/Template.hs @@ -33,23 +33,24 @@ import Text.Pandoc.CrossRef.Util.Meta import Control.Applicative type VarFunc = String -> Maybe MetaValue -newtype Template = Template (VarFunc -> [Inline]) +newtype Template = Template (VarFunc -> Inlines) -makeTemplate :: Meta -> [Inline] -> Template -makeTemplate dtv xs' = Template $ \vf -> scan (\var -> vf var <|> lookupMeta var dtv) xs' +makeTemplate :: Meta -> Inlines -> Template +makeTemplate dtv xs' = Template $ \vf -> fromList $ scan (\var -> vf var <|> lookupMeta var dtv) $ toList xs' where + scan :: (String -> Maybe MetaValue) -> [Inline] -> [Inline] scan = bottomUp . go - go vf (x@(Math DisplayMath var):xs) = toList $ fromList (replaceVar var (vf var) [x]) <> fromList xs + go vf (x@(Math DisplayMath var):xs) = toList $ replaceVar var (vf var) (fromList [x]) <> fromList xs go _ (x:xs) = toList $ singleton x <> fromList xs go _ [] = [] replaceVar var val def' = maybe def' (toInlines ("variable " ++ var)) val -applyTemplate' :: Map String [Inline] -> Template -> [Inline] +applyTemplate' :: Map String Inlines -> Template -> Inlines applyTemplate' vars (Template g) = g internalVars where - internalVars x | Just v <- M.lookup x vars = Just $ MetaInlines v + internalVars x | Just v <- M.lookup x vars = Just $ MetaInlines $ toList v internalVars _ = Nothing -applyTemplate :: [Inline] -> [Inline] -> Template -> [Inline] +applyTemplate :: Inlines -> Inlines -> Template -> Inlines applyTemplate i t = applyTemplate' (fromDistinctAscList [("i", i), ("t", t)]) diff --git a/lib/Text/Pandoc/CrossRef/Util/Util.hs b/lib/Text/Pandoc/CrossRef/Util/Util.hs index d9a08408..abbcba67 100644 --- a/lib/Text/Pandoc/CrossRef/Util/Util.hs +++ b/lib/Text/Pandoc/CrossRef/Util/Util.hs @@ -30,8 +30,7 @@ import Text.Pandoc.Builder import Text.Pandoc.Class import Data.Char (toUpper, toLower, isUpper) import Data.List (isSuffixOf, isPrefixOf, stripPrefix) -import Data.Maybe (fromMaybe) -import Data.Generics +import Data.Generics hiding (Prefix) import Text.Pandoc.Writers.LaTeX import Data.Default import qualified Data.Text as T @@ -55,8 +54,8 @@ isFirstUpper :: String -> Bool isFirstUpper (x:_) = isUpper x isFirstUpper [] = False -chapPrefix :: [Inline] -> Index -> [Inline] -chapPrefix delim index = toList $ intercalate' (fromList delim) (map (str . uncurry (fromMaybe . show)) index) +chapPrefix :: Inlines -> Index -> Inlines +chapPrefix delim index = intercalate' delim (map (str . snd) index) data ReplacedResult a = Replaced Bool a | NotReplaced Bool type GenRR m = forall a. Data a => (a -> m (ReplacedResult a)) diff --git a/pandoc-crossref.cabal b/pandoc-crossref.cabal index fff806f3..9bf6a561 100644 --- a/pandoc-crossref.cabal +++ b/pandoc-crossref.cabal @@ -2,7 +2,7 @@ -- -- see: https://github.com/sol/hpack -- --- hash: bff6647405df1883495f3afdc5a0a7b789940dec86718c25961f35c1a017d42f +-- hash: 95eb0690f18bd5caa4d1af6048d9a14768b8076a2f39ecd3b58fada26f1a9af5 name: pandoc-crossref version: 0.3.0.0 @@ -98,6 +98,7 @@ library Text.Pandoc.CrossRef.Util.ModifyMeta Text.Pandoc.CrossRef.Util.Options Text.Pandoc.CrossRef.Util.PandocOrphans + Text.Pandoc.CrossRef.Util.Prefixes Text.Pandoc.CrossRef.Util.Settings Text.Pandoc.CrossRef.Util.Settings.Gen Text.Pandoc.CrossRef.Util.Settings.Template @@ -204,6 +205,7 @@ test-suite test-pandoc-crossref Text.Pandoc.CrossRef.Util.ModifyMeta Text.Pandoc.CrossRef.Util.Options Text.Pandoc.CrossRef.Util.PandocOrphans + Text.Pandoc.CrossRef.Util.Prefixes Text.Pandoc.CrossRef.Util.Settings Text.Pandoc.CrossRef.Util.Settings.Gen Text.Pandoc.CrossRef.Util.Settings.Template From 0fc3cb8833cdb477473b6d9bb1c909f96fd2478b Mon Sep 17 00:00:00 2001 From: Nikolay Yakimov Date: Fri, 29 Dec 2017 05:20:48 +0300 Subject: [PATCH 002/134] Bump dependencies --- stack.yaml | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/stack.yaml b/stack.yaml index 2f9d76be..f0977712 100644 --- a/stack.yaml +++ b/stack.yaml @@ -4,13 +4,14 @@ packages: - . extra-deps: - roman-numerals-0.5.1.5 -- pandoc-2.0.1.1 +- pandoc-2.0.6 - cmark-gfm-0.1.3 - doctemplates-0.2.1 -- hslua-0.9.2 -- pandoc-types-1.17.2 -- skylighting-0.4.3.2 -- texmath-0.10 -- pandoc-citeproc-0.11.1.3 +- hslua-0.9.3 +- hslua-module-text-0.1.2.1 +- pandoc-types-1.17.3 +- skylighting-0.5.0.1 +- texmath-0.10.1 +- pandoc-citeproc-0.12.2.2 - hs-bibutils-6.2.0.1 -resolver: lts-9.12 +resolver: lts-9.21 From fea6f5a6f936083834718a8955111b5b392bcdcf Mon Sep 17 00:00:00 2001 From: Nikolay Yakimov Date: Tue, 3 Apr 2018 03:43:26 +0300 Subject: [PATCH 003/134] Fix reference sequence compactification --- lib/Text/Pandoc/CrossRef/References/Refs.hs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/lib/Text/Pandoc/CrossRef/References/Refs.hs b/lib/Text/Pandoc/CrossRef/References/Refs.hs index 2a483258..5e5cd329 100644 --- a/lib/Text/Pandoc/CrossRef/References/Refs.hs +++ b/lib/Text/Pandoc/CrossRef/References/Refs.hs @@ -141,13 +141,13 @@ replaceRefsOther' prefix opts cits = do | nameInLink opts , [Link attr t (y, z)] <- toList x = linkWith attr y z (f $ fromList t) cmap f x = f x - return $ writePrefix (makeIndices opts indices) + return $ writePrefix (traceClone $ makeIndices opts indices) data RefData = RefData { rdLabel :: String , rdIdx :: Maybe Index , rdSubfig :: Maybe Index , rdSuffix :: Inlines - } deriving (Eq) + } deriving (Eq, Show) instance Ord RefData where (<=) = (<=) `on` rdIdx @@ -170,7 +170,7 @@ getRefIndex _prefix _opts Citation{citationId=cid,citationSuffix=suf} data RefItem = RefRange RefData RefData | RefSingle RefData makeIndices :: Options -> [RefData] -> Inlines -makeIndices o s = format $ concatMap f $ HT.groupBy g $ sort $ nub s +makeIndices o s = format $ concatMap f $ HT.groupBy g $ traceClone $ sort $ nub s where g :: RefData -> RefData -> Bool g a b = all (null . rdSuffix) [a, b] && ( @@ -183,7 +183,7 @@ makeIndices o s = format $ concatMap f $ HT.groupBy g $ sort $ nub s follows a b | Just (ai, al) <- HT.viewR a , Just (bi, bl) <- HT.viewR b - = ai == bi && A.first (+1) bl == al + = ai == bi && fst bl + 1 == fst al follows _ _ = False f :: [RefData] -> [RefItem] f [] = [] -- drop empty lists From 1b1f6a20fa06116180ed21c60ebfbe8943f8f709 Mon Sep 17 00:00:00 2001 From: Nikolay Yakimov Date: Tue, 3 Apr 2018 03:57:05 +0300 Subject: [PATCH 004/134] Reasonable defaults for prefix settings --- lib/Text/Pandoc/CrossRef/Util/Prefixes.hs | 15 ++++++++++----- 1 file changed, 10 insertions(+), 5 deletions(-) diff --git a/lib/Text/Pandoc/CrossRef/Util/Prefixes.hs b/lib/Text/Pandoc/CrossRef/Util/Prefixes.hs index 03e72610..31848878 100644 --- a/lib/Text/Pandoc/CrossRef/Util/Prefixes.hs +++ b/lib/Text/Pandoc/CrossRef/Util/Prefixes.hs @@ -39,13 +39,19 @@ getPrefixes varN dtv | Just (MetaMap m) <- lookupMeta varN dtv = M.mapWithKey m2p m | otherwise = error "Prefixes not defined" where + var = displayMath m2p _ (MetaMap kv') = Prefix { prefixRef = tryCapitalizeM (flip (getMetaList (toInlines "ref")) kv) "ref" - , prefixTitle = getMetaInlines "title" kv - , prefixCaptionTemplate = makeTemplate kv $ getMetaInlines "captionTemplate" kv - , prefixReferenceTemplate = makeTemplate kv $ getMetaInlines "referenceTemplate" kv + , prefixCaptionTemplate = makeTemplate kv $ + if isJust $ lookupMeta "captionTemplate" kv + then getMetaInlines "captionTemplate" kv + else var "title" <> space <> var "i" <> text ":" <> space <> var "t" + , prefixReferenceTemplate = makeTemplate kv $ + if isJust $ lookupMeta "referenceTemplate" kv + then getMetaInlines "referenceTemplate" kv + else var "p" <> str "\160" <> var "i" , prefixScope = getMetaStringMaybe "scope" kv - , prefixNumbering = mkLabel (varN <> "." <> "numbering") (fromMaybe (error "...") $ lookupMeta "numbering" kv) + , prefixNumbering = mkLabel (varN <> "." <> "numbering") (fromMaybe (MetaString "arabic") $ lookupMeta "numbering" kv) , prefixListOfTitle = getMetaBlock "listOfTitle" kv } where kv = Meta kv' @@ -55,7 +61,6 @@ type Prefixes = M.Map String Prefix data Prefix = Prefix { prefixRef :: !(Bool -> Int -> Inlines) - , prefixTitle :: !Inlines , prefixCaptionTemplate :: !Template , prefixReferenceTemplate :: !Template , prefixScope :: !(Maybe String) From cd9226f9d8aad7a0b010c545ac85636f71d88caa Mon Sep 17 00:00:00 2001 From: Nikolay Yakimov Date: Tue, 3 Apr 2018 03:57:18 +0300 Subject: [PATCH 005/134] More prefix settings --- lib/Text/Pandoc/CrossRef/Util/Settings.hs | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/lib/Text/Pandoc/CrossRef/Util/Settings.hs b/lib/Text/Pandoc/CrossRef/Util/Settings.hs index 260478ea..0017188d 100644 --- a/lib/Text/Pandoc/CrossRef/Util/Settings.hs +++ b/lib/Text/Pandoc/CrossRef/Util/Settings.hs @@ -116,12 +116,18 @@ defaultMeta = <> prefixes' [ "eq" .: [ "ref" .= ["eq.", "eqns."], - "title" .= text "Equation", "captionTemplate" .= var "i", - "referenceTemplate" .= var "p" <> str "\160" <> var "i", - -- "scope" .= -, - "numbering" .= "arabic", "listOfTitle" .= header 1 $ text "List of Equations" + ], + "fig" .: [ + "ref" .= ["fig.", "figs."], + "title" .= text "Figure", + "listOfTitle" .= header 1 $ text "List of Figures" + ], + "lst" .: [ + "ref" .= ["lst.", "lsts."], + "title" .= text "Listing", + "listOfTitle" .= header 1 $ text "List of Listings" ] ] where var = displayMath From eebad201ce7b9fe4f5be8de0893aecbfd5aabc0b Mon Sep 17 00:00:00 2001 From: Nikolay Yakimov Date: Tue, 3 Apr 2018 05:05:40 +0300 Subject: [PATCH 006/134] Bring subfigures back Note: this also adds special syntax to templates allowing to specify custom prefix for templates; It also strips any undefined variables from templates. --- lib/Text/Pandoc/CrossRef/References/Blocks.hs | 208 +++++++++--------- lib/Text/Pandoc/CrossRef/Util/Options.hs | 12 +- lib/Text/Pandoc/CrossRef/Util/Prefixes.hs | 5 +- lib/Text/Pandoc/CrossRef/Util/Settings.hs | 6 +- lib/Text/Pandoc/CrossRef/Util/Template.hs | 10 +- 5 files changed, 128 insertions(+), 113 deletions(-) diff --git a/lib/Text/Pandoc/CrossRef/References/Blocks.hs b/lib/Text/Pandoc/CrossRef/References/Blocks.hs index dcf92c4f..f24a39ed 100644 --- a/lib/Text/Pandoc/CrossRef/References/Blocks.hs +++ b/lib/Text/Pandoc/CrossRef/References/Blocks.hs @@ -39,6 +39,7 @@ import Text.Pandoc.CrossRef.Util.Options import Text.Pandoc.CrossRef.Util.Prefixes import Text.Pandoc.CrossRef.Util.Template import Control.Applicative +import Data.Default (def) import Prelude replaceAll :: (Data a) => Options -> a -> WS a @@ -88,85 +89,86 @@ replaceBlock opts (Header n (label, cls, attrs) text') ]) $ secHeaderTemplate opts | otherwise = fromList text' replaceNoRecurse $ Header n (label', cls, attrs) $ toList textCC --- subfigures --- replaceBlock opts (Div (label,cls,attrs) images) --- | "fig:" `isPrefixOf` label --- , Para caption <- last images --- = do --- idxStr <- replaceAttr opts (Right label) (lookup "label" attrs) caption imgRefs --- let (cont, st) = runState (runReplace (mkRR $ replaceSubfigs opts') $ init images) def --- collectedCaptions = B.toList $ --- intercalate' (B.fromList $ ccsDelim opts) --- $ map (B.fromList . collectCaps . snd) --- $ sortOn (refIndex . snd) --- $ filter (not . null . refTitle . snd) --- $ M.toList --- $ imgRefs_ st --- collectCaps v = --- applyTemplate --- (chapPrefix (chapDelim opts) (refIndex v)) --- (refTitle v) --- (ccsTemplate opts) --- vars = M.fromDistinctAscList --- [ ("ccs", collectedCaptions) --- , ("i", idxStr) --- , ("t", caption) --- ] --- capt = applyTemplate' vars $ subfigureTemplate opts --- lastRef <- fromJust . M.lookup label <$> get imgRefs --- modify imgRefs $ \old -> --- M.union --- old --- (M.map (\v -> v{refIndex = refIndex lastRef, refSubfigure = Just $ refIndex v}) --- $ imgRefs_ st) --- case outFormat opts of --- f | isLatexFormat f -> --- replaceNoRecurse $ Div nullAttr $ --- [ RawBlock (Format "latex") "\\begin{figure}\n\\centering" ] --- ++ cont ++ --- [ Para [RawInline (Format "latex") "\\caption" --- , Span nullAttr caption] --- , RawBlock (Format "latex") $ mkLaTeXLabel label --- , RawBlock (Format "latex") "\\end{figure}"] --- _ -> replaceNoRecurse $ Div (label, "subfigures":cls, attrs) $ toTable cont capt --- where --- opts' = opts --- { figureTemplate = subfigureChildTemplate opts --- , customLabel = \r i -> customLabel opts ("sub"++r) i --- } --- toTable :: [Block] -> [Inline] -> [Block] --- toTable blks capt --- | subfigGrid opts = [Table [] align widths [] $ map blkToRow blks, mkCaption opts "Image Caption" capt] --- | otherwise = blks ++ [mkCaption opts "Image Caption" capt] --- where --- align | Para ils:_ <- blks = replicate (length $ mapMaybe getWidth ils) AlignCenter --- | otherwise = error "Misformatted subfigures block" --- widths | Para ils:_ <- blks --- = fixZeros $ mapMaybe getWidth ils --- | otherwise = error "Misformatted subfigures block" --- getWidth (Image (_id, _class, as) _ _) --- = Just $ maybe 0 percToDouble $ lookup "width" as --- getWidth _ = Nothing --- fixZeros :: [Double] -> [Double] --- fixZeros ws --- = let nz = length $ filter (== 0) ws --- rzw = (0.99 - sum ws) / fromIntegral nz --- in if nz>0 --- then map (\x -> if x == 0 then rzw else x) ws --- else ws --- percToDouble :: String -> Double --- percToDouble percs --- | '%' <- last percs --- , perc <- read $ init percs --- = perc/100.0 --- | otherwise = error "Only percent allowed in subfigure width!" --- blkToRow :: Block -> [[Block]] --- blkToRow (Para inls) = mapMaybe inlToCell inls --- blkToRow x = [[x]] --- inlToCell :: Inline -> Maybe [Block] --- inlToCell (Image (id', cs, as) txt tgt) = Just [Para [Image (id', cs, setW as) txt tgt]] --- inlToCell _ = Nothing --- setW as = ("width", "100%"):filter ((/="width") . fst) as +-- sub-objects +replaceBlock opts (Div (label,cls,attrs) images) + | Just pfx <- getRefPrefix opts label + , Para caption <- last images + = do + idxStr <- replaceAttr opts (Right label) (lookup "label" attrs) (fromList caption) pfx + let (cont, st) = runState (runReplace (mkRR $ replaceSubfigs opts') $ init images) def + collectedCaptions = toList $ + intercalate' (ccsDelim opts) + $ map (collectCaps . snd) + $ sortOn (refIndex . snd) + $ filter (not . null . refTitle . snd) + $ M.toList + $ referenceData_ st + collectCaps v = + applyTemplate + (chapPrefix (chapDelim opts) (refIndex v)) + (refTitle v) + (ccsTemplate opts) + vars = M.fromDistinctAscList + [ ("ccs", fromList collectedCaptions) + , ("i", idxStr) + , ("t", fromList caption) + ] + capt = applyTemplate' vars $ pfxCaptionTemplate opts pfx + opts' = opts { + prefixes = case M.lookup ("sub" <> pfx) $ prefixes opts of + Just sp -> M.insert pfx sp $ prefixes opts + Nothing -> prefixes opts + } + lastRef <- fromJust . M.lookup label <$> get referenceData + modify referenceData $ \old -> + M.union + old + (M.map (\v -> v{refIndex = refIndex lastRef, refSubfigure = Just $ refIndex v}) + $ referenceData_ st) + case outFormat opts of + f | isLatexFormat f -> + replaceNoRecurse $ Div nullAttr $ + [ RawBlock (Format "latex") "\\begin{figure}\n\\centering" ] + ++ cont ++ + [ Para [RawInline (Format "latex") "\\caption" + , Span nullAttr caption] + , RawBlock (Format "latex") $ mkLaTeXLabel label + , RawBlock (Format "latex") "\\end{figure}"] + _ -> replaceNoRecurse $ Div (label, "subfigures":cls, attrs) $ toTable cont capt + where + toTable :: [Block] -> Inlines -> [Block] + toTable blks capt + | subfigGrid opts = [Table [] align widths [] $ map blkToRow blks, mkCaption opts "Image Caption" capt] + | otherwise = blks ++ [mkCaption opts "Image Caption" capt] + where + align | Para ils:_ <- blks = replicate (length $ mapMaybe getWidth ils) AlignCenter + | otherwise = error "Misformatted subfigures block" + widths | Para ils:_ <- blks + = fixZeros $ mapMaybe getWidth ils + | otherwise = error "Misformatted subfigures block" + getWidth (Image (_id, _class, as) _ _) + = Just $ maybe 0 percToDouble $ lookup "width" as + getWidth _ = Nothing + fixZeros :: [Double] -> [Double] + fixZeros ws + = let nz = length $ filter (== 0) ws + rzw = (0.99 - sum ws) / fromIntegral nz + in if nz>0 + then map (\x -> if x == 0 then rzw else x) ws + else ws + percToDouble :: String -> Double + percToDouble percs + | '%' <- last percs + , perc <- read $ init percs + = perc/100.0 + | otherwise = error "Only percent allowed in subfigure width!" + blkToRow :: Block -> [[Block]] + blkToRow (Para inls) = mapMaybe inlToCell inls + blkToRow x = [[x]] + inlToCell :: Inline -> Maybe [Block] + inlToCell (Image (id', cs, as) txt tgt) = Just [Para [Image (id', cs, setW as) txt tgt]] + inlToCell _ = Nothing + setW as = ("width", "100%"):filter ((/="width") . fst) as replaceBlock opts (Div divOps@(label,_,attrs) [Table title align widths header cells]) | not $ null title , Just pfx <- getRefPrefix opts label @@ -177,7 +179,7 @@ replaceBlock opts (Div divOps@(label,_,attrs) [Table title align widths header c case outFormat opts of f | isLatexFormat f -> rawInline "latex" (mkLaTeXLabel label) <> ititle - _ -> applyTemplate idxStr ititle $ fromJust $ pfxCaptionTemplate opts pfx + _ -> applyTemplate idxStr ititle $ pfxCaptionTemplate opts pfx replaceNoRecurse $ Div divOps [Table title' align widths header cells] replaceBlock opts cb@(CodeBlock (label, classes, attrs) code) | not $ null label @@ -202,7 +204,7 @@ replaceBlock opts cb@(CodeBlock (label, classes, attrs) code) _ -> do let cap = text caption idxStr <- replaceAttr opts (Right label) (lookup "label" attrs) cap pfx - let caption' = applyTemplate idxStr cap $ fromJust $ pfxCaptionTemplate opts pfx + let caption' = applyTemplate idxStr cap $ pfxCaptionTemplate opts pfx replaceNoRecurse $ Div (label, "listing":classes, []) [ mkCaption opts "Caption" caption' , CodeBlock ([], classes, attrs \\ [("caption", caption)]) code @@ -231,7 +233,7 @@ replaceBlock opts _ -> do let icaption = fromList caption idxStr <- replaceAttr opts (Right label) (lookup "label" attrs) icaption pfx - let caption' = applyTemplate idxStr icaption $ fromJust $ pfxCaptionTemplate opts pfx + let caption' = applyTemplate idxStr icaption $ pfxCaptionTemplate opts pfx replaceNoRecurse $ Div (label, "listing":classes, []) [ mkCaption opts "Caption" caption' , CodeBlock ([], classes, attrs) code @@ -282,31 +284,31 @@ replaceInline opts (Image attr@(label,_,attrs) alt img@(_, tit)) idxStr <- replaceAttr opts (Right label) (lookup "label" attrs) ialt pfx let alt' = toList $ case outFormat opts of f | isLatexFormat f -> ialt - _ -> applyTemplate idxStr ialt $ fromJust $ pfxCaptionTemplate opts pfx + _ -> applyTemplate idxStr ialt $ pfxCaptionTemplate opts pfx replaceNoRecurse $ Image attr alt' img replaceInline _ _ = noReplaceRecurse --- replaceSubfigs :: Options -> [Inline] -> WS (ReplacedResult [Inline]) --- replaceSubfigs opts = (replaceNoRecurse . concat =<<) . mapM (replaceSubfig opts) +replaceSubfigs :: Options -> [Inline] -> WS (ReplacedResult [Inline]) +replaceSubfigs opts = (replaceNoRecurse . concat =<<) . mapM (replaceSubfig opts) --- replaceSubfig :: Options -> Inline -> WS [Inline] --- replaceSubfig opts x@(Image (label,cls,attrs) alt (src, tit)) --- = do --- let label' | "fig:" `isPrefixOf` label = Right label --- | null label = Left "fig" --- | otherwise = Right $ "fig:" ++ label --- let ialt = fromList alt --- idxStr <- replaceAttr opts label' (lookup "label" attrs) ialt --- case outFormat opts of --- f | isLatexFormat f -> --- return $ latexSubFigure x label --- _ -> --- let alt' = toList $ applyTemplate idxStr ialt $ fromJust $ pfxCaptionTemplate opts pfx --- tit' | "nocaption" `elem` cls = fromMaybe tit $ stripPrefix "fig:" tit --- | "fig:" `isPrefixOf` tit = tit --- | otherwise = "fig:" ++ tit --- in return [Image (label, cls, attrs) alt' (src, tit')] --- replaceSubfig _ x = return [x] +replaceSubfig :: Options -> Inline -> WS [Inline] +replaceSubfig opts x@(Image (label,cls,attrs) alt (src, tit)) + = do + let label' | "fig:" `isPrefixOf` label = Right label + | null label = Left "fig" + | otherwise = Right $ "fig:" ++ label + let ialt = fromList alt + idxStr <- replaceAttr opts label' (lookup "label" attrs) ialt "fig" + case outFormat opts of + f | isLatexFormat f -> + return $ latexSubFigure x label + _ -> + let alt' = toList $ applyTemplate idxStr ialt $ pfxCaptionTemplate opts "fig" + tit' | "nocaption" `elem` cls = fromMaybe tit $ stripPrefix "fig:" tit + | "fig:" `isPrefixOf` tit = tit + | otherwise = "fig:" ++ tit + in return [Image (label, cls, attrs) alt' (src, tit')] +replaceSubfig _ x = return [x] divBlocks :: Block -> Block divBlocks (Table title align widths header cells) diff --git a/lib/Text/Pandoc/CrossRef/Util/Options.hs b/lib/Text/Pandoc/CrossRef/Util/Options.hs index 5bf786ab..07dcbef0 100644 --- a/lib/Text/Pandoc/CrossRef/Util/Options.hs +++ b/lib/Text/Pandoc/CrossRef/Util/Options.hs @@ -24,6 +24,7 @@ import Text.Pandoc.CrossRef.Util.Template import Text.Pandoc.CrossRef.Util.Prefixes import qualified Data.Map as M import Text.Pandoc.Builder +import Data.Maybe data Options = Options { cref :: Bool , chaptersDepth :: Int @@ -57,7 +58,7 @@ data Options = Options { cref :: Bool -- , figureTemplate :: Template -- , subfigureTemplate :: Template -- , subfigureChildTemplate :: Template - -- , ccsTemplate :: Template + , ccsTemplate :: Template -- , tableTemplate :: Template -- , listingTemplate :: Template -- , customLabel :: String -> Int -> Maybe String @@ -75,5 +76,10 @@ data Options = Options { cref :: Bool prefixList :: Options -> [String] prefixList = M.keys . prefixes -pfxCaptionTemplate :: Options -> String -> Maybe Template -pfxCaptionTemplate opts pfx = prefixCaptionTemplate <$> M.lookup pfx (prefixes opts) +pfxCaptionTemplate :: Options -> String -> Template +pfxCaptionTemplate opts pfx = prefixCaptionTemplate $ getPfx opts pfx + +getPfx :: Options -> String -> Prefix +getPfx o pn = fromMaybe defaultPfx $ M.lookup pn $ prefixes o + where + defaultPfx = error $ "Undefined prefix: \"" <> pn <> "\"" diff --git a/lib/Text/Pandoc/CrossRef/Util/Prefixes.hs b/lib/Text/Pandoc/CrossRef/Util/Prefixes.hs index 31848878..9c802430 100644 --- a/lib/Text/Pandoc/CrossRef/Util/Prefixes.hs +++ b/lib/Text/Pandoc/CrossRef/Util/Prefixes.hs @@ -23,7 +23,6 @@ module Text.Pandoc.CrossRef.Util.Prefixes where import Text.Pandoc.Definition import Text.Pandoc.CrossRef.Util.Template -import Text.Pandoc.CrossRef.Util.Util import Text.Pandoc.CrossRef.Util.Meta import Text.Pandoc.CrossRef.Util.CustomLabels import qualified Data.Map as M @@ -45,7 +44,7 @@ getPrefixes varN dtv , prefixCaptionTemplate = makeTemplate kv $ if isJust $ lookupMeta "captionTemplate" kv then getMetaInlines "captionTemplate" kv - else var "title" <> space <> var "i" <> text ":" <> space <> var "t" + else var "title" <> space <> var "i" <> var "titleDelim" <> space <> var "t" <> var "ccs#. " , prefixReferenceTemplate = makeTemplate kv $ if isJust $ lookupMeta "referenceTemplate" kv then getMetaInlines "referenceTemplate" kv @@ -54,7 +53,7 @@ getPrefixes varN dtv , prefixNumbering = mkLabel (varN <> "." <> "numbering") (fromMaybe (MetaString "arabic") $ lookupMeta "numbering" kv) , prefixListOfTitle = getMetaBlock "listOfTitle" kv } - where kv = Meta kv' + where kv = dtv <> Meta kv' m2p k _ = error $ "Invalid value for prefix " <> k type Prefixes = M.Map String Prefix diff --git a/lib/Text/Pandoc/CrossRef/Util/Settings.hs b/lib/Text/Pandoc/CrossRef/Util/Settings.hs index 0017188d..b52b18a5 100644 --- a/lib/Text/Pandoc/CrossRef/Util/Settings.hs +++ b/lib/Text/Pandoc/CrossRef/Util/Settings.hs @@ -107,7 +107,7 @@ defaultMeta = -- <> subfigLabels "alpha a" <> ccsDelim (str "," <> space) <> ccsLabelSep (space <> str "—" <> space) - -- <> ccsTemplate (var "i" <> var "ccsLabelSep" <> var "t") + <> ccsTemplate (var "i" <> var "ccsLabelSep" <> var "t") <> tableEqns False <> autoEqnLabels False <> subfigGrid False @@ -124,6 +124,10 @@ defaultMeta = "title" .= text "Figure", "listOfTitle" .= header 1 $ text "List of Figures" ], + "subfig" .: [ + "captionTemplate" .= var "i", + "numbering" .= "alpha a" + ], "lst" .: [ "ref" .= ["lst.", "lsts."], "title" .= text "Listing", diff --git a/lib/Text/Pandoc/CrossRef/Util/Template.hs b/lib/Text/Pandoc/CrossRef/Util/Template.hs index c2ae486e..78fb7183 100644 --- a/lib/Text/Pandoc/CrossRef/Util/Template.hs +++ b/lib/Text/Pandoc/CrossRef/Util/Template.hs @@ -50,11 +50,15 @@ makeTemplate dtv xs' = Template $ \vf -> fromList $ scan (\var -> vf var <|> loo i <- idx v <- lookupMeta vn dtv getList i v - in toList $ (replaceVar var arr (fromList [x])) <> fromList xs - | otherwise = toList $ (replaceVar var (vf var) (fromList [x])) <> fromList xs + in toList $ (replaceVar arr id) <> fromList xs + | '#' `elem` var = + let (vn, pfx') = span (/='#') var + pfx = drop 1 pfx' + in toList $ (replaceVar (vf vn) (text pfx <>)) <> fromList xs + | otherwise = toList $ (replaceVar (vf var) id) <> fromList xs + where replaceVar val m = maybe mempty (m . toInlines ("variable " ++ var)) val go _ (x:xs) = toList $ singleton x <> fromList xs go _ [] = [] - replaceVar var val def' = maybe def' (toInlines ("variable " ++ var)) val applyTemplate' :: M.Map String Inlines -> Template -> Inlines applyTemplate' vars (Template g) = g internalVars From 36b35315de73882269e84e585336580c83288cbf Mon Sep 17 00:00:00 2001 From: Nikolay Yakimov Date: Tue, 3 Apr 2018 05:16:05 +0300 Subject: [PATCH 007/134] Add prefix defns for tables and sections --- lib/Text/Pandoc/CrossRef/Util/Settings.hs | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/lib/Text/Pandoc/CrossRef/Util/Settings.hs b/lib/Text/Pandoc/CrossRef/Util/Settings.hs index b52b18a5..71efefcc 100644 --- a/lib/Text/Pandoc/CrossRef/Util/Settings.hs +++ b/lib/Text/Pandoc/CrossRef/Util/Settings.hs @@ -132,6 +132,16 @@ defaultMeta = "ref" .= ["lst.", "lsts."], "title" .= text "Listing", "listOfTitle" .= header 1 $ text "List of Listings" + ], + "tbl" .: [ + "ref" .= ["tbl.", "tbls."], + "title" .= text "Table", + "listOfTitle" .= header 1 $ text "List of Tables" + ], + "sec" .: [ + "ref" .= ["sec.", "secs."], + "title" .= text "Section", + "listOfTitle" .= header 1 $ text "List of Sections" ] ] where var = displayMath From 38daf9ee2d47b42d0098d59634bc8156cfd7db0e Mon Sep 17 00:00:00 2001 From: Nikolay Yakimov Date: Tue, 3 Apr 2018 05:16:18 +0300 Subject: [PATCH 008/134] Fix basic test --- test/test-pandoc-crossref.hs | 118 +++++++++++++++++------------------ 1 file changed, 59 insertions(+), 59 deletions(-) diff --git a/test/test-pandoc-crossref.hs b/test/test-pandoc-crossref.hs index 1e8072c2..03f8370c 100644 --- a/test/test-pandoc-crossref.hs +++ b/test/test-pandoc-crossref.hs @@ -51,7 +51,7 @@ main = hspec $ do it "Labels equations" $ testAll (equation' "a^2+b^2=c^2" "equation") (spanWith ("eq:equation", [], []) (equation' "a^2+b^2=c^2\\qquad(1)" []), - eqnRefs =: M.fromList $ refRec'' "eq:equation" 1) + referenceData =: M.fromList $ refRec'' "eq:equation" 1) it "Labels equations in the middle of text" $ testAll ( text "This is an equation: " @@ -61,7 +61,7 @@ main = hspec $ do text "This is an equation: " <> spanWith ("eq:equation", [], []) (equation' "a^2+b^2=c^2\\qquad(1)" []) <> text " it should be labeled", - eqnRefs =: M.fromList $ refRec'' "eq:equation" 1) + referenceData =: M.fromList $ refRec'' "eq:equation" 1) it "Labels equations in the beginning of text" $ testAll ( equation' "a^2+b^2=c^2" "equation" @@ -69,7 +69,7 @@ main = hspec $ do ( spanWith ("eq:equation", [], []) (equation' "a^2+b^2=c^2\\qquad(1)" []) <> text " it should be labeled", - eqnRefs =: M.fromList $ refRec'' "eq:equation" 1) + referenceData =: M.fromList $ refRec'' "eq:equation" 1) it "Labels equations in the end of text" $ testAll ( text "This is an equation: " @@ -77,7 +77,7 @@ main = hspec $ do ( text "This is an equation: " <> spanWith ("eq:equation", [], []) (equation' "a^2+b^2=c^2\\qquad(1)" []), - eqnRefs =: M.fromList $ refRec'' "eq:equation" 1) + referenceData =: M.fromList $ refRec'' "eq:equation" 1) -- TODO: -- describe "References.Blocks.spanInlines" @@ -87,7 +87,7 @@ main = hspec $ do it "Labels images" $ testAll (figure "test.jpg" [] "Test figure" "figure") (figure "test.jpg" [] "Figure 1: Test figure" "figure", - imgRefs =: M.fromList $ refRec' "fig:figure" 1 "Test figure") + referenceData =: M.fromList $ refRec' "fig:figure" 1 "Test figure") it "Labels subfigures" $ testAll ( divWith ("fig:subfigure",[],[]) ( @@ -112,36 +112,36 @@ main = hspec $ do <> para (figure' "fig:" "test22.jpg" [] "b" "figure22") <> para (text "Figure 2: figure caption 2. a — Test figure 21, b — Test figure 22") ) - , imgRefs =: M.fromList [("fig:figure1",RefRec { - refIndex = [(1,Nothing)], - refTitle = [Str "Test",Space,Str "figure",Space,Str "1"], - refSubfigure = Just [(1, Just "a")]}), + , referenceData =: M.fromList [("fig:figure1",RefRec { + refIndex = [(1,"1")], + refTitle = fromList [Str "Test",Space,Str "figure",Space,Str "1"], + refSubfigure = Just [(1, "a")]}), ("fig:figure2",RefRec { - refIndex = [(1,Nothing)], - refTitle = [Str "Test",Space,Str "figure",Space,Str "2"], - refSubfigure = Just [(2, Just "b")]}), + refIndex = [(1,"1")], + refTitle = fromList [Str "Test",Space,Str "figure",Space,Str "2"], + refSubfigure = Just [(2, "b")]}), ("fig:subfigure",RefRec { - refIndex = [(1,Nothing)], - refTitle = [Str "figure",Space,Str "caption"], + refIndex = [(1,"1")], + refTitle = fromList [Str "figure",Space,Str "caption"], refSubfigure = Nothing}), ("fig:figure21",RefRec { - refIndex = [(2,Nothing)], - refTitle = [Str "Test",Space,Str "figure",Space,Str "21"], - refSubfigure = Just [(1, Just "a")]}), + refIndex = [(2,"2")], + refTitle = fromList [Str "Test",Space,Str "figure",Space,Str "21"], + refSubfigure = Just [(1, "a")]}), ("fig:figure22",RefRec { - refIndex = [(2,Nothing)], - refTitle = [Str "Test",Space,Str "figure",Space,Str "22"], - refSubfigure = Just [(2, Just "b")]}), + refIndex = [(2,"2")], + refTitle = fromList [Str "Test",Space,Str "figure",Space,Str "22"], + refSubfigure = Just [(2, "b")]}), ("fig:subfigure2",RefRec { - refIndex = [(2,Nothing)], - refTitle = [Str "figure",Space,Str "caption",Space,Str "2"], + refIndex = [(2,"2")], + refTitle = fromList [Str "figure",Space,Str "caption",Space,Str "2"], refSubfigure = Nothing}) ] ) it "Labels equations" $ testAll (equation "a^2+b^2=c^2" "equation") (para $ spanWith ("eq:equation", [], []) (equation' "a^2+b^2=c^2\\qquad(1)" []), - eqnRefs =: M.fromList $ refRec'' "eq:equation" 1) + referenceData =: M.fromList $ refRec'' "eq:equation" 1) it "Labels equations in the middle of text" $ testAll (para $ text "This is an equation: " @@ -151,7 +151,7 @@ main = hspec $ do text "This is an equation: " <> spanWith ("eq:equation", [], []) (equation' "a^2+b^2=c^2\\qquad(1)" []) <> text " it should be labeled", - eqnRefs =: M.fromList $ refRec'' "eq:equation" 1) + referenceData =: M.fromList $ refRec'' "eq:equation" 1) it "Labels equations in the beginning of text" $ testAll (para $ equation' "a^2+b^2=c^2" "equation" @@ -159,7 +159,7 @@ main = hspec $ do (para $ spanWith ("eq:equation", [], []) (equation' "a^2+b^2=c^2\\qquad(1)" []) <> text " it should be labeled", - eqnRefs =: M.fromList $ refRec'' "eq:equation" 1) + referenceData =: M.fromList $ refRec'' "eq:equation" 1) it "Labels equations in the end of text" $ testAll (para $ text "This is an equation: " @@ -167,79 +167,79 @@ main = hspec $ do (para $ text "This is an equation: " <> spanWith ("eq:equation", [], []) (equation' "a^2+b^2=c^2\\qquad(1)" []), - eqnRefs =: M.fromList $ refRec'' "eq:equation" 1) + referenceData =: M.fromList $ refRec'' "eq:equation" 1) it "Labels tables" $ testAll (table' "Test table" "table") (divWith ("tbl:table", [], []) $ table' "Table 1: Test table" [], - tblRefs =: M.fromList $ refRec' "tbl:table" 1 "Test table") + referenceData =: M.fromList $ refRec' "tbl:table" 1 "Test table") it "Labels code blocks" $ testAll (codeBlock' "Test code block" "codeblock") (codeBlockDiv "Listing 1: Test code block" "codeblock", - lstRefs =: M.fromList $ refRec' "lst:codeblock" 1 "Test code block") + referenceData =: M.fromList $ refRec' "lst:codeblock" 1 "Test code block") it "Labels code block divs" $ testAll (codeBlockDiv "Test code block" "codeblock") (codeBlockDiv "Listing 1: Test code block" "codeblock", - lstRefs =: M.fromList $ refRec' "lst:codeblock" 1 "Test code block") + referenceData =: M.fromList $ refRec' "lst:codeblock" 1 "Test code block") it "Labels sections divs" $ testAll (section "Section Header" 1 "section") (section "Section Header" 1 "section", - secRefs ^= M.fromList (refRec' "sec:section" 1 "Section Header") - $ curChap =: [(1,Nothing)]) + referenceData ^= M.fromList (refRec' "sec:section" 1 "Section Header") + $ curChap =: [(1,"1")]) describe "References.Refs.replaceRefs" $ do it "References one image" $ - testRefs' "fig:" [1] [4] imgRefs "fig.\160\&4" + testRefs' "fig:" [1] [4] referenceData "fig.\160\&4" it "References multiple images" $ - testRefs' "fig:" [1..3] [4..6] imgRefs "figs.\160\&4-6" + testRefs' "fig:" [1..3] [4..6] referenceData "figs.\160\&4-6" it "References one equation" $ - testRefs' "eq:" [1] [4] eqnRefs "eq.\160\&4" + testRefs' "eq:" [1] [4] referenceData "eq.\160\&4" it "References multiple equations" $ - testRefs' "eq:" [1..3] [4..6] eqnRefs "eqns.\160\&4-6" + testRefs' "eq:" [1..3] [4..6] referenceData "eqns.\160\&4-6" it "References one table" $ - testRefs' "tbl:" [1] [4] tblRefs "tbl.\160\&4" + testRefs' "tbl:" [1] [4] referenceData "tbl.\160\&4" it "References multiple tables" $ - testRefs' "tbl:" [1..3] [4..6] tblRefs "tbls.\160\&4-6" + testRefs' "tbl:" [1..3] [4..6] referenceData "tbls.\160\&4-6" it "References one listing" $ - testRefs' "lst:" [1] [4] lstRefs "lst.\160\&4" + testRefs' "lst:" [1] [4] referenceData "lst.\160\&4" it "References multiple listings" $ - testRefs' "lst:" [1..3] [4..6] lstRefs "lsts.\160\&4-6" + testRefs' "lst:" [1..3] [4..6] referenceData "lsts.\160\&4-6" it "References one section" $ - testRefs' "sec:" [1] [4] secRefs "sec.\160\&4" + testRefs' "sec:" [1] [4] referenceData "sec.\160\&4" it "References multiple sections" $ - testRefs' "sec:" [1..3] [4..6] secRefs "secs.\160\&4-6" + testRefs' "sec:" [1..3] [4..6] referenceData "secs.\160\&4-6" it "Separates references to different chapter items by a comma" $ - testRefs'' "lst:" [1..6] (zip [1,1..] [4..6] ++ zip [2,2..] [7..9]) lstRefs "lsts.\160\&1.4-1.6, 2.7-2.9" + testRefs'' "lst:" [1..6] (zip [1,1..] [4..6] ++ zip [2,2..] [7..9]) referenceData "lsts.\160\&1.4-1.6, 2.7-2.9" describe "References.Refs.replaceRefs capitalization" $ do it "References one image" $ - testRefs' "Fig:" [1] [4] imgRefs "Fig.\160\&4" + testRefs' "Fig:" [1] [4] referenceData "Fig.\160\&4" it "References multiple images" $ - testRefs' "Fig:" [1..3] [4..6] imgRefs "Figs.\160\&4-6" + testRefs' "Fig:" [1..3] [4..6] referenceData "Figs.\160\&4-6" it "References one equation" $ - testRefs' "Eq:" [1] [4] eqnRefs "Eq.\160\&4" + testRefs' "Eq:" [1] [4] referenceData "Eq.\160\&4" it "References multiple equations" $ - testRefs' "Eq:" [1..3] [4..6] eqnRefs "Eqns.\160\&4-6" + testRefs' "Eq:" [1..3] [4..6] referenceData "Eqns.\160\&4-6" it "References one table" $ - testRefs' "Tbl:" [1] [4] tblRefs "Tbl.\160\&4" + testRefs' "Tbl:" [1] [4] referenceData "Tbl.\160\&4" it "References multiple tables" $ - testRefs' "Tbl:" [1..3] [4..6] tblRefs "Tbls.\160\&4-6" + testRefs' "Tbl:" [1..3] [4..6] referenceData "Tbls.\160\&4-6" it "References one listing" $ - testRefs' "Lst:" [1] [4] lstRefs "Lst.\160\&4" + testRefs' "Lst:" [1] [4] referenceData "Lst.\160\&4" it "References multiple listings" $ - testRefs' "Lst:" [1..3] [4..6] lstRefs "Lsts.\160\&4-6" + testRefs' "Lst:" [1..3] [4..6] referenceData "Lsts.\160\&4-6" it "References one listing" $ - testRefs' "Sec:" [1] [4] secRefs "Sec.\160\&4" + testRefs' "Sec:" [1] [4] referenceData "Sec.\160\&4" it "References multiple listings" $ - testRefs' "Sec:" [1..3] [4..6] secRefs "Secs.\160\&4-6" + testRefs' "Sec:" [1..3] [4..6] referenceData "Secs.\160\&4-6" describe "References.List.listOf" $ do it "Generates list of tables" $ testList (rawBlock "latex" "\\listoftables") - (tblRefs =: M.fromList $ refRec' "tbl:1" 4 "4" <> refRec' "tbl:2" 5 "5" <> refRec' "tbl:3" 6 "6") + (referenceData =: M.fromList $ refRec' "tbl:1" 4 "4" <> refRec' "tbl:2" 5 "5" <> refRec' "tbl:3" 6 "6") (header 1 (text "List of Tables") <> orderedList ((plain . str . show) `map` [4..6 :: Int])) it "Generates list of figures" $ testList (rawBlock "latex" "\\listoffigures") - (imgRefs =: M.fromList $ refRec' "fig:1" 4 "4" <> refRec' "fig:2" 5 "5" <> refRec' "fig:3" 6 "6") + (referenceData =: M.fromList $ refRec' "fig:1" 4 "4" <> refRec' "fig:2" 5 "5" <> refRec' "fig:3" 6 "6") (header 1 (text "List of Figures") <> orderedList ((plain . str . show) `map` [4..6 :: Int])) describe "Util.CodeBlockCaptions" $ @@ -252,9 +252,9 @@ main = hspec $ do describe "Util.Template" $ it "Applies templates" $ - let template=Util.Template.makeTemplate defaultMeta (toList $ displayMath "figureTitle" <> displayMath "i" <> displayMath "t") - in Util.Template.applyTemplate [Str "1"] [Str "title"] template `shouldBe` - toList (str "Figure" <> str "1" <> str "title") + let template=Util.Template.makeTemplate defaultMeta (displayMath "figureTitle" <> displayMath "i" <> displayMath "t") + in Util.Template.applyTemplate (text "1") (text "title") template `shouldBe` + (str "Figure" <> str "1" <> str "title") describe "Citation groups shouldn't be separated (#22 regression test)" $ do it "Should not separate citation groups" $ do @@ -336,13 +336,13 @@ refGen' :: String -> [Int] -> [(Int, Int)] -> M.Map String RefRec refGen' p l1 l2 = M.fromList $ mconcat $ zipWith refRec''' (((uncapitalizeFirst p++) . show) `map` l1) l2 refRec' :: String -> Int -> String -> [(String, RefRec)] -refRec' ref i tit = [(ref, RefRec{refIndex=[(i,Nothing)],refTitle=toList $ text tit,refSubfigure=Nothing})] +refRec' ref i tit = [(ref, RefRec{refIndex=[(i,show i)],refTitle=text tit,refSubfigure=Nothing})] refRec'' :: String -> Int -> [(String, RefRec)] refRec'' ref i = refRec' ref i [] refRec''' :: String -> (Int, Int) -> [(String, RefRec)] -refRec''' ref (c,i) = [(ref, RefRec{refIndex=[(c,Nothing), (i,Nothing)],refTitle=toList $ text [],refSubfigure=Nothing})] +refRec''' ref (c,i) = [(ref, RefRec{refIndex=[(c,show c), (i,show i)],refTitle=text [],refSubfigure=Nothing})] testRefs' :: String -> [Int] -> [Int] -> Accessor References (M.Map String RefRec) -> String -> Expectation testRefs' p l1 l2 prop res = testRefs (para $ citeGen p l1) (setVal prop (refGen p l1 l2) def) (para $ text res) From e827a314a0446f22f889966f1443bb73893aa7cb Mon Sep 17 00:00:00 2001 From: Nikolay Yakimov Date: Tue, 3 Apr 2018 05:20:41 +0300 Subject: [PATCH 009/134] Only ouput sub-object as LaTeX subfigures if objects are figures --- lib/Text/Pandoc/CrossRef/References/Blocks.hs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/Text/Pandoc/CrossRef/References/Blocks.hs b/lib/Text/Pandoc/CrossRef/References/Blocks.hs index f24a39ed..2c61a180 100644 --- a/lib/Text/Pandoc/CrossRef/References/Blocks.hs +++ b/lib/Text/Pandoc/CrossRef/References/Blocks.hs @@ -126,7 +126,7 @@ replaceBlock opts (Div (label,cls,attrs) images) (M.map (\v -> v{refIndex = refIndex lastRef, refSubfigure = Just $ refIndex v}) $ referenceData_ st) case outFormat opts of - f | isLatexFormat f -> + f | isLatexFormat f, pfx == "fig" -> replaceNoRecurse $ Div nullAttr $ [ RawBlock (Format "latex") "\\begin{figure}\n\\centering" ] ++ cont ++ From 566e32881a2aeb10510ae30476a02935b7f8cc58 Mon Sep 17 00:00:00 2001 From: Nikolay Yakimov Date: Tue, 3 Apr 2018 05:31:59 +0300 Subject: [PATCH 010/134] Fix test --- test/test-pandoc-crossref.hs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/test/test-pandoc-crossref.hs b/test/test-pandoc-crossref.hs index 03f8370c..933f2a46 100644 --- a/test/test-pandoc-crossref.hs +++ b/test/test-pandoc-crossref.hs @@ -252,7 +252,9 @@ main = hspec $ do describe "Util.Template" $ it "Applies templates" $ - let template=Util.Template.makeTemplate defaultMeta (displayMath "figureTitle" <> displayMath "i" <> displayMath "t") + let template=Util.Template.makeTemplate + (defaultMeta <> Meta (M.singleton "figureTitle" (toMetaValue $ text "Figure"))) + (displayMath "figureTitle" <> displayMath "i" <> displayMath "t") in Util.Template.applyTemplate (text "1") (text "title") template `shouldBe` (str "Figure" <> str "1" <> str "title") From 26fa89632e9627034c90caa40e935082064e4fca Mon Sep 17 00:00:00 2001 From: Nikolay Yakimov Date: Tue, 3 Apr 2018 05:32:17 +0300 Subject: [PATCH 011/134] Fix capitalized label lookup --- lib/Text/Pandoc/CrossRef/References/Refs.hs | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/lib/Text/Pandoc/CrossRef/References/Refs.hs b/lib/Text/Pandoc/CrossRef/References/Refs.hs index 5e5cd329..ba010566 100644 --- a/lib/Text/Pandoc/CrossRef/References/Refs.hs +++ b/lib/Text/Pandoc/CrossRef/References/Refs.hs @@ -37,6 +37,7 @@ import Text.Pandoc.CrossRef.Util.Util import Text.Pandoc.CrossRef.Util.Options import Text.Pandoc.CrossRef.Util.Prefixes import Control.Applicative +import Data.Char (toLower) import Debug.Trace import Prelude @@ -110,7 +111,7 @@ replaceRefsLatex' prefix opts cits = | otherwise = "\\cref" listLabels :: String -> String -> String -> String -> [Citation] -> String -listLabels prefix p sep s = +listLabels _prefix p sep s = intercalate sep . map ((p ++) . (++ s) . mkLaTeXLabel' . citationId) getLabelPrefix :: Options -> String -> Maybe String @@ -155,7 +156,7 @@ instance Ord RefData where getRefIndex :: String -> Options -> Citation -> WS RefData getRefIndex _prefix _opts Citation{citationId=cid,citationSuffix=suf} = do - ref <- M.lookup lab <$> get referenceData + ref <- M.lookup llab <$> get referenceData let sub = refSubfigure <$> ref idx = refIndex <$> ref return RefData @@ -165,7 +166,9 @@ getRefIndex _prefix _opts Citation{citationId=cid,citationSuffix=suf} , rdSuffix = fromList suf } where - lab = cid + (pfx, lab) = span (/=':') cid + lpfx = map toLower pfx + llab = lpfx <> lab data RefItem = RefRange RefData RefData | RefSingle RefData From f870adafcde77a65016cd0e5b0dd605619551dde Mon Sep 17 00:00:00 2001 From: Nikolay Yakimov Date: Tue, 3 Apr 2018 05:47:00 +0300 Subject: [PATCH 012/134] Re-add list-of --- lib/Text/Pandoc/CrossRef/References/List.hs | 21 ++++++++++++++++----- 1 file changed, 16 insertions(+), 5 deletions(-) diff --git a/lib/Text/Pandoc/CrossRef/References/List.hs b/lib/Text/Pandoc/CrossRef/References/List.hs index fc2ce562..fe811eb3 100644 --- a/lib/Text/Pandoc/CrossRef/References/List.hs +++ b/lib/Text/Pandoc/CrossRef/References/List.hs @@ -30,21 +30,32 @@ import qualified Data.Map as M import Text.Pandoc.CrossRef.References.Types import Text.Pandoc.CrossRef.Util.Util import Text.Pandoc.CrossRef.Util.Options +import Text.Pandoc.CrossRef.Util.Prefixes listOf :: Options -> [Block] -> WS [Block] +listOf opts (RawBlock (Format "latex") cmd:xs) + | Just pfxBrace <- "\\listof{" `stripPrefix` cmd + , (pfx, "}") <- span (/='}') pfxBrace + = getPfxData pfx >>= fmap toList . makeList opts pfx (fromList xs) listOf Options{outFormat=f} x | isLatexFormat f = return x listOf opts (RawBlock (Format "latex") "\\listoffigures":xs) - = undefined -- get imgRefs >>= makeList opts lofTitle xs + = getPfxData "fig" >>= fmap toList . makeList opts "fig" (fromList xs) listOf opts (RawBlock (Format "latex") "\\listoftables":xs) - = undefined -- get tblRefs >>= makeList opts lotTitle xs + = getPfxData "tbl" >>= fmap toList . makeList opts "tbl" (fromList xs) listOf opts (RawBlock (Format "latex") "\\listoflistings":xs) - = undefined -- get lstRefs >>= makeList opts lolTitle xs + = getPfxData "lst" >>= fmap toList . makeList opts "lst" (fromList xs) listOf _ x = return x -makeList :: Options -> (Options -> Blocks) -> Blocks -> M.Map String RefRec -> WS Blocks +getPfxData :: String -> WS RefMap +getPfxData pfx = M.filterWithKey (\k _ -> (pfx <> ":") `isPrefixOf` k) <$> get referenceData + +getLot :: Options -> String -> Blocks +getLot opts = prefixListOfTitle . getPfx opts + +makeList :: Options -> String -> Blocks -> M.Map String RefRec -> WS Blocks makeList opts titlef xs refs = return $ - titlef opts <> + getLot opts titlef <> (if chaptersDepth opts > 0 then divWith ("", ["list"], []) (mconcat $ map itemChap refsSorted) else orderedList (map item refsSorted)) From 1a06945751de3a8bee2ea43f3f3fc37794731356 Mon Sep 17 00:00:00 2001 From: Nikolay Yakimov Date: Tue, 3 Apr 2018 06:37:19 +0300 Subject: [PATCH 013/134] Variable scope priority in prefix reader --- lib/Text/Pandoc/CrossRef/Util/Prefixes.hs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/Text/Pandoc/CrossRef/Util/Prefixes.hs b/lib/Text/Pandoc/CrossRef/Util/Prefixes.hs index 9c802430..0dea395d 100644 --- a/lib/Text/Pandoc/CrossRef/Util/Prefixes.hs +++ b/lib/Text/Pandoc/CrossRef/Util/Prefixes.hs @@ -53,7 +53,7 @@ getPrefixes varN dtv , prefixNumbering = mkLabel (varN <> "." <> "numbering") (fromMaybe (MetaString "arabic") $ lookupMeta "numbering" kv) , prefixListOfTitle = getMetaBlock "listOfTitle" kv } - where kv = dtv <> Meta kv' + where kv = Meta kv' <> dtv m2p k _ = error $ "Invalid value for prefix " <> k type Prefixes = M.Map String Prefix From 6d0c9ab01bcd7b46167f3930e3680a47fce97551 Mon Sep 17 00:00:00 2001 From: Nikolay Yakimov Date: Tue, 3 Apr 2018 06:48:59 +0300 Subject: [PATCH 014/134] Fix reference counting --- lib/Text/Pandoc/CrossRef/References/Blocks.hs | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/lib/Text/Pandoc/CrossRef/References/Blocks.hs b/lib/Text/Pandoc/CrossRef/References/Blocks.hs index 2c61a180..2de5aa1b 100644 --- a/lib/Text/Pandoc/CrossRef/References/Blocks.hs +++ b/lib/Text/Pandoc/CrossRef/References/Blocks.hs @@ -344,7 +344,12 @@ replaceAttr :: Options -> Either String String -> Maybe String -> Inlines -> Str replaceAttr o label refLabel title pfx = do chap <- take (chaptersDepth o) `fmap` get curChap - i <- (1+) `fmap` (M.size . M.filter (\x -> (chap == init (refIndex x)) && isNothing (refSubfigure x)) <$> get referenceData) + i <- (1+) `fmap` ( + M.size . M.filterWithKey ( + \k x -> ((pfx <> ":") `isPrefixOf` k) && (chap == init (refIndex x)) && isNothing (refSubfigure x) + ) + <$> get referenceData + ) let customLabel = prefixNumbering $ fromJust $ M.lookup pfx (prefixes o) let index = chap ++ [(i, fromMaybe (customLabel i) refLabel)] label' = either (++ ':':show index) id label From 2963cad265381efda029dd781ca5966272e91826 Mon Sep 17 00:00:00 2001 From: Nikolay Yakimov Date: Tue, 3 Apr 2018 07:33:31 +0300 Subject: [PATCH 015/134] Fix label names --- lib/Text/Pandoc/CrossRef/References/Refs.hs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/Text/Pandoc/CrossRef/References/Refs.hs b/lib/Text/Pandoc/CrossRef/References/Refs.hs index ba010566..a3e89985 100644 --- a/lib/Text/Pandoc/CrossRef/References/Refs.hs +++ b/lib/Text/Pandoc/CrossRef/References/Refs.hs @@ -160,7 +160,7 @@ getRefIndex _prefix _opts Citation{citationId=cid,citationSuffix=suf} let sub = refSubfigure <$> ref idx = refIndex <$> ref return RefData - { rdLabel = lab + { rdLabel = llab , rdIdx = idx , rdSubfig = join sub , rdSuffix = fromList suf From 74da5798f3888e9950b4af7940a5adcf564f8dd8 Mon Sep 17 00:00:00 2001 From: Nikolay Yakimov Date: Tue, 3 Apr 2018 07:33:48 +0300 Subject: [PATCH 016/134] Remove debug traces --- lib/Text/Pandoc/CrossRef/References/Refs.hs | 9 +++------ 1 file changed, 3 insertions(+), 6 deletions(-) diff --git a/lib/Text/Pandoc/CrossRef/References/Refs.hs b/lib/Text/Pandoc/CrossRef/References/Refs.hs index a3e89985..7233066b 100644 --- a/lib/Text/Pandoc/CrossRef/References/Refs.hs +++ b/lib/Text/Pandoc/CrossRef/References/Refs.hs @@ -65,11 +65,8 @@ replaceRefs opts ils _ -> replaceRefsOther replaceRefs _ x = return x -traceClone :: Show a => a -> a -traceClone x = trace (show x) x - getRefPrefix :: Options -> String -> Bool -> Int -> Inlines -> Inlines -getRefPrefix opts prefix capitalize num cit = traceClone $ +getRefPrefix opts prefix capitalize num cit = applyTemplate' (M.fromDistinctAscList [("i", cit), ("p", refprefix)]) reftempl where Prefix{prefixRef=refprefixf, prefixReferenceTemplate=reftempl} = fromMaybe undefined $ M.lookup prefix $ prefixes opts refprefix = refprefixf capitalize num @@ -142,7 +139,7 @@ replaceRefsOther' prefix opts cits = do | nameInLink opts , [Link attr t (y, z)] <- toList x = linkWith attr y z (f $ fromList t) cmap f x = f x - return $ writePrefix (traceClone $ makeIndices opts indices) + return $ writePrefix (makeIndices opts indices) data RefData = RefData { rdLabel :: String , rdIdx :: Maybe Index @@ -173,7 +170,7 @@ getRefIndex _prefix _opts Citation{citationId=cid,citationSuffix=suf} data RefItem = RefRange RefData RefData | RefSingle RefData makeIndices :: Options -> [RefData] -> Inlines -makeIndices o s = format $ concatMap f $ HT.groupBy g $ traceClone $ sort $ nub s +makeIndices o s = format $ concatMap f $ HT.groupBy g $ sort $ nub s where g :: RefData -> RefData -> Bool g a b = all (null . rdSuffix) [a, b] && ( From fa6b28b34468e6f677edf52e6db95995f58a45b3 Mon Sep 17 00:00:00 2001 From: Nikolay Yakimov Date: Tue, 3 Apr 2018 07:36:11 +0300 Subject: [PATCH 017/134] Custom settings type and Semigroup instance --- lib/Text/Pandoc/CrossRef.hs | 4 ++-- lib/Text/Pandoc/CrossRef/Util/Meta.hs | 19 +++++++-------- lib/Text/Pandoc/CrossRef/Util/ModifyMeta.hs | 9 ++++---- lib/Text/Pandoc/CrossRef/Util/Prefixes.hs | 16 +++++++------ lib/Text/Pandoc/CrossRef/Util/Settings.hs | 23 +++++++++++-------- lib/Text/Pandoc/CrossRef/Util/Settings/Gen.hs | 3 ++- .../Pandoc/CrossRef/Util/Settings/Types.hs | 22 ++++++++++++++++++ lib/Text/Pandoc/CrossRef/Util/Template.hs | 7 +++--- pandoc-crossref.cabal | 4 +++- test/test-pandoc-crossref.hs | 3 ++- 10 files changed, 72 insertions(+), 38 deletions(-) create mode 100644 lib/Text/Pandoc/CrossRef/Util/Settings/Types.hs diff --git a/lib/Text/Pandoc/CrossRef.hs b/lib/Text/Pandoc/CrossRef.hs index 31045756..c2b75428 100644 --- a/lib/Text/Pandoc/CrossRef.hs +++ b/lib/Text/Pandoc/CrossRef.hs @@ -94,7 +94,7 @@ import Text.Pandoc.CrossRef.Util.Settings.Gen as SG -- | Enviromnent for 'CrossRefM' data CrossRefEnv = CrossRefEnv { - creSettings :: Meta -- ^Metadata settings + creSettings :: Settings -- ^Metadata settings , creOptions :: Options -- ^Internal pandoc-crossref options } @@ -142,7 +142,7 @@ This is primary function to work with 'CrossRefM' -} runCrossRef :: forall a b. Meta -> Maybe Format -> (a -> CrossRefM b) -> a -> b runCrossRef meta fmt action arg = R.runReader (action arg) env where - settings = meta <> defaultMeta + settings = Settings meta <> defaultMeta env = CrossRefEnv { creSettings = settings , creOptions = getOptions settings fmt diff --git a/lib/Text/Pandoc/CrossRef/Util/Meta.hs b/lib/Text/Pandoc/CrossRef/Util/Meta.hs index e752a91a..ae53dc3a 100644 --- a/lib/Text/Pandoc/CrossRef/Util/Meta.hs +++ b/lib/Text/Pandoc/CrossRef/Util/Meta.hs @@ -33,6 +33,7 @@ module Text.Pandoc.CrossRef.Util.Meta ( ) where import Text.Pandoc.CrossRef.Util.Util +import Text.Pandoc.CrossRef.Util.Settings.Types import Text.Pandoc.Definition import Text.Pandoc.Builder import Data.Default @@ -40,26 +41,26 @@ import Text.Pandoc.Walk import Text.Pandoc.Shared hiding (capitalize) import Data.Maybe -getMetaList :: (Default a) => (MetaValue -> a) -> String -> Meta -> Int -> a -getMetaList f name meta i = maybe def f $ lookupMeta name meta >>= getList i +getMetaList :: (Default a) => (MetaValue -> a) -> String -> Settings -> Int -> a +getMetaList f name (Settings meta) i = maybe def f $ lookupMeta name meta >>= getList i -getMetaBool :: String -> Meta -> Bool +getMetaBool :: String -> Settings -> Bool getMetaBool = getScalar toBool -getMetaInlines :: String -> Meta -> Inlines +getMetaInlines :: String -> Settings -> Inlines getMetaInlines = getScalar toInlines -getMetaBlock :: String -> Meta -> Blocks +getMetaBlock :: String -> Settings -> Blocks getMetaBlock = getScalar toBlocks -getMetaString :: String -> Meta -> String +getMetaString :: String -> Settings -> String getMetaString = getScalar toString -getMetaStringMaybe :: String -> Meta -> Maybe String +getMetaStringMaybe :: String -> Settings -> Maybe String getMetaStringMaybe = getScalar toMaybeString -getScalar :: Def b => (String -> MetaValue -> b) -> String -> Meta -> b -getScalar conv name meta = maybe def' (conv name) $ lookupMeta name meta +getScalar :: Def b => (String -> MetaValue -> b) -> String -> Settings -> b +getScalar conv name (Settings meta) = maybe def' (conv name) $ lookupMeta name meta class Def a where def' :: a diff --git a/lib/Text/Pandoc/CrossRef/Util/ModifyMeta.hs b/lib/Text/Pandoc/CrossRef/Util/ModifyMeta.hs index a17f4d6a..4feaba0a 100644 --- a/lib/Text/Pandoc/CrossRef/Util/ModifyMeta.hs +++ b/lib/Text/Pandoc/CrossRef/Util/ModifyMeta.hs @@ -27,18 +27,19 @@ import Data.List (intercalate) import Text.Pandoc import Text.Pandoc.Builder hiding ((<>)) import Text.Pandoc.CrossRef.Util.Options +import Text.Pandoc.CrossRef.Util.Settings.Types import Text.Pandoc.CrossRef.Util.Meta import Text.Pandoc.CrossRef.Util.Util import qualified Data.Text as T import Control.Monad.Writer -modifyMeta :: Options -> Meta -> Meta +modifyMeta :: Options -> Settings -> Meta modifyMeta opts meta | isLatexFormat (outFormat opts) = setMeta "header-includes" - (headerInc $ lookupMeta "header-includes" meta) - meta - | otherwise = meta + (headerInc $ lookupSettings "header-includes" meta) + $ unSettings meta + | otherwise = unSettings meta where headerInc :: Maybe MetaValue -> MetaValue headerInc Nothing = incList diff --git a/lib/Text/Pandoc/CrossRef/Util/Prefixes.hs b/lib/Text/Pandoc/CrossRef/Util/Prefixes.hs index 0dea395d..87d10e00 100644 --- a/lib/Text/Pandoc/CrossRef/Util/Prefixes.hs +++ b/lib/Text/Pandoc/CrossRef/Util/Prefixes.hs @@ -23,37 +23,39 @@ module Text.Pandoc.CrossRef.Util.Prefixes where import Text.Pandoc.Definition import Text.Pandoc.CrossRef.Util.Template +import Text.Pandoc.CrossRef.Util.Settings.Types import Text.Pandoc.CrossRef.Util.Meta import Text.Pandoc.CrossRef.Util.CustomLabels import qualified Data.Map as M -import Text.Pandoc.Builder +import Text.Pandoc.Builder hiding ((<>)) import Data.Default +import Data.Monoid import Data.Maybe instance Default Inlines where def = mempty -getPrefixes :: String -> Meta -> Prefixes +getPrefixes :: String -> Settings -> Prefixes getPrefixes varN dtv - | Just (MetaMap m) <- lookupMeta varN dtv = M.mapWithKey m2p m + | Just (MetaMap m) <- lookupSettings varN dtv = M.mapWithKey m2p m | otherwise = error "Prefixes not defined" where var = displayMath m2p _ (MetaMap kv') = Prefix { prefixRef = tryCapitalizeM (flip (getMetaList (toInlines "ref")) kv) "ref" , prefixCaptionTemplate = makeTemplate kv $ - if isJust $ lookupMeta "captionTemplate" kv + if isJust $ lookupSettings "captionTemplate" kv then getMetaInlines "captionTemplate" kv else var "title" <> space <> var "i" <> var "titleDelim" <> space <> var "t" <> var "ccs#. " , prefixReferenceTemplate = makeTemplate kv $ - if isJust $ lookupMeta "referenceTemplate" kv + if isJust $ lookupSettings "referenceTemplate" kv then getMetaInlines "referenceTemplate" kv else var "p" <> str "\160" <> var "i" , prefixScope = getMetaStringMaybe "scope" kv - , prefixNumbering = mkLabel (varN <> "." <> "numbering") (fromMaybe (MetaString "arabic") $ lookupMeta "numbering" kv) + , prefixNumbering = mkLabel (varN <> "." <> "numbering") (fromMaybe (MetaString "arabic") $ lookupSettings "numbering" kv) , prefixListOfTitle = getMetaBlock "listOfTitle" kv } - where kv = Meta kv' <> dtv + where kv = Settings (Meta kv') <> dtv m2p k _ = error $ "Invalid value for prefix " <> k type Prefixes = M.Map String Prefix diff --git a/lib/Text/Pandoc/CrossRef/Util/Settings.hs b/lib/Text/Pandoc/CrossRef/Util/Settings.hs index 71efefcc..fc893ce3 100644 --- a/lib/Text/Pandoc/CrossRef/Util/Settings.hs +++ b/lib/Text/Pandoc/CrossRef/Util/Settings.hs @@ -19,27 +19,30 @@ with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -} -module Text.Pandoc.CrossRef.Util.Settings (getSettings, defaultMeta) where +module Text.Pandoc.CrossRef.Util.Settings (getSettings, defaultMeta, Settings(..)) where import Text.Pandoc -import Text.Pandoc.Builder +import Text.Pandoc.Builder hiding ((<>)) import Control.Exception (handle,IOException) import Text.Pandoc.CrossRef.Util.Settings.Gen +import Text.Pandoc.CrossRef.Util.Settings.Types import Text.Pandoc.CrossRef.Util.Meta import Text.Pandoc.CrossRef.Util.PandocOrphans() import System.Directory import System.FilePath import System.IO +import Data.Monoid import qualified Data.Text as T import qualified Data.Map as M -getSettings :: Maybe Format -> Meta -> IO Meta -getSettings fmt meta = do +getSettings :: Maybe Format -> Meta -> IO Settings +getSettings fmt inMeta = do + let meta = Settings inMeta dirConfig <- readConfig (getMetaString "crossrefYaml" (meta <> defaultMeta)) home <- getHomeDirectory globalConfig <- readConfig (home ".pandoc-crossref" "config.yaml") - formatConfig <- maybe (return nullMeta) (readFmtConfig home) fmt + formatConfig <- maybe (return mempty) (readFmtConfig home) fmt return $ meta <> dirConfig <> formatConfig <> globalConfig <> defaultMeta where readConfig path = @@ -48,16 +51,16 @@ getSettings fmt meta = do hSetEncoding h utf8 yaml <- hGetContents h Pandoc meta' _ <- readMd $ T.pack $ unlines ["---", yaml, "---"] - return meta' + return $ Settings meta' readMd = handleError . runPure . readMarkdown def{readerExtensions=pandocExtensions} readFmtConfig home fmt' = readConfig (home ".pandoc-crossref" "config-" ++ fmtStr fmt' ++ ".yaml") - handler :: IOException -> IO Meta - handler _ = return nullMeta + handler :: IOException -> IO Settings + handler _ = return mempty fmtStr (Format fmtstr) = fmtstr -defaultMeta :: Meta -defaultMeta = +defaultMeta :: Settings +defaultMeta = Settings $ cref False <> chapters False <> chaptersDepth "1" diff --git a/lib/Text/Pandoc/CrossRef/Util/Settings/Gen.hs b/lib/Text/Pandoc/CrossRef/Util/Settings/Gen.hs index a87e9afc..ddfc2dd8 100644 --- a/lib/Text/Pandoc/CrossRef/Util/Settings/Gen.hs +++ b/lib/Text/Pandoc/CrossRef/Util/Settings/Gen.hs @@ -23,6 +23,7 @@ with this program; if not, write to the Free Software Foundation, Inc., module Text.Pandoc.CrossRef.Util.Settings.Gen where import Text.Pandoc.CrossRef.Util.Settings.Template +import Text.Pandoc.CrossRef.Util.Settings.Types import Text.Pandoc.CrossRef.Util.Meta import Text.Pandoc.CrossRef.Util.Options as O (Options(..)) import Language.Haskell.TH (mkName) @@ -46,7 +47,7 @@ fmap concat $ mapM (makeAcc . mkName) , "secHeaderDelim" ] -getOptions :: Meta -> Maybe Format -> Options +getOptions :: Settings -> Maybe Format -> Options getOptions dtv fmt = let opts = $(makeCon ''Options 'Options) in if getMetaBool "chapters" dtv diff --git a/lib/Text/Pandoc/CrossRef/Util/Settings/Types.hs b/lib/Text/Pandoc/CrossRef/Util/Settings/Types.hs new file mode 100644 index 00000000..b014e856 --- /dev/null +++ b/lib/Text/Pandoc/CrossRef/Util/Settings/Types.hs @@ -0,0 +1,22 @@ +module Text.Pandoc.CrossRef.Util.Settings.Types where + +import Text.Pandoc.Definition +import Data.Semigroup +import qualified Data.Map as M + +newtype Settings = Settings { unSettings :: Meta } deriving (Eq, Ord, Show) +newtype MetaSetting = MetaSetting MetaValue deriving (Eq, Ord, Show) + +lookupSettings :: String -> Settings -> Maybe MetaValue +lookupSettings k (Settings s) = lookupMeta k s + +instance Semigroup Settings where + (Settings (Meta a)) <> (Settings (Meta b)) = Settings $ Meta $ M.unionWith merge a b + +instance Monoid Settings where + mappend = (<>) + mempty = Settings nullMeta + +merge :: MetaValue -> MetaValue -> MetaValue +merge (MetaMap m1) (MetaMap m2) = MetaMap $ M.unionWith merge m1 m2 +merge x _ = x diff --git a/lib/Text/Pandoc/CrossRef/Util/Template.hs b/lib/Text/Pandoc/CrossRef/Util/Template.hs index 78fb7183..bfd37281 100644 --- a/lib/Text/Pandoc/CrossRef/Util/Template.hs +++ b/lib/Text/Pandoc/CrossRef/Util/Template.hs @@ -30,14 +30,15 @@ import Text.Pandoc.Builder import Text.Pandoc.Generic import qualified Data.Map as M hiding (toList, fromList, singleton) import Text.Pandoc.CrossRef.Util.Meta +import Text.Pandoc.CrossRef.Util.Settings.Types import Control.Applicative import Text.Read type VarFunc = String -> Maybe MetaValue newtype Template = Template (VarFunc -> Inlines) -makeTemplate :: Meta -> Inlines -> Template -makeTemplate dtv xs' = Template $ \vf -> fromList $ scan (\var -> vf var <|> lookupMeta var dtv) $ toList xs' +makeTemplate :: Settings -> Inlines -> Template +makeTemplate dtv xs' = Template $ \vf -> fromList $ scan (\var -> vf var <|> lookupSettings var dtv) $ toList xs' where scan :: (String -> Maybe MetaValue) -> [Inline] -> [Inline] scan = bottomUp . go @@ -48,7 +49,7 @@ makeTemplate dtv xs' = Template $ \vf -> fromList $ scan (\var -> vf var <|> loo idx = readMaybe . toString ("index variable " ++ idxVar) =<< (vf idxVar) arr = do i <- idx - v <- lookupMeta vn dtv + v <- lookupSettings vn dtv getList i v in toList $ (replaceVar arr id) <> fromList xs | '#' `elem` var = diff --git a/pandoc-crossref.cabal b/pandoc-crossref.cabal index 8b7ae5c0..41e6a95b 100644 --- a/pandoc-crossref.cabal +++ b/pandoc-crossref.cabal @@ -2,7 +2,7 @@ -- -- see: https://github.com/sol/hpack -- --- hash: 50bfd180f124ef47795787dc70ba832d1ac839add25dda9a3df3af90cc6c59f6 +-- hash: 7363be4fc2eccadb7479eece11df48cf220e2ec120304d1852966e9f0c1e3a06 name: pandoc-crossref version: 0.3.1.0 @@ -106,6 +106,7 @@ library Text.Pandoc.CrossRef.Util.Settings Text.Pandoc.CrossRef.Util.Settings.Gen Text.Pandoc.CrossRef.Util.Settings.Template + Text.Pandoc.CrossRef.Util.Settings.Types Text.Pandoc.CrossRef.Util.Template Text.Pandoc.CrossRef.Util.Util Paths_pandoc_crossref @@ -213,6 +214,7 @@ test-suite test-pandoc-crossref Text.Pandoc.CrossRef.Util.Settings Text.Pandoc.CrossRef.Util.Settings.Gen Text.Pandoc.CrossRef.Util.Settings.Template + Text.Pandoc.CrossRef.Util.Settings.Types Text.Pandoc.CrossRef.Util.Template Text.Pandoc.CrossRef.Util.Util Paths_pandoc_crossref diff --git a/test/test-pandoc-crossref.hs b/test/test-pandoc-crossref.hs index 933f2a46..0ab24cfc 100644 --- a/test/test-pandoc-crossref.hs +++ b/test/test-pandoc-crossref.hs @@ -33,6 +33,7 @@ import Text.Pandoc.CrossRef import Text.Pandoc.CrossRef.Util.Options import Text.Pandoc.CrossRef.Util.Util import Text.Pandoc.CrossRef.References.Types +import Text.Pandoc.CrossRef.Util.Settings.Types import Data.Accessor hiding ((=:)) import qualified Text.Pandoc.CrossRef.References.Blocks as References.Blocks import qualified Text.Pandoc.CrossRef.References.Refs as References.Refs @@ -253,7 +254,7 @@ main = hspec $ do describe "Util.Template" $ it "Applies templates" $ let template=Util.Template.makeTemplate - (defaultMeta <> Meta (M.singleton "figureTitle" (toMetaValue $ text "Figure"))) + (defaultMeta <> Settings (Meta (M.singleton "figureTitle" (toMetaValue $ text "Figure")))) (displayMath "figureTitle" <> displayMath "i" <> displayMath "t") in Util.Template.applyTemplate (text "1") (text "title") template `shouldBe` (str "Figure" <> str "1" <> str "title") From 151551c90460a9f279da50cc6d7bdd7c37cc0638 Mon Sep 17 00:00:00 2001 From: Nikolay Yakimov Date: Tue, 3 Apr 2018 07:36:29 +0300 Subject: [PATCH 018/134] Update demo.md --- docs/demo/demo.md | 19 +++++++++++-------- 1 file changed, 11 insertions(+), 8 deletions(-) diff --git a/docs/demo/demo.md b/docs/demo/demo.md index e2344cde..c8d0660e 100644 --- a/docs/demo/demo.md +++ b/docs/demo/demo.md @@ -1,13 +1,16 @@ --- codeBlockCaptions: True -figureTitle: | - Figure # -lofTitle: | - ## List of Figures -lotTitle: | - ## List of Tables -tableTemplate: | - *$$tableTitle$$ $$i$$*$$titleDelim$$ $$t$$ +prefixes: + fig: + title: | + Figure # + listOfTitle: | + ## List of Figures + tbl: + listOfTitle: | + ## List of Tables + captionTemplate: | + *$$title$$ $$i$$*$$titleDelim$$ $$t$$ autoSectionLabels: True title: pandoc-crossref demo document --- From fe8ce6dce8cb6ef91226338b0eab7c683cbe8727 Mon Sep 17 00:00:00 2001 From: Nikolay Yakimov Date: Tue, 3 Apr 2018 07:41:08 +0300 Subject: [PATCH 019/134] Bump stack resolver --- stack.yaml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/stack.yaml b/stack.yaml index e12d4ea0..92e704c4 100644 --- a/stack.yaml +++ b/stack.yaml @@ -1,6 +1,6 @@ packages: - . +allow-newer: true extra-deps: - roman-numerals-0.5.1.5 -resolver: lts-11.1 -allow-newer: true +resolver: lts-11.3 From cc54e81c1a22592464d7af813d343a9440e0bd32 Mon Sep 17 00:00:00 2001 From: Nikolay Yakimov Date: Tue, 3 Apr 2018 08:08:37 +0300 Subject: [PATCH 020/134] Dedicated counter for references --- lib/Text/Pandoc/CrossRef/References/Blocks.hs | 13 +++++-------- lib/Text/Pandoc/CrossRef/References/Types.hs | 3 ++- 2 files changed, 7 insertions(+), 9 deletions(-) diff --git a/lib/Text/Pandoc/CrossRef/References/Blocks.hs b/lib/Text/Pandoc/CrossRef/References/Blocks.hs index 2de5aa1b..d98a375f 100644 --- a/lib/Text/Pandoc/CrossRef/References/Blocks.hs +++ b/lib/Text/Pandoc/CrossRef/References/Blocks.hs @@ -343,14 +343,11 @@ spanInlines _ x = x replaceAttr :: Options -> Either String String -> Maybe String -> Inlines -> String -> WS Inlines replaceAttr o label refLabel title pfx = do - chap <- take (chaptersDepth o) `fmap` get curChap - i <- (1+) `fmap` ( - M.size . M.filterWithKey ( - \k x -> ((pfx <> ":") `isPrefixOf` k) && (chap == init (refIndex x)) && isNothing (refSubfigure x) - ) - <$> get referenceData - ) - let customLabel = prefixNumbering $ fromJust $ M.lookup pfx (prefixes o) + let ropt = getPfx o pfx + chap <- take (chaptersDepth o) `fmap` get curChap + i <- (1+) . fromMaybe 0 . M.lookup pfx <$> get pfxCounter + modify pfxCounter $ M.insert pfx i + let customLabel = prefixNumbering ropt let index = chap ++ [(i, fromMaybe (customLabel i) refLabel)] label' = either (++ ':':show index) id label hasLabel <- M.member label' <$> get referenceData diff --git a/lib/Text/Pandoc/CrossRef/References/Types.hs b/lib/Text/Pandoc/CrossRef/References/Types.hs index 49e11ede..470df4cb 100644 --- a/lib/Text/Pandoc/CrossRef/References/Types.hs +++ b/lib/Text/Pandoc/CrossRef/References/Types.hs @@ -39,12 +39,13 @@ type RefMap = M.Map String RefRec -- state data type data References = References { referenceData_ :: RefMap , curChap_ :: Index + , pfxCounter_ :: M.Map String Int } deriving (Show, Eq) --state monad type WS a = State References a instance Default References where - def = References M.empty [] + def = References M.empty [] M.empty deriveAccessors ''References From 2957de091f1f1f9cb2678c1abd9ba99b3d709855 Mon Sep 17 00:00:00 2001 From: Nikolay Yakimov Date: Tue, 3 Apr 2018 08:15:07 +0300 Subject: [PATCH 021/134] Reset counters on chapter change when appropriate --- lib/Text/Pandoc/CrossRef/References/Blocks.hs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/lib/Text/Pandoc/CrossRef/References/Blocks.hs b/lib/Text/Pandoc/CrossRef/References/Blocks.hs index d98a375f..8c0a0f5a 100644 --- a/lib/Text/Pandoc/CrossRef/References/Blocks.hs +++ b/lib/Text/Pandoc/CrossRef/References/Blocks.hs @@ -70,6 +70,8 @@ replaceBlock opts (Header n (label, cls, attrs) text') | ln == n = inc cc | otherwise = cc ++ take (n-ln-1) (zip (repeat 1) (repeat "1")) ++ [(1, fromMaybe "1" cl)] in cc' + when (n <= chaptersDepth opts) $ do + modify pfxCounter $ M.singleton "sec" . fromMaybe 0 . M.lookup "sec" when ("sec:" `isPrefixOf` label') $ do index <- get curChap modify referenceData $ M.insert label' RefRec { From 747f80db65a85f6b8ca886043797114dbe36c23f Mon Sep 17 00:00:00 2001 From: Nikolay Yakimov Date: Tue, 3 Apr 2018 09:19:21 +0300 Subject: [PATCH 022/134] Fix tests --- test/test-pandoc-crossref.hs | 60 +++++++++++++++++++++--------------- 1 file changed, 36 insertions(+), 24 deletions(-) diff --git a/test/test-pandoc-crossref.hs b/test/test-pandoc-crossref.hs index 0ab24cfc..33c07af6 100644 --- a/test/test-pandoc-crossref.hs +++ b/test/test-pandoc-crossref.hs @@ -52,7 +52,8 @@ main = hspec $ do it "Labels equations" $ testAll (equation' "a^2+b^2=c^2" "equation") (spanWith ("eq:equation", [], []) (equation' "a^2+b^2=c^2\\qquad(1)" []), - referenceData =: M.fromList $ refRec'' "eq:equation" 1) + (referenceData =: M.fromList $ refRec'' "eq:equation" 1) . + (pfxCounter =: M.singleton "eq" 1)) it "Labels equations in the middle of text" $ testAll ( text "This is an equation: " @@ -62,7 +63,8 @@ main = hspec $ do text "This is an equation: " <> spanWith ("eq:equation", [], []) (equation' "a^2+b^2=c^2\\qquad(1)" []) <> text " it should be labeled", - referenceData =: M.fromList $ refRec'' "eq:equation" 1) + (referenceData =: M.fromList $ refRec'' "eq:equation" 1) . + (pfxCounter =: M.singleton "eq" 1)) it "Labels equations in the beginning of text" $ testAll ( equation' "a^2+b^2=c^2" "equation" @@ -70,7 +72,8 @@ main = hspec $ do ( spanWith ("eq:equation", [], []) (equation' "a^2+b^2=c^2\\qquad(1)" []) <> text " it should be labeled", - referenceData =: M.fromList $ refRec'' "eq:equation" 1) + (referenceData =: M.fromList $ refRec'' "eq:equation" 1) . + (pfxCounter =: M.singleton "eq" 1)) it "Labels equations in the end of text" $ testAll ( text "This is an equation: " @@ -78,7 +81,8 @@ main = hspec $ do ( text "This is an equation: " <> spanWith ("eq:equation", [], []) (equation' "a^2+b^2=c^2\\qquad(1)" []), - referenceData =: M.fromList $ refRec'' "eq:equation" 1) + (referenceData =: M.fromList $ refRec'' "eq:equation" 1) . + (pfxCounter =: M.singleton "eq" 1)) -- TODO: -- describe "References.Blocks.spanInlines" @@ -88,7 +92,8 @@ main = hspec $ do it "Labels images" $ testAll (figure "test.jpg" [] "Test figure" "figure") (figure "test.jpg" [] "Figure 1: Test figure" "figure", - referenceData =: M.fromList $ refRec' "fig:figure" 1 "Test figure") + (referenceData =: M.fromList $ refRec' "fig:figure" 1 "Test figure") . + (pfxCounter =: M.singleton "fig" 1)) it "Labels subfigures" $ testAll ( divWith ("fig:subfigure",[],[]) ( @@ -113,7 +118,7 @@ main = hspec $ do <> para (figure' "fig:" "test22.jpg" [] "b" "figure22") <> para (text "Figure 2: figure caption 2. a — Test figure 21, b — Test figure 22") ) - , referenceData =: M.fromList [("fig:figure1",RefRec { + , (referenceData =: M.fromList [("fig:figure1",RefRec { refIndex = [(1,"1")], refTitle = fromList [Str "Test",Space,Str "figure",Space,Str "1"], refSubfigure = Just [(1, "a")]}), @@ -138,11 +143,12 @@ main = hspec $ do refTitle = fromList [Str "figure",Space,Str "caption",Space,Str "2"], refSubfigure = Nothing}) ] - ) + ) . (pfxCounter =: M.singleton "fig" 2)) it "Labels equations" $ testAll (equation "a^2+b^2=c^2" "equation") (para $ spanWith ("eq:equation", [], []) (equation' "a^2+b^2=c^2\\qquad(1)" []), - referenceData =: M.fromList $ refRec'' "eq:equation" 1) + (referenceData =: M.fromList $ refRec'' "eq:equation" 1) . + (pfxCounter =: M.singleton "eq" 1)) it "Labels equations in the middle of text" $ testAll (para $ text "This is an equation: " @@ -152,7 +158,8 @@ main = hspec $ do text "This is an equation: " <> spanWith ("eq:equation", [], []) (equation' "a^2+b^2=c^2\\qquad(1)" []) <> text " it should be labeled", - referenceData =: M.fromList $ refRec'' "eq:equation" 1) + (referenceData =: M.fromList $ refRec'' "eq:equation" 1) . + (pfxCounter =: M.singleton "eq" 1)) it "Labels equations in the beginning of text" $ testAll (para $ equation' "a^2+b^2=c^2" "equation" @@ -160,7 +167,8 @@ main = hspec $ do (para $ spanWith ("eq:equation", [], []) (equation' "a^2+b^2=c^2\\qquad(1)" []) <> text " it should be labeled", - referenceData =: M.fromList $ refRec'' "eq:equation" 1) + (referenceData =: M.fromList $ refRec'' "eq:equation" 1) . + (pfxCounter =: M.singleton "eq" 1)) it "Labels equations in the end of text" $ testAll (para $ text "This is an equation: " @@ -168,24 +176,28 @@ main = hspec $ do (para $ text "This is an equation: " <> spanWith ("eq:equation", [], []) (equation' "a^2+b^2=c^2\\qquad(1)" []), - referenceData =: M.fromList $ refRec'' "eq:equation" 1) + (referenceData =: M.fromList $ refRec'' "eq:equation" 1) . + (pfxCounter =: M.singleton "eq" 1)) it "Labels tables" $ testAll (table' "Test table" "table") (divWith ("tbl:table", [], []) $ table' "Table 1: Test table" [], - referenceData =: M.fromList $ refRec' "tbl:table" 1 "Test table") + (referenceData =: M.fromList $ refRec' "tbl:table" 1 "Test table") . + (pfxCounter =: M.singleton "tbl" 1)) it "Labels code blocks" $ testAll (codeBlock' "Test code block" "codeblock") (codeBlockDiv "Listing 1: Test code block" "codeblock", - referenceData =: M.fromList $ refRec' "lst:codeblock" 1 "Test code block") + (referenceData =: M.fromList $ refRec' "lst:codeblock" 1 "Test code block") . + (pfxCounter =: M.singleton "lst" 1)) it "Labels code block divs" $ testAll (codeBlockDiv "Test code block" "codeblock") (codeBlockDiv "Listing 1: Test code block" "codeblock", - referenceData =: M.fromList $ refRec' "lst:codeblock" 1 "Test code block") + (referenceData =: M.fromList $ refRec' "lst:codeblock" 1 "Test code block") . + (pfxCounter =: M.singleton "lst" 1)) it "Labels sections divs" $ testAll (section "Section Header" 1 "section") (section "Section Header" 1 "section", - referenceData ^= M.fromList (refRec' "sec:section" 1 "Section Header") - $ curChap =: [(1,"1")]) + (referenceData ^= M.fromList (refRec' "sec:section" 1 "Section Header")) . + (curChap ^= [(1,"1")])) describe "References.Refs.replaceRefs" $ do it "References one image" $ @@ -353,22 +365,22 @@ testRefs' p l1 l2 prop res = testRefs (para $ citeGen p l1) (setVal prop (refGen testRefs'' :: String -> [Int] -> [(Int, Int)] -> Accessor References (M.Map String RefRec) -> String -> Expectation testRefs'' p l1 l2 prop res = testRefs (para $ citeGen p l1) (setVal prop (refGen' p l1 l2) def) (para $ text res) -testAll :: (Eq a, Data a, Show a) => Many a -> (Many a, References) -> Expectation +testAll :: (Eq a, Data a, Show a) => Many a -> (Many a, References -> References) -> Expectation testAll = testState f def where f = References.Blocks.replaceAll defaultOptions testState :: (Eq s, Eq a1, Show s, Show a1, Df.Default s) => - ([a] -> State s [a1]) -> s -> Many a -> (Many a1, s) -> Expectation -testState f init' arg res = runState (f $ toList arg) init' `shouldBe` first toList res + ([a] -> State s [a1]) -> s -> Many a -> (Many a1, s -> s) -> Expectation +testState f init' arg (r, s) = runState (f $ toList arg) init' `shouldBe` (toList r, s init') testRefs :: Blocks -> References -> Blocks -> Expectation -testRefs bs st rbs = testState (bottomUpM (References.Refs.replaceRefs defaultOptions)) st bs (rbs, st) +testRefs bs st rbs = testState (bottomUpM (References.Refs.replaceRefs defaultOptions)) st bs (rbs, id) testCBCaptions :: Blocks -> Blocks -> Expectation testCBCaptions bs res = runState (bottomUpM (Util.CodeBlockCaptions.mkCodeBlockCaptions defaultOptions{Text.Pandoc.CrossRef.Util.Options.codeBlockCaptions=True}) (toList bs)) def `shouldBe` (toList res,def) -testList :: Blocks -> References -> Blocks -> Expectation -testList bs st res = runState (bottomUpM (References.List.listOf defaultOptions) (toList bs)) st `shouldBe` (toList res,st) +testList :: Blocks -> (References -> References) -> Blocks -> Expectation +testList bs st res = runState (bottomUpM (References.List.listOf defaultOptions) (toList bs)) (st def) `shouldBe` (toList res, st def) figure :: String -> String -> String -> String -> Blocks figure = (((para .) .) .) . figure' "fig:" @@ -427,5 +439,5 @@ cit :: String -> [Citation] cit r = [defCit{citationId=r}] infixr 0 =: -(=:) :: Df.Default r => Accessor r a -> a -> r -a =: b = a ^= b $ def +(=:) :: Accessor r a -> a -> r -> r +a =: b = a ^= b From 538e1b12157ec1755dce6f09a1ffb69e0dd42d10 Mon Sep 17 00:00:00 2001 From: Nikolay Yakimov Date: Tue, 3 Apr 2018 09:22:21 +0300 Subject: [PATCH 023/134] Minimal scoping This just resets all counters that have new element prefix in "scope". --- lib/Text/Pandoc/CrossRef/References/Blocks.hs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/lib/Text/Pandoc/CrossRef/References/Blocks.hs b/lib/Text/Pandoc/CrossRef/References/Blocks.hs index 8c0a0f5a..b7cb8246 100644 --- a/lib/Text/Pandoc/CrossRef/References/Blocks.hs +++ b/lib/Text/Pandoc/CrossRef/References/Blocks.hs @@ -348,6 +348,8 @@ replaceAttr o label refLabel title pfx let ropt = getPfx o pfx chap <- take (chaptersDepth o) `fmap` get curChap i <- (1+) . fromMaybe 0 . M.lookup pfx <$> get pfxCounter + let shouldReset = M.keys . M.filter (\p -> pfx `elem` prefixScope p) $ prefixes o + modify pfxCounter $ M.filterWithKey $ \k _ -> k `notElem` shouldReset modify pfxCounter $ M.insert pfx i let customLabel = prefixNumbering ropt let index = chap ++ [(i, fromMaybe (customLabel i) refLabel)] From 8e03e067656179199db2518f69fbbb86ce033fa9 Mon Sep 17 00:00:00 2001 From: Nikolay Yakimov Date: Tue, 3 Apr 2018 13:00:00 +0300 Subject: [PATCH 024/134] Some work towards arbitrary reference-able elements --- lib/Text/Pandoc/CrossRef/References/Blocks.hs | 71 +++++++++++-------- lib/Text/Pandoc/CrossRef/References/Refs.hs | 6 +- lib/Text/Pandoc/CrossRef/References/Types.hs | 14 ++-- test/m2m/custom-prefixes/expect.md | 9 +++ test/m2m/custom-prefixes/expect.tex | 14 ++++ test/m2m/custom-prefixes/input.md | 19 +++++ test/test-pandoc-crossref.hs | 55 ++++++++++---- 7 files changed, 136 insertions(+), 52 deletions(-) create mode 100644 test/m2m/custom-prefixes/expect.md create mode 100644 test/m2m/custom-prefixes/expect.tex create mode 100644 test/m2m/custom-prefixes/input.md diff --git a/lib/Text/Pandoc/CrossRef/References/Blocks.hs b/lib/Text/Pandoc/CrossRef/References/Blocks.hs index b7cb8246..9f7cd58e 100644 --- a/lib/Text/Pandoc/CrossRef/References/Blocks.hs +++ b/lib/Text/Pandoc/CrossRef/References/Blocks.hs @@ -53,44 +53,45 @@ replaceAll opts = = everywhere (mkT splitMath) | otherwise = id +getCurPfx :: String -> WS (Maybe Index) +getCurPfx pfx = M.lookup pfx <$> get curChap + replaceBlock :: Options -> Block -> WS (ReplacedResult Block) replaceBlock opts (Header n (label, cls, attrs) text') = do let label' = if autoSectionLabels opts && not ("sec:" `isPrefixOf` label) then "sec:"++label else label - unless ("unnumbered" `elem` cls) $ do - -- TODO: Rework this horribleness that is curChap - modify curChap $ \cc -> - let ln = length cc - cl = lookup "label" attrs - inc l = let incd = fst (last l) + 1 - in init l ++ [(incd, fromMaybe (show incd) cl)] - cc' | ln > n = inc $ take n cc - | ln == n = inc cc - | otherwise = cc ++ take (n-ln-1) (zip (repeat 1) (repeat "1")) ++ [(1, fromMaybe "1" cl)] - in cc' + if "unnumbered" `elem` cls + then replaceNoRecurse $ Header n (label', cls, attrs) text' + else do + cur <- getCurPfx "sec" + let cc = fromMaybe [] cur + cl = lookup "label" attrs + inc l = let incd = fst (last l) + 1 + in init l ++ [(incd, fromMaybe (show incd) cl)] + cc' + | length cc >= n = inc $ take n cc + | otherwise = take (n-1) (cc ++ repeat (1, "1")) ++ [(1, fromMaybe "1" cl)] + modify curChap $ M.insert "sec" cc' when (n <= chaptersDepth opts) $ do modify pfxCounter $ M.singleton "sec" . fromMaybe 0 . M.lookup "sec" when ("sec:" `isPrefixOf` label') $ do - index <- get curChap modify referenceData $ M.insert label' RefRec { - refIndex=index - , refTitle= fromList text' + refIndex = cc' + , refTitle = fromList text' , refSubfigure = Nothing } - cc <- get curChap - let textCC | numberSections opts - , sectionsDepth opts < 0 - || n <= if sectionsDepth opts == 0 then chaptersDepth opts else sectionsDepth opts - , "unnumbered" `notElem` cls - = applyTemplate' (M.fromDistinctAscList [ - ("i", text (intercalate "." $ map snd cc)) - , ("n", text $ show $ n - 1) - , ("t", fromList text') - ]) $ secHeaderTemplate opts - | otherwise = fromList text' - replaceNoRecurse $ Header n (label', cls, attrs) $ toList textCC + let textCC | numberSections opts + , sectionsDepth opts < 0 + || n <= if sectionsDepth opts == 0 then chaptersDepth opts else sectionsDepth opts + = applyTemplate' (M.fromDistinctAscList [ + ("i", text (intercalate "." $ map snd cc')) + , ("n", text $ show $ n - 1) + , ("t", fromList text') + ]) $ secHeaderTemplate opts + | otherwise = fromList text' + replaceNoRecurse $ Header n (label', cls, attrs) $ toList textCC -- sub-objects replaceBlock opts (Div (label,cls,attrs) images) | Just pfx <- getRefPrefix opts label @@ -247,6 +248,11 @@ replaceBlock opts (Para [Span attrs@(label, _, _) [Math DisplayMath eq]]) = do (eq', idx) <- replaceEqn opts attrs eq pfx replaceNoRecurse $ Div attrs [Table [] [AlignCenter, AlignRight] [0.9, 0.09] [] [[[Plain [Math DisplayMath eq']], [Plain [Math DisplayMath $ "(" ++ idx ++ ")"]]]]] +replaceBlock opts x@(Div (label, _, attrs) _content) + | Just pfx <- getRefPrefix opts label + = do + void $ replaceAttr opts (Right label) (lookup "label" attrs) mempty pfx + replaceRecurse x replaceBlock _ _ = noReplaceRecurse getRefPrefix :: Options -> String -> Maybe String @@ -288,6 +294,11 @@ replaceInline opts (Image attr@(label,_,attrs) alt img@(_, tit)) f | isLatexFormat f -> ialt _ -> applyTemplate idxStr ialt $ pfxCaptionTemplate opts pfx replaceNoRecurse $ Image attr alt' img +replaceInline opts x@(Span (label,_,attrs) _content) + | Just pfx <- getRefPrefix opts label + = do + void $ replaceAttr opts (Right label) (lookup "label" attrs) mempty pfx + replaceRecurse x replaceInline _ _ = noReplaceRecurse replaceSubfigs :: Options -> [Inline] -> WS (ReplacedResult [Inline]) @@ -346,14 +357,18 @@ replaceAttr :: Options -> Either String String -> Maybe String -> Inlines -> Str replaceAttr o label refLabel title pfx = do let ropt = getPfx o pfx - chap <- take (chaptersDepth o) `fmap` get curChap + cur <- get curChap + let chap = take (chaptersDepth o) . fromMaybe [] . M.lookup "sec" $ cur i <- (1+) . fromMaybe 0 . M.lookup pfx <$> get pfxCounter + -- TODO: shouldReset should likely be a transitive closure... let shouldReset = M.keys . M.filter (\p -> pfx `elem` prefixScope p) $ prefixes o modify pfxCounter $ M.filterWithKey $ \k _ -> k `notElem` shouldReset modify pfxCounter $ M.insert pfx i let customLabel = prefixNumbering ropt - let index = chap ++ [(i, fromMaybe (customLabel i) refLabel)] + scop = join $ fmap (flip M.lookup cur) $ prefixScope ropt + index = chap ++ [(i, fromMaybe (customLabel i) refLabel)] label' = either (++ ':':show index) id label + modify curChap $ M.insert pfx index hasLabel <- M.member label' <$> get referenceData when hasLabel $ error $ "Duplicate label: " ++ label' diff --git a/lib/Text/Pandoc/CrossRef/References/Refs.hs b/lib/Text/Pandoc/CrossRef/References/Refs.hs index 7233066b..19668a56 100644 --- a/lib/Text/Pandoc/CrossRef/References/Refs.hs +++ b/lib/Text/Pandoc/CrossRef/References/Refs.hs @@ -126,7 +126,7 @@ citationGroupPred = (==) `on` liftM2 (,) citationPrefix citationMode replaceRefsOther' :: String -> Options -> [Citation] -> WS Inlines replaceRefsOther' prefix opts cits = do - indices <- mapM (getRefIndex prefix opts) cits + indices <- mapM getRefIndex cits let cap = maybe False isFirstUpper $ getLabelPrefix opts . citationId . head $ cits writePrefix | all (==SuppressAuthor) $ map citationMode cits @@ -150,8 +150,8 @@ data RefData = RefData { rdLabel :: String instance Ord RefData where (<=) = (<=) `on` rdIdx -getRefIndex :: String -> Options -> Citation -> WS RefData -getRefIndex _prefix _opts Citation{citationId=cid,citationSuffix=suf} +getRefIndex :: Citation -> WS RefData +getRefIndex Citation{citationId=cid,citationSuffix=suf} = do ref <- M.lookup llab <$> get referenceData let sub = refSubfigure <$> ref diff --git a/lib/Text/Pandoc/CrossRef/References/Types.hs b/lib/Text/Pandoc/CrossRef/References/Types.hs index 470df4cb..ee6d5e0e 100644 --- a/lib/Text/Pandoc/CrossRef/References/Types.hs +++ b/lib/Text/Pandoc/CrossRef/References/Types.hs @@ -29,23 +29,23 @@ import Text.Pandoc.Builder type Index = [(Int, String)] -data RefRec = RefRec { refIndex :: Index - , refTitle :: Inlines - , refSubfigure :: Maybe Index +data RefRec = RefRec { refIndex :: !Index + , refTitle :: !Inlines + , refSubfigure :: !(Maybe Index) } deriving (Show, Eq) type RefMap = M.Map String RefRec -- state data type -data References = References { referenceData_ :: RefMap - , curChap_ :: Index - , pfxCounter_ :: M.Map String Int +data References = References { referenceData_ :: !RefMap + , curChap_ :: !(M.Map String Index) + , pfxCounter_ :: !(M.Map String Int) } deriving (Show, Eq) --state monad type WS a = State References a instance Default References where - def = References M.empty [] M.empty + def = References M.empty M.empty M.empty deriveAccessors ''References diff --git a/test/m2m/custom-prefixes/expect.md b/test/m2m/custom-prefixes/expect.md new file mode 100644 index 00000000..2a63f562 --- /dev/null +++ b/test/m2m/custom-prefixes/expect.md @@ -0,0 +1,9 @@ +::: {#dfn:ring} +A *ring* is a triple $(R,+,*)$ satisfying: + +1. [$+$ is an abelian group]{#cl:addgp} +2. [$*$ is a monoid]{#cl:multmon} +3. [$*$ distributes over $+$]{#cl:distrib} +::: + +cl. 1, cl. 3, dfn. 1 diff --git a/test/m2m/custom-prefixes/expect.tex b/test/m2m/custom-prefixes/expect.tex new file mode 100644 index 00000000..ca7e6579 --- /dev/null +++ b/test/m2m/custom-prefixes/expect.tex @@ -0,0 +1,14 @@ +\leavevmode\hypertarget{dfn:ring}{}% +A \emph{ring} is a triple \((R,+,*)\) satisfying: + +\begin{enumerate} +\tightlist +\item + \protect\hypertarget{cl:addgp}{}{\(+\) is an abelian group} +\item + \protect\hypertarget{cl:multmon}{}{\(*\) is a monoid} +\item + \protect\hypertarget{cl:distrib}{}{\(*\) distributes over \(+\)} +\end{enumerate} + +cl.~\ref{cl:addgp}, cl.~\ref{cl:distrib}, dfn.~\ref{dfn:ring} diff --git a/test/m2m/custom-prefixes/input.md b/test/m2m/custom-prefixes/input.md new file mode 100644 index 00000000..5d80ab8f --- /dev/null +++ b/test/m2m/custom-prefixes/input.md @@ -0,0 +1,19 @@ +--- +prefixes: + dfn: + ref: ["dfn.", "dfns."] + title: "Definition" + cl: + ref: ["cl.", "cls."] + scope: "dfn" +... + +
+A _ring_ is a triple $(R,+,*)$ satisfying: + +#. [$+$ is an abelian group]{#cl:addgp} +#. [$*$ is a monoid]{#cl:multmon} +#. [$*$ distributes over $+$]{#cl:distrib} +
+ +@cl:addgp, @cl:distrib, @dfn:ring diff --git a/test/test-pandoc-crossref.hs b/test/test-pandoc-crossref.hs index 33c07af6..75a7d076 100644 --- a/test/test-pandoc-crossref.hs +++ b/test/test-pandoc-crossref.hs @@ -53,7 +53,9 @@ main = hspec $ do testAll (equation' "a^2+b^2=c^2" "equation") (spanWith ("eq:equation", [], []) (equation' "a^2+b^2=c^2\\qquad(1)" []), (referenceData =: M.fromList $ refRec'' "eq:equation" 1) . - (pfxCounter =: M.singleton "eq" 1)) + (pfxCounter =: M.singleton "eq" 1) . + (curChap =: M.singleton "eq" [(1, "1")]) + ) it "Labels equations in the middle of text" $ testAll ( text "This is an equation: " @@ -64,7 +66,9 @@ main = hspec $ do <> spanWith ("eq:equation", [], []) (equation' "a^2+b^2=c^2\\qquad(1)" []) <> text " it should be labeled", (referenceData =: M.fromList $ refRec'' "eq:equation" 1) . - (pfxCounter =: M.singleton "eq" 1)) + (pfxCounter =: M.singleton "eq" 1) . + (curChap =: M.singleton "eq" [(1, "1")]) + ) it "Labels equations in the beginning of text" $ testAll ( equation' "a^2+b^2=c^2" "equation" @@ -73,7 +77,9 @@ main = hspec $ do spanWith ("eq:equation", [], []) (equation' "a^2+b^2=c^2\\qquad(1)" []) <> text " it should be labeled", (referenceData =: M.fromList $ refRec'' "eq:equation" 1) . - (pfxCounter =: M.singleton "eq" 1)) + (pfxCounter =: M.singleton "eq" 1) . + (curChap =: M.singleton "eq" [(1, "1")]) + ) it "Labels equations in the end of text" $ testAll ( text "This is an equation: " @@ -82,7 +88,9 @@ main = hspec $ do text "This is an equation: " <> spanWith ("eq:equation", [], []) (equation' "a^2+b^2=c^2\\qquad(1)" []), (referenceData =: M.fromList $ refRec'' "eq:equation" 1) . - (pfxCounter =: M.singleton "eq" 1)) + (pfxCounter =: M.singleton "eq" 1) . + (curChap =: M.singleton "eq" [(1, "1")]) + ) -- TODO: -- describe "References.Blocks.spanInlines" @@ -93,7 +101,9 @@ main = hspec $ do testAll (figure "test.jpg" [] "Test figure" "figure") (figure "test.jpg" [] "Figure 1: Test figure" "figure", (referenceData =: M.fromList $ refRec' "fig:figure" 1 "Test figure") . - (pfxCounter =: M.singleton "fig" 1)) + (pfxCounter =: M.singleton "fig" 1) . + (curChap =: M.singleton "fig" [(1, "1")]) + ) it "Labels subfigures" $ testAll ( divWith ("fig:subfigure",[],[]) ( @@ -143,12 +153,17 @@ main = hspec $ do refTitle = fromList [Str "figure",Space,Str "caption",Space,Str "2"], refSubfigure = Nothing}) ] - ) . (pfxCounter =: M.singleton "fig" 2)) + ) . + (pfxCounter =: M.singleton "fig" 2) . + (curChap =: M.singleton "fig" [(2, "2")]) + ) it "Labels equations" $ testAll (equation "a^2+b^2=c^2" "equation") (para $ spanWith ("eq:equation", [], []) (equation' "a^2+b^2=c^2\\qquad(1)" []), (referenceData =: M.fromList $ refRec'' "eq:equation" 1) . - (pfxCounter =: M.singleton "eq" 1)) + (pfxCounter =: M.singleton "eq" 1) . + (curChap =: M.singleton "eq" [(1, "1")]) + ) it "Labels equations in the middle of text" $ testAll (para $ text "This is an equation: " @@ -159,7 +174,9 @@ main = hspec $ do <> spanWith ("eq:equation", [], []) (equation' "a^2+b^2=c^2\\qquad(1)" []) <> text " it should be labeled", (referenceData =: M.fromList $ refRec'' "eq:equation" 1) . - (pfxCounter =: M.singleton "eq" 1)) + (pfxCounter =: M.singleton "eq" 1) . + (curChap =: M.singleton "eq" [(1, "1")]) + ) it "Labels equations in the beginning of text" $ testAll (para $ equation' "a^2+b^2=c^2" "equation" @@ -168,7 +185,9 @@ main = hspec $ do spanWith ("eq:equation", [], []) (equation' "a^2+b^2=c^2\\qquad(1)" []) <> text " it should be labeled", (referenceData =: M.fromList $ refRec'' "eq:equation" 1) . - (pfxCounter =: M.singleton "eq" 1)) + (pfxCounter =: M.singleton "eq" 1) . + (curChap =: M.singleton "eq" [(1, "1")]) + ) it "Labels equations in the end of text" $ testAll (para $ text "This is an equation: " @@ -177,27 +196,35 @@ main = hspec $ do text "This is an equation: " <> spanWith ("eq:equation", [], []) (equation' "a^2+b^2=c^2\\qquad(1)" []), (referenceData =: M.fromList $ refRec'' "eq:equation" 1) . - (pfxCounter =: M.singleton "eq" 1)) + (pfxCounter =: M.singleton "eq" 1) . + (curChap =: M.singleton "eq" [(1, "1")]) + ) it "Labels tables" $ testAll (table' "Test table" "table") (divWith ("tbl:table", [], []) $ table' "Table 1: Test table" [], (referenceData =: M.fromList $ refRec' "tbl:table" 1 "Test table") . - (pfxCounter =: M.singleton "tbl" 1)) + (pfxCounter =: M.singleton "tbl" 1) . + (curChap =: M.singleton "tbl" [(1, "1")]) + ) it "Labels code blocks" $ testAll (codeBlock' "Test code block" "codeblock") (codeBlockDiv "Listing 1: Test code block" "codeblock", (referenceData =: M.fromList $ refRec' "lst:codeblock" 1 "Test code block") . - (pfxCounter =: M.singleton "lst" 1)) + (pfxCounter =: M.singleton "lst" 1) . + (curChap =: M.singleton "lst" [(1, "1")]) + ) it "Labels code block divs" $ testAll (codeBlockDiv "Test code block" "codeblock") (codeBlockDiv "Listing 1: Test code block" "codeblock", (referenceData =: M.fromList $ refRec' "lst:codeblock" 1 "Test code block") . - (pfxCounter =: M.singleton "lst" 1)) + (pfxCounter =: M.singleton "lst" 1) . + (curChap =: M.singleton "lst" [(1, "1")]) + ) it "Labels sections divs" $ testAll (section "Section Header" 1 "section") (section "Section Header" 1 "section", (referenceData ^= M.fromList (refRec' "sec:section" 1 "Section Header")) . - (curChap ^= [(1,"1")])) + (curChap ^= M.singleton "sec" [(1,"1")])) describe "References.Refs.replaceRefs" $ do it "References one image" $ From e13af3761d32fc6a54f0fe5de689b7817fed947c Mon Sep 17 00:00:00 2001 From: Nikolay Yakimov Date: Sat, 7 Apr 2018 21:19:56 +0300 Subject: [PATCH 025/134] Remove hard-coded label prefixes, clean-up some old code --- lib/Text/Pandoc/CrossRef.hs | 4 +- lib/Text/Pandoc/CrossRef/References/Blocks.hs | 57 +++++-------------- lib/Text/Pandoc/CrossRef/References/Refs.hs | 2 +- .../Pandoc/CrossRef/Util/CodeBlockCaptions.hs | 23 ++++---- lib/Text/Pandoc/CrossRef/Util/Options.hs | 21 +++++++ lib/Text/Pandoc/CrossRef/Util/Util.hs | 11 ---- package.yaml | 1 + pandoc-crossref.cabal | 9 ++- test/test-pandoc-crossref.hs | 2 +- 9 files changed, 58 insertions(+), 72 deletions(-) diff --git a/lib/Text/Pandoc/CrossRef.hs b/lib/Text/Pandoc/CrossRef.hs index c2b75428..50da0fac 100644 --- a/lib/Text/Pandoc/CrossRef.hs +++ b/lib/Text/Pandoc/CrossRef.hs @@ -88,7 +88,6 @@ import Data.Monoid ((<>)) import Text.Pandoc.CrossRef.References import Text.Pandoc.CrossRef.Util.Settings import Text.Pandoc.CrossRef.Util.Options as O -import Text.Pandoc.CrossRef.Util.CodeBlockCaptions import Text.Pandoc.CrossRef.Util.ModifyMeta import Text.Pandoc.CrossRef.Util.Settings.Gen as SG @@ -109,8 +108,7 @@ crossRefBlocks blocks = do opts <- R.asks creOptions let doWalk = - bottomUpM (mkCodeBlockCaptions opts) blocks - >>= replaceAll opts + replaceAll opts blocks >>= bottomUpM (replaceRefs opts) >>= bottomUpM (listOf opts) return $ evalState doWalk def diff --git a/lib/Text/Pandoc/CrossRef/References/Blocks.hs b/lib/Text/Pandoc/CrossRef/References/Blocks.hs index 9f7cd58e..2d6c5d45 100644 --- a/lib/Text/Pandoc/CrossRef/References/Blocks.hs +++ b/lib/Text/Pandoc/CrossRef/References/Blocks.hs @@ -38,6 +38,7 @@ import Text.Pandoc.CrossRef.Util.Util import Text.Pandoc.CrossRef.Util.Options import Text.Pandoc.CrossRef.Util.Prefixes import Text.Pandoc.CrossRef.Util.Template +import Text.Pandoc.CrossRef.Util.CodeBlockCaptions import Control.Applicative import Data.Default (def) import Prelude @@ -46,7 +47,8 @@ replaceAll :: (Data a) => Options -> a -> WS a replaceAll opts = runReplace (mkRR (replaceBlock opts) `extRR` replaceInline opts) . runSplitMath - . everywhere (mkT divBlocks `extT` spanInlines opts) + . everywhere (mkT (divBlocks opts) `extT` spanInlines opts) + . everywhere (mkT (mkCodeBlockCaptions opts)) where runSplitMath | tableEqns opts , not $ isLatexFormat (outFormat opts) @@ -184,34 +186,6 @@ replaceBlock opts (Div divOps@(label,_,attrs) [Table title align widths header c rawInline "latex" (mkLaTeXLabel label) <> ititle _ -> applyTemplate idxStr ititle $ pfxCaptionTemplate opts pfx replaceNoRecurse $ Div divOps [Table title' align widths header cells] -replaceBlock opts cb@(CodeBlock (label, classes, attrs) code) - | not $ null label - , Just pfx <- getRefPrefix opts label - , Just caption <- lookup "caption" attrs - = case outFormat opts of - f - --if used with listings package,nothing shoud be done - | isLatexFormat f, listings opts -> noReplaceNoRecurse - --if not using listings, however, wrap it in a codelisting environment - | isLatexFormat f -> - replaceNoRecurse $ Div nullAttr [ - RawBlock (Format "latex") "\\begin{codelisting}" - , Plain [ - RawInline (Format "latex") "\\caption{" - , Str caption - , RawInline (Format "latex") "}" - ] - , cb - , RawBlock (Format "latex") "\\end{codelisting}" - ] - _ -> do - let cap = text caption - idxStr <- replaceAttr opts (Right label) (lookup "label" attrs) cap pfx - let caption' = applyTemplate idxStr cap $ pfxCaptionTemplate opts pfx - replaceNoRecurse $ Div (label, "listing":classes, []) [ - mkCaption opts "Caption" caption' - , CodeBlock ([], classes, attrs \\ [("caption", caption)]) code - ] replaceBlock opts (Div (label,"listing":_, []) [Para caption, CodeBlock ([],classes,attrs) code]) @@ -255,15 +229,6 @@ replaceBlock opts x@(Div (label, _, attrs) _content) replaceRecurse x replaceBlock _ _ = noReplaceRecurse -getRefPrefix :: Options -> String -> Maybe String -getRefPrefix opts label - | ':' `notElem` label = Nothing - | otherwise = - let pfx = takeWhile (/=':') label - in if pfx `elem` prefixList opts - then Just pfx - else Nothing - replaceEqn :: Options -> Attr -> String -> Maybe String -> WS (String, String) replaceEqn opts (label, _, attrs) eq pfx = do let label' | null label = Left "eq" @@ -323,13 +288,19 @@ replaceSubfig opts x@(Image (label,cls,attrs) alt (src, tit)) in return [Image (label, cls, attrs) alt' (src, tit')] replaceSubfig _ x = return [x] -divBlocks :: Block -> Block -divBlocks (Table title align widths header cells) +divBlocks :: Options -> Block -> Block +divBlocks opts (Table title align widths header cells) | not $ null title - , Just label <- getRefLabel "tbl" [last title] + , Just label <- getRefLabel opts [last title] = Div (label,[],[]) [Table (dropWhileEnd isSpace $ init title) align widths header cells] where isSpace = (||) <$> (==Space) <*> (==SoftBreak) -divBlocks x = x +divBlocks opts (CodeBlock (label, classes, attrs) code) + | Just caption <- lookup "caption" attrs + , Just _ <- getRefPrefix opts label + = let p = Para $ toList $ text caption + cb' = CodeBlock ([], classes, delete ("caption", caption) attrs) code + in Div (label,"listing":classes, []) [p, cb'] +divBlocks _ x = x splitMath :: [Block] -> [Block] @@ -347,7 +318,7 @@ splitMath xs = xs spanInlines :: Options -> [Inline] -> [Inline] spanInlines opts (math@(Math DisplayMath _eq):ils) | c:ils' <- dropWhile (==Space) ils - , Just label <- getRefLabel "eq" [c] + , Just label <- getRefLabel opts [c] = Span (label,[],[]) [math]:ils' | autoEqnLabels opts = Span nullAttr [math]:ils diff --git a/lib/Text/Pandoc/CrossRef/References/Refs.hs b/lib/Text/Pandoc/CrossRef/References/Refs.hs index 19668a56..da010e5d 100644 --- a/lib/Text/Pandoc/CrossRef/References/Refs.hs +++ b/lib/Text/Pandoc/CrossRef/References/Refs.hs @@ -34,7 +34,7 @@ import Data.Accessor.Monad.Trans.State import Text.Pandoc.CrossRef.References.Types import Text.Pandoc.CrossRef.Util.Template import Text.Pandoc.CrossRef.Util.Util -import Text.Pandoc.CrossRef.Util.Options +import Text.Pandoc.CrossRef.Util.Options hiding (getRefPrefix) import Text.Pandoc.CrossRef.Util.Prefixes import Control.Applicative import Data.Char (toLower) diff --git a/lib/Text/Pandoc/CrossRef/Util/CodeBlockCaptions.hs b/lib/Text/Pandoc/CrossRef/Util/CodeBlockCaptions.hs index 57303e71..6a873904 100644 --- a/lib/Text/Pandoc/CrossRef/Util/CodeBlockCaptions.hs +++ b/lib/Text/Pandoc/CrossRef/Util/CodeBlockCaptions.hs @@ -24,31 +24,30 @@ module Text.Pandoc.CrossRef.Util.CodeBlockCaptions ) where import Text.Pandoc.Definition -import Data.List (isPrefixOf, stripPrefix) -import Data.Maybe (fromMaybe) -import Text.Pandoc.CrossRef.References.Types +import Data.List (stripPrefix) import Text.Pandoc.CrossRef.Util.Options -import Text.Pandoc.CrossRef.Util.Util -mkCodeBlockCaptions :: Options -> [Block] -> WS [Block] -mkCodeBlockCaptions opts x@(cb@(CodeBlock _ _):p@(Para _):xs) - = return $ fromMaybe x $ orderAgnostic opts $ p:cb:xs -mkCodeBlockCaptions opts x@(p@(Para _):cb@(CodeBlock _ _):xs) - = return $ fromMaybe x $ orderAgnostic opts $ p:cb:xs -mkCodeBlockCaptions _ x = return x +mkCodeBlockCaptions :: Options -> [Block] -> [Block] +mkCodeBlockCaptions opts (cb@(CodeBlock _ _):p@(Para _):xs) + | Just res <- orderAgnostic opts $ p:cb:xs + = res +mkCodeBlockCaptions opts (p@(Para _):cb@(CodeBlock _ _):xs) + | Just res <- orderAgnostic opts $ p:cb:xs + = res +mkCodeBlockCaptions _ x = x orderAgnostic :: Options -> [Block] -> Maybe [Block] orderAgnostic opts (Para ils:CodeBlock (label,classes,attrs) code:xs) | codeBlockCaptions opts , Just caption <- getCodeBlockCaption ils , not $ null label - , "lst" `isPrefixOf` label + , Just _ <- getRefPrefix opts label = return $ Div (label,"listing":classes, []) [Para caption, CodeBlock ([],classes,attrs) code] : xs orderAgnostic opts (Para ils:CodeBlock (_,classes,attrs) code:xs) | codeBlockCaptions opts , Just (caption, labinl) <- splitLast <$> getCodeBlockCaption ils - , Just label <- getRefLabel "lst" labinl + , Just label <- getRefLabel opts labinl = return $ Div (label,"listing":classes, []) [Para $ init caption, CodeBlock ([],classes,attrs) code] : xs where diff --git a/lib/Text/Pandoc/CrossRef/Util/Options.hs b/lib/Text/Pandoc/CrossRef/Util/Options.hs index 07dcbef0..57f1eab8 100644 --- a/lib/Text/Pandoc/CrossRef/Util/Options.hs +++ b/lib/Text/Pandoc/CrossRef/Util/Options.hs @@ -25,6 +25,8 @@ import Text.Pandoc.CrossRef.Util.Prefixes import qualified Data.Map as M import Text.Pandoc.Builder import Data.Maybe +import Data.List +import Data.List.Extra data Options = Options { cref :: Bool , chaptersDepth :: Int @@ -83,3 +85,22 @@ getPfx :: Options -> String -> Prefix getPfx o pn = fromMaybe defaultPfx $ M.lookup pn $ prefixes o where defaultPfx = error $ "Undefined prefix: \"" <> pn <> "\"" + +getRefPrefix :: Options -> String -> Maybe String +getRefPrefix opts label + | ':' `notElem` label = Nothing + | otherwise = + let pfx = takeWhile (/=':') label + in if pfx `elem` prefixList opts + then Just pfx + else Nothing + +getRefLabel :: Options -> [Inline] -> Maybe String +getRefLabel _ [] = Nothing +getRefLabel opts ils + | Str attr <- last ils + , all (==Space) (init ils) + , Just lbl <- stripPrefix "{#" attr >>= stripSuffix "}" + , Just _ <- getRefPrefix opts lbl + = Just lbl +getRefLabel _ _ = Nothing diff --git a/lib/Text/Pandoc/CrossRef/Util/Util.hs b/lib/Text/Pandoc/CrossRef/Util/Util.hs index 6cf21fb7..f99525f9 100644 --- a/lib/Text/Pandoc/CrossRef/Util/Util.hs +++ b/lib/Text/Pandoc/CrossRef/Util/Util.hs @@ -29,7 +29,6 @@ import Text.Pandoc.Definition import Text.Pandoc.Builder hiding ((<>)) import Text.Pandoc.Class import Data.Char (toUpper, toLower, isUpper) -import Data.List (isSuffixOf, isPrefixOf, stripPrefix) import Data.Generics hiding (Prefix) import Text.Pandoc.Writers.LaTeX import Data.Default @@ -111,13 +110,3 @@ mkLaTeXLabel' l = let ll = either (error . show) T.unpack $ runPure (writeLaTeX def $ Pandoc nullMeta [Div (l, [], []) []]) in takeWhile (/='}') . drop 1 . dropWhile (/='{') $ ll - -getRefLabel :: String -> [Inline] -> Maybe String -getRefLabel _ [] = Nothing -getRefLabel tag ils - | Str attr <- last ils - , all (==Space) (init ils) - , "}" `isSuffixOf` attr - , ("{#"++tag++":") `isPrefixOf` attr - = init `fmap` stripPrefix "{#" attr -getRefLabel _ _ = Nothing diff --git a/package.yaml b/package.yaml index 18a8b6c4..eb25057e 100644 --- a/package.yaml +++ b/package.yaml @@ -33,6 +33,7 @@ dependencies: - directory >=1 && <1.4 - filepath >=1.1 && <1.5 - text >=1.2.2 && <1.3 +- extra >= 1.6 && <1.7 library: source-dirs: lib ghc-options: -Wall diff --git a/pandoc-crossref.cabal b/pandoc-crossref.cabal index 41e6a95b..84e824a2 100644 --- a/pandoc-crossref.cabal +++ b/pandoc-crossref.cabal @@ -2,7 +2,7 @@ -- -- see: https://github.com/sol/hpack -- --- hash: 7363be4fc2eccadb7479eece11df48cf220e2ec120304d1852966e9f0c1e3a06 +-- hash: 0aa60fb73626950d93c18ec1bb626dece6292c0d0f4a305bf777b0e1ba6e265b name: pandoc-crossref version: 0.3.1.0 @@ -26,6 +26,9 @@ extra-source-files: data-files: docs/demo/demo.md docs/index.md + test/m2m/custom-prefixes/expect.md + test/m2m/custom-prefixes/expect.tex + test/m2m/custom-prefixes/input.md test/m2m/delim/expect.md test/m2m/delim/expect.tex test/m2m/delim/input.md @@ -79,6 +82,7 @@ library , data-accessor-transformers >=0.2.1.6 && <0.3.0.0 , data-default >=0.4 && <0.8 , directory >=1 && <1.4 + , extra >=1.6 && <1.7 , filepath >=1.1 && <1.5 , mtl >=1.1 && <2.3 , pandoc >=2.1.3 && <2.2 @@ -126,6 +130,7 @@ executable pandoc-crossref , data-default >=0.4 && <0.8 , deepseq >=1.4 && <1.5 , directory >=1 && <1.4 + , extra >=1.6 && <1.7 , filepath >=1.1 && <1.5 , mtl >=1.1 && <2.3 , open-browser >=0.2 && <0.3 @@ -158,6 +163,7 @@ test-suite test-integrative , data-accessor-transformers >=0.2.1.6 && <0.3.0.0 , data-default >=0.4 && <0.8 , directory >=1 && <1.4 + , extra >=1.6 && <1.7 , filepath >=1.1 && <1.5 , hspec >=2.4.4 && <3 , mtl >=1.1 && <2.3 @@ -186,6 +192,7 @@ test-suite test-pandoc-crossref , data-accessor-transformers >=0.2.1.6 && <0.3.0.0 , data-default >=0.4 && <0.8 , directory >=1 && <1.4 + , extra >=1.6 && <1.7 , filepath >=1.1 && <1.5 , hspec >=2.4.4 && <3 , mtl >=1.1 && <2.3 diff --git a/test/test-pandoc-crossref.hs b/test/test-pandoc-crossref.hs index 75a7d076..009e8115 100644 --- a/test/test-pandoc-crossref.hs +++ b/test/test-pandoc-crossref.hs @@ -404,7 +404,7 @@ testRefs :: Blocks -> References -> Blocks -> Expectation testRefs bs st rbs = testState (bottomUpM (References.Refs.replaceRefs defaultOptions)) st bs (rbs, id) testCBCaptions :: Blocks -> Blocks -> Expectation -testCBCaptions bs res = runState (bottomUpM (Util.CodeBlockCaptions.mkCodeBlockCaptions defaultOptions{Text.Pandoc.CrossRef.Util.Options.codeBlockCaptions=True}) (toList bs)) def `shouldBe` (toList res,def) +testCBCaptions bs res = bottomUp (Util.CodeBlockCaptions.mkCodeBlockCaptions defaultOptions{Text.Pandoc.CrossRef.Util.Options.codeBlockCaptions=True}) (toList bs) `shouldBe` toList res testList :: Blocks -> (References -> References) -> Blocks -> Expectation testList bs st res = runState (bottomUpM (References.List.listOf defaultOptions) (toList bs)) (st def) `shouldBe` (toList res, st def) From 2ec199995a8299c6ad0264c61804f9d2dff09d62 Mon Sep 17 00:00:00 2001 From: Nikolay Yakimov Date: Sat, 7 Apr 2018 21:40:33 +0300 Subject: [PATCH 026/134] removed commented-out code --- lib/Text/Pandoc/CrossRef/Util/Options.hs | 20 -------------------- 1 file changed, 20 deletions(-) diff --git a/lib/Text/Pandoc/CrossRef/Util/Options.hs b/lib/Text/Pandoc/CrossRef/Util/Options.hs index 57f1eab8..47b00a77 100644 --- a/lib/Text/Pandoc/CrossRef/Util/Options.hs +++ b/lib/Text/Pandoc/CrossRef/Util/Options.hs @@ -35,16 +35,6 @@ data Options = Options { cref :: Bool , autoSectionLabels :: Bool , numberSections :: Bool , sectionsDepth :: Int - -- , figPrefix :: Bool -> Int -> [Inline] - -- , eqnPrefix :: Bool -> Int -> [Inline] - -- , tblPrefix :: Bool -> Int -> [Inline] - -- , lstPrefix :: Bool -> Int -> [Inline] - -- , secPrefix :: Bool -> Int -> [Inline] - -- , figPrefixTemplate :: Template - -- , eqnPrefixTemplate :: Template - -- , tblPrefixTemplate :: Template - -- , lstPrefixTemplate :: Template - -- , secPrefixTemplate :: Template , refIndexTemplate :: Template , subfigureRefIndexTemplate :: Template , secHeaderTemplate :: Template @@ -53,17 +43,8 @@ data Options = Options { cref :: Bool , pairDelim :: Inlines , lastDelim :: Inlines , refDelim :: Inlines - -- , lofTitle :: [Block] - -- , lotTitle :: [Block] - -- , lolTitle :: [Block] , outFormat :: Maybe Format - -- , figureTemplate :: Template - -- , subfigureTemplate :: Template - -- , subfigureChildTemplate :: Template , ccsTemplate :: Template - -- , tableTemplate :: Template - -- , listingTemplate :: Template - -- , customLabel :: String -> Int -> Maybe String , ccsDelim :: Inlines , ccsLabelSep :: Inlines , tableEqns :: Bool @@ -72,7 +53,6 @@ data Options = Options { cref :: Bool , linkReferences :: Bool , nameInLink :: Bool , prefixes :: Prefixes - -- TODO: Defaults for prefix settings } prefixList :: Options -> [String] From 5da0d84b2cf32bf60dd4a9895ef912093e465bc2 Mon Sep 17 00:00:00 2001 From: Nikolay Yakimov Date: Sat, 7 Apr 2018 21:43:58 +0300 Subject: [PATCH 027/134] Reduce name shadowing --- lib/Text/Pandoc/CrossRef/References/Blocks.hs | 50 +++++++++---------- 1 file changed, 25 insertions(+), 25 deletions(-) diff --git a/lib/Text/Pandoc/CrossRef/References/Blocks.hs b/lib/Text/Pandoc/CrossRef/References/Blocks.hs index 2d6c5d45..83b149da 100644 --- a/lib/Text/Pandoc/CrossRef/References/Blocks.hs +++ b/lib/Text/Pandoc/CrossRef/References/Blocks.hs @@ -24,7 +24,7 @@ module Text.Pandoc.CrossRef.References.Blocks ) where import Text.Pandoc.Definition -import Text.Pandoc.Builder hiding ((<>)) +import qualified Text.Pandoc.Builder as B import Text.Pandoc.Shared (stringify) import Control.Monad.State hiding (get, modify) import Data.List @@ -81,27 +81,27 @@ replaceBlock opts (Header n (label, cls, attrs) text') when ("sec:" `isPrefixOf` label') $ do modify referenceData $ M.insert label' RefRec { refIndex = cc' - , refTitle = fromList text' + , refTitle = B.fromList text' , refSubfigure = Nothing } let textCC | numberSections opts , sectionsDepth opts < 0 || n <= if sectionsDepth opts == 0 then chaptersDepth opts else sectionsDepth opts = applyTemplate' (M.fromDistinctAscList [ - ("i", text (intercalate "." $ map snd cc')) - , ("n", text $ show $ n - 1) - , ("t", fromList text') + ("i", B.text (intercalate "." $ map snd cc')) + , ("n", B.text $ show $ n - 1) + , ("t", B.fromList text') ]) $ secHeaderTemplate opts - | otherwise = fromList text' - replaceNoRecurse $ Header n (label', cls, attrs) $ toList textCC + | otherwise = B.fromList text' + replaceNoRecurse $ Header n (label', cls, attrs) $ B.toList textCC -- sub-objects replaceBlock opts (Div (label,cls,attrs) images) | Just pfx <- getRefPrefix opts label , Para caption <- last images = do - idxStr <- replaceAttr opts (Right label) (lookup "label" attrs) (fromList caption) pfx + idxStr <- replaceAttr opts (Right label) (lookup "label" attrs) (B.fromList caption) pfx let (cont, st) = runState (runReplace (mkRR $ replaceSubfigs opts') $ init images) def - collectedCaptions = toList $ + collectedCaptions = B.toList $ intercalate' (ccsDelim opts) $ map (collectCaps . snd) $ sortOn (refIndex . snd) @@ -114,9 +114,9 @@ replaceBlock opts (Div (label,cls,attrs) images) (refTitle v) (ccsTemplate opts) vars = M.fromDistinctAscList - [ ("ccs", fromList collectedCaptions) + [ ("ccs", B.fromList collectedCaptions) , ("i", idxStr) - , ("t", fromList caption) + , ("t", B.fromList caption) ] capt = applyTemplate' vars $ pfxCaptionTemplate opts pfx opts' = opts { @@ -141,7 +141,7 @@ replaceBlock opts (Div (label,cls,attrs) images) , RawBlock (Format "latex") "\\end{figure}"] _ -> replaceNoRecurse $ Div (label, "subfigures":cls, attrs) $ toTable cont capt where - toTable :: [Block] -> Inlines -> [Block] + toTable :: [Block] -> B.Inlines -> [Block] toTable blks capt | subfigGrid opts = [Table [] align widths [] $ map blkToRow blks, mkCaption opts "Image Caption" capt] | otherwise = blks ++ [mkCaption opts "Image Caption" capt] @@ -178,12 +178,12 @@ replaceBlock opts (Div divOps@(label,_,attrs) [Table title align widths header c | not $ null title , Just pfx <- getRefPrefix opts label = do - let ititle = fromList title + let ititle = B.fromList title idxStr <- replaceAttr opts (Right label) (lookup "label" attrs) ititle pfx - let title' = toList $ + let title' = B.toList $ case outFormat opts of f | isLatexFormat f -> - rawInline "latex" (mkLaTeXLabel label) <> ititle + B.rawInline "latex" (mkLaTeXLabel label) <> ititle _ -> applyTemplate idxStr ititle $ pfxCaptionTemplate opts pfx replaceNoRecurse $ Div divOps [Table title' align widths header cells] replaceBlock opts @@ -208,7 +208,7 @@ replaceBlock opts , RawBlock (Format "latex") "\\end{codelisting}" ] _ -> do - let icaption = fromList caption + let icaption = B.fromList caption idxStr <- replaceAttr opts (Right label) (lookup "label" attrs) icaption pfx let caption' = applyTemplate idxStr icaption $ pfxCaptionTemplate opts pfx replaceNoRecurse $ Div (label, "listing":classes, []) [ @@ -253,9 +253,9 @@ replaceInline opts (Image attr@(label,_,attrs) alt img@(_, tit)) | Just pfx <- getRefPrefix opts label , "fig:" `isPrefixOf` tit = do - let ialt = fromList alt + let ialt = B.fromList alt idxStr <- replaceAttr opts (Right label) (lookup "label" attrs) ialt pfx - let alt' = toList $ case outFormat opts of + let alt' = B.toList $ case outFormat opts of f | isLatexFormat f -> ialt _ -> applyTemplate idxStr ialt $ pfxCaptionTemplate opts pfx replaceNoRecurse $ Image attr alt' img @@ -275,13 +275,13 @@ replaceSubfig opts x@(Image (label,cls,attrs) alt (src, tit)) let label' | "fig:" `isPrefixOf` label = Right label | null label = Left "fig" | otherwise = Right $ "fig:" ++ label - let ialt = fromList alt + let ialt = B.fromList alt idxStr <- replaceAttr opts label' (lookup "label" attrs) ialt "fig" case outFormat opts of f | isLatexFormat f -> return $ latexSubFigure x label _ -> - let alt' = toList $ applyTemplate idxStr ialt $ pfxCaptionTemplate opts "fig" + let alt' = B.toList $ applyTemplate idxStr ialt $ pfxCaptionTemplate opts "fig" tit' | "nocaption" `elem` cls = fromMaybe tit $ stripPrefix "fig:" tit | "fig:" `isPrefixOf` tit = tit | otherwise = "fig:" ++ tit @@ -297,7 +297,7 @@ divBlocks opts (Table title align widths header cells) divBlocks opts (CodeBlock (label, classes, attrs) code) | Just caption <- lookup "caption" attrs , Just _ <- getRefPrefix opts label - = let p = Para $ toList $ text caption + = let p = Para $ B.toList $ B.text caption cb' = CodeBlock ([], classes, delete ("caption", caption) attrs) code in Div (label,"listing":classes, []) [p, cb'] divBlocks _ x = x @@ -324,7 +324,7 @@ spanInlines opts (math@(Math DisplayMath _eq):ils) = Span nullAttr [math]:ils spanInlines _ x = x -replaceAttr :: Options -> Either String String -> Maybe String -> Inlines -> String -> WS Inlines +replaceAttr :: Options -> Either String String -> Maybe String -> B.Inlines -> String -> WS B.Inlines replaceAttr o label refLabel title pfx = do let ropt = getPfx o pfx @@ -370,7 +370,7 @@ latexSubFigure (Image (_, cls, attrs) alt (src, title)) label = ] latexSubFigure x _ = [x] -mkCaption :: Options -> String -> Inlines -> Block +mkCaption :: Options -> String -> B.Inlines -> Block mkCaption opts style - | outFormat opts == Just (Format "docx") = Div ([], [], [("custom-style", style)]) . toList . para - | otherwise = Para . toList + | outFormat opts == Just (Format "docx") = Div ([], [], [("custom-style", style)]) . B.toList . B.para + | otherwise = Para . B.toList From 9de84d190ebd9e760884a8bcb2ae34e782bed0eb Mon Sep 17 00:00:00 2001 From: Nikolay Yakimov Date: Sat, 7 Apr 2018 22:07:49 +0300 Subject: [PATCH 028/134] Clean up warnings --- lib/Text/Pandoc/CrossRef/References/Blocks.hs | 3 ++- lib/Text/Pandoc/CrossRef/Util/Meta.hs | 2 +- lib/Text/Pandoc/CrossRef/Util/Prefixes.hs | 13 ++++++++++--- lib/Text/Pandoc/CrossRef/Util/Template.hs | 2 +- 4 files changed, 14 insertions(+), 6 deletions(-) diff --git a/lib/Text/Pandoc/CrossRef/References/Blocks.hs b/lib/Text/Pandoc/CrossRef/References/Blocks.hs index 83b149da..71340b98 100644 --- a/lib/Text/Pandoc/CrossRef/References/Blocks.hs +++ b/lib/Text/Pandoc/CrossRef/References/Blocks.hs @@ -336,7 +336,8 @@ replaceAttr o label refLabel title pfx modify pfxCounter $ M.filterWithKey $ \k _ -> k `notElem` shouldReset modify pfxCounter $ M.insert pfx i let customLabel = prefixNumbering ropt - scop = join $ fmap (flip M.lookup cur) $ prefixScope ropt + -- TODO: should we prepend scoped refrences with references to the scope they're in? + -- scop = join $ fmap (flip M.lookup cur) $ prefixScope ropt index = chap ++ [(i, fromMaybe (customLabel i) refLabel)] label' = either (++ ':':show index) id label modify curChap $ M.insert pfx index diff --git a/lib/Text/Pandoc/CrossRef/Util/Meta.hs b/lib/Text/Pandoc/CrossRef/Util/Meta.hs index ae53dc3a..38d73e91 100644 --- a/lib/Text/Pandoc/CrossRef/Util/Meta.hs +++ b/lib/Text/Pandoc/CrossRef/Util/Meta.hs @@ -110,7 +110,7 @@ toMaybeString :: String -> MetaValue -> Maybe String toMaybeString _ (MetaString s) = Just s toMaybeString _ (MetaBlocks b) = Just $ stringify b toMaybeString _ (MetaInlines i) = Just $ stringify i -toMaybeString n x = Nothing +toMaybeString _ _ = Nothing getList :: Int -> MetaValue -> Maybe MetaValue getList i (MetaList l) = l !!? i diff --git a/lib/Text/Pandoc/CrossRef/Util/Prefixes.hs b/lib/Text/Pandoc/CrossRef/Util/Prefixes.hs index 87d10e00..2e96e435 100644 --- a/lib/Text/Pandoc/CrossRef/Util/Prefixes.hs +++ b/lib/Text/Pandoc/CrossRef/Util/Prefixes.hs @@ -18,10 +18,11 @@ with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -} -{-# LANGUAGE FlexibleInstances #-} +{-# LANGUAGE FlexibleInstances, GeneralizedNewtypeDeriving, MultiParamTypeClasses #-} module Text.Pandoc.CrossRef.Util.Prefixes where import Text.Pandoc.Definition +import Text.Pandoc.Walk (Walkable(..)) import Text.Pandoc.CrossRef.Util.Template import Text.Pandoc.CrossRef.Util.Settings.Types import Text.Pandoc.CrossRef.Util.Meta @@ -32,8 +33,14 @@ import Data.Default import Data.Monoid import Data.Maybe -instance Default Inlines where +newtype Inlines' = Inlines' { fromInlines' :: Inlines } deriving (Eq, Monoid) +instance Default Inlines' where def = mempty +instance Walkable Inline Inlines' where + walk f (Inlines' x) = Inlines' $ walk f x + walkM f (Inlines' x) = Inlines' <$> walkM f x + query f (Inlines' x) = query f x + getPrefixes :: String -> Settings -> Prefixes getPrefixes varN dtv @@ -42,7 +49,7 @@ getPrefixes varN dtv where var = displayMath m2p _ (MetaMap kv') = Prefix { - prefixRef = tryCapitalizeM (flip (getMetaList (toInlines "ref")) kv) "ref" + prefixRef = (fromInlines' .) . tryCapitalizeM (flip (getMetaList (Inlines' . toInlines "ref")) kv) "ref" , prefixCaptionTemplate = makeTemplate kv $ if isJust $ lookupSettings "captionTemplate" kv then getMetaInlines "captionTemplate" kv diff --git a/lib/Text/Pandoc/CrossRef/Util/Template.hs b/lib/Text/Pandoc/CrossRef/Util/Template.hs index bfd37281..e5d4f6dc 100644 --- a/lib/Text/Pandoc/CrossRef/Util/Template.hs +++ b/lib/Text/Pandoc/CrossRef/Util/Template.hs @@ -42,7 +42,7 @@ makeTemplate dtv xs' = Template $ \vf -> fromList $ scan (\var -> vf var <|> loo where scan :: (String -> Maybe MetaValue) -> [Inline] -> [Inline] scan = bottomUp . go - go vf (x@(Math DisplayMath var):xs) + go vf ((Math DisplayMath var):xs) | '[' `elem` var && ']' == last var = let (vn, idxBr) = span (/='[') var idxVar = drop 1 $ takeWhile (/=']') idxBr From c758ddeecf03ec317eb676e3d034c9b286b4af9e Mon Sep 17 00:00:00 2001 From: Nikolay Yakimov Date: Fri, 13 Apr 2018 21:37:29 +0300 Subject: [PATCH 029/134] Re-enable some cleveref settigns --- lib/Text/Pandoc/CrossRef/Util/ModifyMeta.hs | 16 +++++++++------- 1 file changed, 9 insertions(+), 7 deletions(-) diff --git a/lib/Text/Pandoc/CrossRef/Util/ModifyMeta.hs b/lib/Text/Pandoc/CrossRef/Util/ModifyMeta.hs index 4feaba0a..8b14e74f 100644 --- a/lib/Text/Pandoc/CrossRef/Util/ModifyMeta.hs +++ b/lib/Text/Pandoc/CrossRef/Util/ModifyMeta.hs @@ -27,6 +27,7 @@ import Data.List (intercalate) import Text.Pandoc import Text.Pandoc.Builder hiding ((<>)) import Text.Pandoc.CrossRef.Util.Options +import Text.Pandoc.CrossRef.Util.Prefixes import Text.Pandoc.CrossRef.Util.Settings.Types import Text.Pandoc.CrossRef.Util.Meta import Text.Pandoc.CrossRef.Util.Util @@ -91,11 +92,12 @@ modifyMeta opts meta ] | otherwise = ["\\newcommand*\\listoflistings{\\listof{codelisting}{"++metaString' "lolTitle"++"}}"] cleveref = [ usepackage cleverefOpts "cleveref" ] - -- <> crefname "figure" figPrefix - -- <> crefname "table" tblPrefix - -- <> crefname "equation" eqnPrefix - -- <> crefname "listing" lstPrefix - -- <> crefname "section" secPrefix + <> crefname "figure" (pfxRef "fig") + <> crefname "table" (pfxRef "tbl") + <> crefname "equation" (pfxRef "eq") + <> crefname "listing" (pfxRef "lst") + <> crefname "section" (pfxRef "sec") + pfxRef labelPrefix = prefixRef . flip getPfx labelPrefix cleverefCodelisting = [ "\\crefname{codelisting}{\\cref@listing@name}{\\cref@listing@name@plural}" , "\\Crefname{codelisting}{\\Cref@listing@name}{\\Cref@listing@name@plural}" @@ -112,5 +114,5 @@ modifyMeta opts meta toLatex = either (error . show) T.unpack . runPure . writeLaTeX def . Pandoc nullMeta . return . Plain metaString s = toLatex . toList $ getMetaInlines s meta metaString' s = toLatex [Str $ getMetaString s meta] - prefix f uc = "{" ++ toLatex (f opts uc 0) ++ "}" ++ - "{" ++ toLatex (f opts uc 1) ++ "}" + prefix f uc = "{" ++ toLatex (toList $ f opts uc 0) ++ "}" ++ + "{" ++ toLatex (toList $ f opts uc 1) ++ "}" From 0894f001d205e83ed3f4ea905e04f2777616c0e7 Mon Sep 17 00:00:00 2001 From: Nikolay Yakimov Date: Tue, 1 May 2018 23:18:25 +0300 Subject: [PATCH 030/134] GHC 8.4 support --- .travis.yml | 8 +++---- appveyor.yml | 4 ++-- lib/Text/Pandoc/CrossRef/Util/Prefixes.hs | 3 +-- lib/Text/Pandoc/CrossRef/Util/Settings.hs | 1 - .../Pandoc/CrossRef/Util/Settings/Types.hs | 1 - package.yaml | 6 ++--- pandoc-crossref.cabal | 24 +++++++++---------- src/pandoc-crossref.hs | 1 - stack.yaml | 2 +- test/m2m/equations-tables-auto/expect.md | 8 +++++++ test/m2m/equations-tables/expect.md | 4 ++++ 11 files changed, 34 insertions(+), 28 deletions(-) diff --git a/.travis.yml b/.travis.yml index e9dc1251..53e8442a 100644 --- a/.travis.yml +++ b/.travis.yml @@ -10,10 +10,10 @@ addons: matrix: include: - - env: STACK_YAML=stack.yaml RELEASE_FN=ghc82-pandoc21 - compiler: ": #GHC 8.2" - - env: STACK_YAML=stack.yaml RELEASE_FN=ghc82-pandoc21 - compiler: ": #GHC 8.2" + - env: STACK_YAML=stack.yaml RELEASE_FN=ghc84-pandoc22 + compiler: ": #GHC 8.4" + - env: STACK_YAML=stack.yaml RELEASE_FN=ghc84-pandoc22 + compiler: ": #GHC 8.4" os: osx before_install: diff --git a/appveyor.yml b/appveyor.yml index c2bfac4a..4c002e31 100644 --- a/appveyor.yml +++ b/appveyor.yml @@ -9,8 +9,8 @@ environment: STACK_ROOT: "c:\\sr" matrix: - STACK_YAML: "stack.yaml" - PANDOCVER: "21" - GHCVER: "82" + PANDOCVER: "22" + GHCVER: "84" before_build: - appveyor DownloadFile http://www.stackage.org/stack/windows-i386 -FileName stack.zip diff --git a/lib/Text/Pandoc/CrossRef/Util/Prefixes.hs b/lib/Text/Pandoc/CrossRef/Util/Prefixes.hs index 2e96e435..789d1e15 100644 --- a/lib/Text/Pandoc/CrossRef/Util/Prefixes.hs +++ b/lib/Text/Pandoc/CrossRef/Util/Prefixes.hs @@ -30,10 +30,9 @@ import Text.Pandoc.CrossRef.Util.CustomLabels import qualified Data.Map as M import Text.Pandoc.Builder hiding ((<>)) import Data.Default -import Data.Monoid import Data.Maybe -newtype Inlines' = Inlines' { fromInlines' :: Inlines } deriving (Eq, Monoid) +newtype Inlines' = Inlines' { fromInlines' :: Inlines } deriving (Eq, Semigroup, Monoid) instance Default Inlines' where def = mempty instance Walkable Inline Inlines' where diff --git a/lib/Text/Pandoc/CrossRef/Util/Settings.hs b/lib/Text/Pandoc/CrossRef/Util/Settings.hs index fc893ce3..d258614c 100644 --- a/lib/Text/Pandoc/CrossRef/Util/Settings.hs +++ b/lib/Text/Pandoc/CrossRef/Util/Settings.hs @@ -32,7 +32,6 @@ import Text.Pandoc.CrossRef.Util.PandocOrphans() import System.Directory import System.FilePath import System.IO -import Data.Monoid import qualified Data.Text as T import qualified Data.Map as M diff --git a/lib/Text/Pandoc/CrossRef/Util/Settings/Types.hs b/lib/Text/Pandoc/CrossRef/Util/Settings/Types.hs index b014e856..28d664ca 100644 --- a/lib/Text/Pandoc/CrossRef/Util/Settings/Types.hs +++ b/lib/Text/Pandoc/CrossRef/Util/Settings/Types.hs @@ -1,7 +1,6 @@ module Text.Pandoc.CrossRef.Util.Settings.Types where import Text.Pandoc.Definition -import Data.Semigroup import qualified Data.Map as M newtype Settings = Settings { unSettings :: Meta } deriving (Eq, Ord, Show) diff --git a/package.yaml b/package.yaml index eb25057e..eeef8ee6 100644 --- a/package.yaml +++ b/package.yaml @@ -1,5 +1,5 @@ name: pandoc-crossref -version: '0.3.1.0' +version: '0.4.0.0' synopsis: Pandoc filter for cross-references description: pandoc-crossref is a pandoc filter for numbering figures, equations, tables and cross-references to them. @@ -17,8 +17,8 @@ data-files: - docs/index.md - test/m2m/*/* dependencies: -- base >=4.9 && <5 -- pandoc >=2.1.3 && < 2.2 +- base >=4.11 && <5 +- pandoc >=2.2 && < 2.3 - pandoc-types ==1.17.* - mtl >=1.1 && <2.3 - containers >=0.1 && <0.6 diff --git a/pandoc-crossref.cabal b/pandoc-crossref.cabal index 84e824a2..64a0a0b6 100644 --- a/pandoc-crossref.cabal +++ b/pandoc-crossref.cabal @@ -1,11 +1,11 @@ --- This file has been generated from package.yaml by hpack version 0.21.2. +-- This file has been generated from package.yaml by hpack version 0.28.2. -- -- see: https://github.com/sol/hpack -- --- hash: 0aa60fb73626950d93c18ec1bb626dece6292c0d0f4a305bf777b0e1ba6e265b +-- hash: 5e96038910c3fa4d4908cf74bd8274363cc9dbff5712e21afefc716d3d2a5200 name: pandoc-crossref -version: 0.3.1.0 +version: 0.4.0.0 synopsis: Pandoc filter for cross-references description: pandoc-crossref is a pandoc filter for numbering figures, equations, tables and cross-references to them. category: Text @@ -17,12 +17,10 @@ license: GPL-2 license-file: LICENSE build-type: Simple cabal-version: >= 1.10 - extra-source-files: CHANGELOG.md test/demo-chapters.inc test/demo.inc - data-files: docs/demo/demo.md docs/index.md @@ -75,7 +73,7 @@ library lib ghc-options: -Wall build-depends: - base >=4.9 && <5 + base >=4.11 && <5 , containers >=0.1 && <0.6 , data-accessor >=0.2.2.6 && <0.3.0.0 , data-accessor-template >=0.2.1.12 && <0.3.0.0 @@ -85,7 +83,7 @@ library , extra >=1.6 && <1.7 , filepath >=1.1 && <1.5 , mtl >=1.1 && <2.3 - , pandoc >=2.1.3 && <2.2 + , pandoc >=2.2 && <2.3 , pandoc-types ==1.17.* , roman-numerals ==0.5.* , syb >=0.4 && <0.8 @@ -122,7 +120,7 @@ executable pandoc-crossref src ghc-options: -Wall -threaded build-depends: - base >=4.9 && <5 + base >=4.11 && <5 , containers >=0.1 && <0.6 , data-accessor >=0.2.2.6 && <0.3.0.0 , data-accessor-template >=0.2.1.12 && <0.3.0.0 @@ -135,7 +133,7 @@ executable pandoc-crossref , mtl >=1.1 && <2.3 , open-browser >=0.2 && <0.3 , optparse-applicative >=0.13 && <0.15 - , pandoc >=2.1.3 && <2.2 + , pandoc >=2.2 && <2.3 , pandoc-crossref , pandoc-types ==1.17.* , roman-numerals ==0.5.* @@ -156,7 +154,7 @@ test-suite test-integrative test ghc-options: -Wall -fno-warn-unused-do-bind -threaded build-depends: - base >=4.9 && <5 + base >=4.11 && <5 , containers >=0.1 && <0.6 , data-accessor >=0.2.2.6 && <0.3.0.0 , data-accessor-template >=0.2.1.12 && <0.3.0.0 @@ -167,7 +165,7 @@ test-suite test-integrative , filepath >=1.1 && <1.5 , hspec >=2.4.4 && <3 , mtl >=1.1 && <2.3 - , pandoc >=2.1.3 && <2.2 + , pandoc >=2.2 && <2.3 , pandoc-crossref , pandoc-types ==1.17.* , roman-numerals ==0.5.* @@ -185,7 +183,7 @@ test-suite test-pandoc-crossref lib ghc-options: -Wall -fno-warn-unused-do-bind -threaded build-depends: - base >=4.9 && <5 + base >=4.11 && <5 , containers >=0.1 && <0.6 , data-accessor >=0.2.2.6 && <0.3.0.0 , data-accessor-template >=0.2.1.12 && <0.3.0.0 @@ -196,7 +194,7 @@ test-suite test-pandoc-crossref , filepath >=1.1 && <1.5 , hspec >=2.4.4 && <3 , mtl >=1.1 && <2.3 - , pandoc >=2.1.3 && <2.2 + , pandoc >=2.2 && <2.3 , pandoc-types ==1.17.* , roman-numerals ==0.5.* , syb >=0.4 && <0.8 diff --git a/src/pandoc-crossref.hs b/src/pandoc-crossref.hs index 2d7c0b4e..5bee63e8 100644 --- a/src/pandoc-crossref.hs +++ b/src/pandoc-crossref.hs @@ -20,7 +20,6 @@ with this program; if not, write to the Free Software Foundation, Inc., {-# LANGUAGE ApplicativeDo, TemplateHaskell, CPP #-} import Text.Pandoc -import Text.Pandoc.Builder import Text.Pandoc.JSON import Text.Pandoc.CrossRef diff --git a/stack.yaml b/stack.yaml index 92e704c4..b17d0d28 100644 --- a/stack.yaml +++ b/stack.yaml @@ -3,4 +3,4 @@ packages: allow-newer: true extra-deps: - roman-numerals-0.5.1.5 -resolver: lts-11.3 +resolver: nightly-2018-05-01 diff --git a/test/m2m/equations-tables-auto/expect.md b/test/m2m/equations-tables-auto/expect.md index 62804276..2144a630 100644 --- a/test/m2m/equations-tables-auto/expect.md +++ b/test/m2m/equations-tables-auto/expect.md @@ -4,6 +4,7 @@ This is a test file with some referenced equations, line --------------------------------------------------------------- --------- $$ this $$ $$(1)$$ + --------------------------------------------------------------- --------- @@ -14,6 +15,7 @@ Some equations might be inside of text, --------------------------------------------------------------- --------- $$ for example $$ $$(2)$$ + --------------------------------------------------------------- --------- @@ -26,6 +28,7 @@ Some equations might be on start of paragraphs: --------------------------------------------------------------- --------- $$ start $$ $$(3)$$ + --------------------------------------------------------------- --------- @@ -38,6 +41,7 @@ Other might be on separate paragraphs of their own: --------------------------------------------------------------- --------- $$ separate $$ $$(4)$$ + --------------------------------------------------------------- --------- @@ -49,6 +53,7 @@ This is a test file with some referenced equations, line ::: {#eq:0} --------------------------------------------------------------- --------- $$ this $$ $$(5)$$ + --------------------------------------------------------------- --------- ::: @@ -57,6 +62,7 @@ Some equations might be inside of text, ::: {#eq:1} --------------------------------------------------------------- --------- $$ for example $$ $$(6)$$ + --------------------------------------------------------------- --------- ::: @@ -67,6 +73,7 @@ Some equations might be on start of paragraphs: ::: {#eq:2} --------------------------------------------------------------- --------- $$ start $$ $$(7)$$ + --------------------------------------------------------------- --------- ::: @@ -77,6 +84,7 @@ Other might be on separate paragraphs of their own: ::: {#eq:3} --------------------------------------------------------------- --------- $$ separate $$ $$(8)$$ + --------------------------------------------------------------- --------- ::: diff --git a/test/m2m/equations-tables/expect.md b/test/m2m/equations-tables/expect.md index d34e2316..16a779ec 100644 --- a/test/m2m/equations-tables/expect.md +++ b/test/m2m/equations-tables/expect.md @@ -17,6 +17,7 @@ This is a test file with some referenced equations, line ::: {#eq:0} --------------------------------------------------------------- --------- $$ this $$ $$(1)$$ + --------------------------------------------------------------- --------- ::: @@ -25,6 +26,7 @@ Some equations might be inside of text, ::: {#eq:1} --------------------------------------------------------------- --------- $$ for example $$ $$(2)$$ + --------------------------------------------------------------- --------- ::: @@ -35,6 +37,7 @@ Some equations might be on start of paragraphs: ::: {#eq:2} --------------------------------------------------------------- --------- $$ start $$ $$(3)$$ + --------------------------------------------------------------- --------- ::: @@ -45,6 +48,7 @@ Other might be on separate paragraphs of their own: ::: {#eq:3} --------------------------------------------------------------- --------- $$ separate $$ $$(4)$$ + --------------------------------------------------------------- --------- ::: From cd338a17030b2dad1d7e4ed4b3e678e3d927e8a9 Mon Sep 17 00:00:00 2001 From: Nikolay Yakimov Date: Wed, 2 May 2018 00:51:49 +0300 Subject: [PATCH 031/134] Add git commit info to version output --- package.yaml | 1 + pandoc-crossref.cabal | 3 ++- src/pandoc-crossref.hs | 3 +++ 3 files changed, 6 insertions(+), 1 deletion(-) diff --git a/package.yaml b/package.yaml index eeef8ee6..4cb566aa 100644 --- a/package.yaml +++ b/package.yaml @@ -52,6 +52,7 @@ executables: - open-browser >= 0.2 && < 0.3 - temporary >= 1.2 && < 1.3 - deepseq >= 1.4 && < 1.5 + - gitrev >= 1.3.1 && < 1.4 tests: test-pandoc-crossref: main: test-pandoc-crossref.hs diff --git a/pandoc-crossref.cabal b/pandoc-crossref.cabal index 64a0a0b6..519df23c 100644 --- a/pandoc-crossref.cabal +++ b/pandoc-crossref.cabal @@ -2,7 +2,7 @@ -- -- see: https://github.com/sol/hpack -- --- hash: 5e96038910c3fa4d4908cf74bd8274363cc9dbff5712e21afefc716d3d2a5200 +-- hash: 248ac326ef0ad394bc726d613423d794868c351a14d3b85ef11c6bbe9ac24d4e name: pandoc-crossref version: 0.4.0.0 @@ -130,6 +130,7 @@ executable pandoc-crossref , directory >=1 && <1.4 , extra >=1.6 && <1.7 , filepath >=1.1 && <1.5 + , gitrev >=1.3.1 && <1.4 , mtl >=1.1 && <2.3 , open-browser >=0.2 && <0.3 , optparse-applicative >=0.13 && <0.15 diff --git a/src/pandoc-crossref.hs b/src/pandoc-crossref.hs index 5bee63e8..80676c94 100644 --- a/src/pandoc-crossref.hs +++ b/src/pandoc-crossref.hs @@ -31,6 +31,7 @@ import System.IO.Temp import System.IO import ManData import Control.Concurrent +import Development.GitRev man, manHtml :: String man = $(embedManualText) @@ -50,6 +51,8 @@ run = do go :: Maybe Flag -> Maybe String -> IO () go (Just Version) _ = putStrLn $ "pandoc-crossref v" <> VERSION_pandoc_crossref + <> " git commit " <> $gitHash + <> " (" <> $gitBranch <> ")" <> " built with Pandoc v" <> VERSION_pandoc <> "," <> " pandoc-types v" <> VERSION_pandoc_types <> " and GHC " <> TOOL_VERSION_ghc From 0ae2769d3632026bb7da45d6e2664464b0e5a33a Mon Sep 17 00:00:00 2001 From: Nikolay Yakimov Date: Mon, 9 Jul 2018 08:11:59 +0300 Subject: [PATCH 032/134] Update failing LaTeX test --- test/test-pandoc-crossref.hs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/test-pandoc-crossref.hs b/test/test-pandoc-crossref.hs index 009e8115..c5fb11dc 100644 --- a/test/test-pandoc-crossref.hs +++ b/test/test-pandoc-crossref.hs @@ -352,7 +352,7 @@ main = hspec $ do it "Tbl labels" $ table' "A table" "some_table1" <> para (citeGen "tbl:some_table" [1]) - `test` "\\hypertarget{tbl:some_table1}{}\n\\begin{longtable}[]{@{}@{}}\n\\caption{\\label{tbl:some_table1}A table}\\tabularnewline\n\\toprule\n\\tabularnewline\n\\midrule\n\\endfirsthead\n\\toprule\n\\tabularnewline\n\\midrule\n\\endhead\n\\tabularnewline\n\\bottomrule\n\\end{longtable}\n\ntbl.~\\ref{tbl:some_table1}" + `test` "\\hypertarget{tbl:some_table1}{}\n\\begin{longtable}[]{@{}@{}}\n\\caption{\\label{tbl:some_table1}A table}\\tabularnewline\n\\toprule\n\\endhead\n\\tabularnewline\n\\bottomrule\n\\end{longtable}\n\ntbl.~\\ref{tbl:some_table1}" it "Code block labels" $ do codeBlock' "A code block" "some_codeblock1" From 8988f5742a4af7215c65c2a3260d00f6b5e6b986 Mon Sep 17 00:00:00 2001 From: Nikolay Yakimov Date: Mon, 9 Jul 2018 11:44:29 +0300 Subject: [PATCH 033/134] Update for pandoc-types v1.17.5.1 --- lib/Text/Pandoc/CrossRef/Util/Settings.hs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/lib/Text/Pandoc/CrossRef/Util/Settings.hs b/lib/Text/Pandoc/CrossRef/Util/Settings.hs index 0ff24832..c81b2a3e 100644 --- a/lib/Text/Pandoc/CrossRef/Util/Settings.hs +++ b/lib/Text/Pandoc/CrossRef/Util/Settings.hs @@ -61,12 +61,12 @@ defaultMeta :: Settings defaultMeta = Settings $ cref False <> chapters False - <> chaptersDepth (MetaString "1") + <> chaptersDepth "1" <> listings False <> codeBlockCaptions False <> autoSectionLabels False <> numberSections False - <> sectionsDepth (MetaString "0") + <> sectionsDepth "0" -- <> figLabels "arabic" -- <> eqnLabels "arabic" -- <> tblLabels "arabic" @@ -101,8 +101,8 @@ defaultMeta = Settings $ -- <> figureTemplate (var "figureTitle" <> space <> var "i" <> var "titleDelim" <> space <> var "t") -- <> tableTemplate (var "tableTitle" <> space <> var "i" <> var "titleDelim" <> space <> var "t") -- <> listingTemplate (var "listingTitle" <> space <> var "i" <> var "titleDelim" <> space <> var "t") - <> crossrefYaml (MetaString "pandoc-crossref.yaml") - <> chaptersDepth (MetaString "1") + <> crossrefYaml "pandoc-crossref.yaml" + <> chaptersDepth "1" -- <> subfigureChildTemplate (var "i") -- <> subfigureTemplate (var "figureTitle" <> space <> var "i" <> var "titleDelim" <> space <> var "t" <> str "." <> space <> var "ccs") -- <> subfigLabels "alpha a" From 508487f68f39fec7fe10dcc8d6b593c463e68684 Mon Sep 17 00:00:00 2001 From: Nikolay Yakimov Date: Sun, 25 Nov 2018 00:44:14 +0300 Subject: [PATCH 034/134] Fix broken TeX preamble settings; configurable TeX prefixes Closes #190 --- lib/Text/Pandoc/CrossRef/References/List.hs | 6 +---- .../Pandoc/CrossRef/Util/LatexPrefixes.hs | 26 +++++++++++++++++++ lib/Text/Pandoc/CrossRef/Util/ModifyMeta.hs | 20 +++++++------- lib/Text/Pandoc/CrossRef/Util/Options.hs | 5 ++++ lib/Text/Pandoc/CrossRef/Util/Prefixes.hs | 4 +++ lib/Text/Pandoc/CrossRef/Util/Settings.hs | 10 +++++++ .../Pandoc/CrossRef/Util/Settings/Template.hs | 3 +++ pandoc-crossref.cabal | 4 ++- 8 files changed, 62 insertions(+), 16 deletions(-) create mode 100644 lib/Text/Pandoc/CrossRef/Util/LatexPrefixes.hs diff --git a/lib/Text/Pandoc/CrossRef/References/List.hs b/lib/Text/Pandoc/CrossRef/References/List.hs index ce49402f..438b66c1 100644 --- a/lib/Text/Pandoc/CrossRef/References/List.hs +++ b/lib/Text/Pandoc/CrossRef/References/List.hs @@ -30,7 +30,6 @@ import qualified Data.Map as M import Text.Pandoc.CrossRef.References.Types import Text.Pandoc.CrossRef.Util.Util import Text.Pandoc.CrossRef.Util.Options -import Text.Pandoc.CrossRef.Util.Prefixes listOf :: Options -> [Block] -> WS [Block] listOf opts (RawBlock (Format "latex") cmd:xs) @@ -52,13 +51,10 @@ listOf _ x = return x getPfxData :: String -> WS RefMap getPfxData pfx = M.filterWithKey (\k _ -> (pfx <> ":") `isPrefixOf` k) <$> get referenceData -getLot :: Options -> String -> Blocks -getLot opts = prefixListOfTitle . getPfx opts - makeList :: Options -> String -> Blocks -> M.Map String RefRec -> WS Blocks makeList opts titlef xs refs = return $ - getLot opts titlef <> + getTitleForListOf opts titlef <> (if chaptersDepth opts > 0 then divWith ("", ["list"], []) (mconcat $ map itemChap refsSorted) else orderedList (map item refsSorted)) diff --git a/lib/Text/Pandoc/CrossRef/Util/LatexPrefixes.hs b/lib/Text/Pandoc/CrossRef/Util/LatexPrefixes.hs new file mode 100644 index 00000000..a9ebc33e --- /dev/null +++ b/lib/Text/Pandoc/CrossRef/Util/LatexPrefixes.hs @@ -0,0 +1,26 @@ +module Text.Pandoc.CrossRef.Util.LatexPrefixes where + +import Text.Pandoc.CrossRef.Util.Settings.Types +import Text.Pandoc.CrossRef.Util.Meta +import Text.Pandoc.Definition + +data LatexPrefixes = LatexPrefixes { + latexFigurePrefix :: !String + , latexTablePrefix :: !String + , latexEquationPrefix :: !String + , latexListingPrefix :: !String + , latexSectionPrefix :: !String + } + +getLatexPrefixes :: String -> Settings -> LatexPrefixes +getLatexPrefixes varN dtv + | Just (MetaMap kv') <- lookupSettings varN dtv = + let kv = Settings (Meta kv') + in LatexPrefixes { + latexFigurePrefix = getMetaString "figure" kv + , latexTablePrefix = getMetaString "table" kv + , latexEquationPrefix = getMetaString "equation" kv + , latexListingPrefix = getMetaString "listing" kv + , latexSectionPrefix = getMetaString "section" kv + } + | otherwise = error "Prefixes not defined" diff --git a/lib/Text/Pandoc/CrossRef/Util/ModifyMeta.hs b/lib/Text/Pandoc/CrossRef/Util/ModifyMeta.hs index 8b14e74f..bd74bed7 100644 --- a/lib/Text/Pandoc/CrossRef/Util/ModifyMeta.hs +++ b/lib/Text/Pandoc/CrossRef/Util/ModifyMeta.hs @@ -25,11 +25,11 @@ module Text.Pandoc.CrossRef.Util.ModifyMeta import Data.List (intercalate) import Text.Pandoc +import Text.Pandoc.Shared (blocksToInlines) import Text.Pandoc.Builder hiding ((<>)) import Text.Pandoc.CrossRef.Util.Options import Text.Pandoc.CrossRef.Util.Prefixes import Text.Pandoc.CrossRef.Util.Settings.Types -import Text.Pandoc.CrossRef.Util.Meta import Text.Pandoc.CrossRef.Util.Util import qualified Data.Text as T import Control.Monad.Writer @@ -67,30 +67,30 @@ modifyMeta opts meta ] floatnames = [ "\\AtBeginDocument{%" - , "\\renewcommand*\\figurename{"++metaString "figureTitle"++"}" - , "\\renewcommand*\\tablename{"++metaString "tableTitle"++"}" + , "\\renewcommand*\\figurename{"++getFloatCaption "fig"++"}" + , "\\renewcommand*\\tablename{"++getFloatCaption "tbl"++"}" , "}" ] listnames = [ "\\AtBeginDocument{%" - , "\\renewcommand*\\listfigurename{"++metaString' "lofTitle"++"}" - , "\\renewcommand*\\listtablename{"++metaString' "lotTitle"++"}" + , "\\renewcommand*\\listfigurename{"++getListOfTitle "fig"++"}" + , "\\renewcommand*\\listtablename{"++getListOfTitle "tbl"++"}" , "}" ] codelisting = [ usepackage [] "float" , "\\floatstyle{ruled}" , "\\@ifundefined{c@chapter}{\\newfloat{codelisting}{h}{lop}}{\\newfloat{codelisting}{h}{lop}[chapter]}" - , "\\floatname{codelisting}{"++metaString "listingTitle"++"}" + , "\\floatname{codelisting}{"++getListOfTitle "lst"++"}" ] lolcommand | listings opts = [ "\\newcommand*\\listoflistings\\lstlistoflistings" , "\\AtBeginDocument{%" - , "\\renewcommand*{\\lstlistlistingname}{"++metaString' "lolTitle"++"}" + , "\\renewcommand*{\\lstlistlistingname}{"++getListOfTitle "lst"++"}" , "}" ] - | otherwise = ["\\newcommand*\\listoflistings{\\listof{codelisting}{"++metaString' "lolTitle"++"}}"] + | otherwise = ["\\newcommand*\\listoflistings{\\listof{codelisting}{"++getListOfTitle "lst"++"}}"] cleveref = [ usepackage cleverefOpts "cleveref" ] <> crefname "figure" (pfxRef "fig") <> crefname "table" (pfxRef "tbl") @@ -112,7 +112,7 @@ modifyMeta opts meta usepackage xs p = "\\@ifpackageloaded{"++p++"}{}{\\usepackage"++o++"{"++p++"}}" where o = "[" ++ intercalate "," xs ++ "]" toLatex = either (error . show) T.unpack . runPure . writeLaTeX def . Pandoc nullMeta . return . Plain - metaString s = toLatex . toList $ getMetaInlines s meta - metaString' s = toLatex [Str $ getMetaString s meta] + getListOfTitle = toLatex . blocksToInlines . toList . getTitleForListOf opts + getFloatCaption = toLatex . toList . prefixTitle . getPfx opts prefix f uc = "{" ++ toLatex (toList $ f opts uc 0) ++ "}" ++ "{" ++ toLatex (toList $ f opts uc 1) ++ "}" diff --git a/lib/Text/Pandoc/CrossRef/Util/Options.hs b/lib/Text/Pandoc/CrossRef/Util/Options.hs index 47b00a77..4ef3bbf0 100644 --- a/lib/Text/Pandoc/CrossRef/Util/Options.hs +++ b/lib/Text/Pandoc/CrossRef/Util/Options.hs @@ -27,6 +27,7 @@ import Text.Pandoc.Builder import Data.Maybe import Data.List import Data.List.Extra +import Text.Pandoc.CrossRef.Util.LatexPrefixes data Options = Options { cref :: Bool , chaptersDepth :: Int @@ -53,6 +54,7 @@ data Options = Options { cref :: Bool , linkReferences :: Bool , nameInLink :: Bool , prefixes :: Prefixes + , latexPrefixes :: LatexPrefixes } prefixList :: Options -> [String] @@ -84,3 +86,6 @@ getRefLabel opts ils , Just _ <- getRefPrefix opts lbl = Just lbl getRefLabel _ _ = Nothing + +getTitleForListOf :: Options -> String -> Blocks +getTitleForListOf opts = prefixListOfTitle . getPfx opts diff --git a/lib/Text/Pandoc/CrossRef/Util/Prefixes.hs b/lib/Text/Pandoc/CrossRef/Util/Prefixes.hs index 789d1e15..c80c943b 100644 --- a/lib/Text/Pandoc/CrossRef/Util/Prefixes.hs +++ b/lib/Text/Pandoc/CrossRef/Util/Prefixes.hs @@ -60,6 +60,7 @@ getPrefixes varN dtv , prefixScope = getMetaStringMaybe "scope" kv , prefixNumbering = mkLabel (varN <> "." <> "numbering") (fromMaybe (MetaString "arabic") $ lookupSettings "numbering" kv) , prefixListOfTitle = getMetaBlock "listOfTitle" kv + , prefixTitle = getMetaInlines "title" kv } where kv = Settings (Meta kv') <> dtv m2p k _ = error $ "Invalid value for prefix " <> k @@ -73,4 +74,7 @@ data Prefix = Prefix { , prefixScope :: !(Maybe String) , prefixNumbering :: !(Int -> String) , prefixListOfTitle :: !Blocks + -- Used for LaTeX metadata; the same value is used in + -- default value for prefixCaptionTemplate + , prefixTitle :: Inlines } diff --git a/lib/Text/Pandoc/CrossRef/Util/Settings.hs b/lib/Text/Pandoc/CrossRef/Util/Settings.hs index c81b2a3e..b080e2fe 100644 --- a/lib/Text/Pandoc/CrossRef/Util/Settings.hs +++ b/lib/Text/Pandoc/CrossRef/Util/Settings.hs @@ -114,6 +114,13 @@ defaultMeta = Settings $ <> subfigGrid False <> linkReferences False <> nameInLink False + <> latexPrefixes' [ + "figure" .= "fig" + , "table" .= "tbl" + , "equation" .= "eq" + , "listing" .= "lst" + , "section" .= "sec" + ] <> prefixes' [ "eq" .: [ "ref" .= ["eq.", "eqns."], @@ -150,6 +157,9 @@ defaultMeta = Settings $ prefixes' :: [(String, MetaValue)] -> Meta prefixes' = prefixes . MetaMap . M.fromList +latexPrefixes' :: [(String, MetaValue)] -> Meta +latexPrefixes' = latexPrefixes . MetaMap . M.fromList + infixr 0 .: (.:) :: String -> [(String, MetaValue)] -> (String, MetaValue) key .: val = (key, MetaMap $ M.fromList val) diff --git a/lib/Text/Pandoc/CrossRef/Util/Settings/Template.hs b/lib/Text/Pandoc/CrossRef/Util/Settings/Template.hs index 98e1bdda..15e14d8e 100644 --- a/lib/Text/Pandoc/CrossRef/Util/Settings/Template.hs +++ b/lib/Text/Pandoc/CrossRef/Util/Settings/Template.hs @@ -30,6 +30,7 @@ import Language.Haskell.TH.Syntax hiding (Inline) import Data.List import Text.Pandoc.CrossRef.Util.Template import Text.Pandoc.CrossRef.Util.Prefixes +import Text.Pandoc.CrossRef.Util.LatexPrefixes namedFields :: Con -> [VarStrictType] namedFields (RecC _ fs) = fs @@ -79,6 +80,7 @@ makeCon' t accName = do tmplT <- [t|$(conT t) -> Template|] clT <- [t|$(conT t) -> String -> Int -> Maybe String|] pfxT <- [t|$(conT t) -> Prefixes|] + lpsT <- [t|$(conT t) -> LatexPrefixes|] let varName | Name (OccName n) _ <- accName = liftString n let dtv = return $ VarE $ mkName "dtv" body <- @@ -92,5 +94,6 @@ makeCon' t accName = do | t' == clT -> [|customLabel $(dtv)|] | t' == fmtT -> return $ VarE $ mkName "fmt" | t' == pfxT -> [|getPrefixes $(varName) $(dtv)|] + | t' == lpsT -> [|getLatexPrefixes $(varName) $(dtv)|] | otherwise -> fail $ show t' return [(accName, body)] diff --git a/pandoc-crossref.cabal b/pandoc-crossref.cabal index c26ad24e..c7db5c20 100644 --- a/pandoc-crossref.cabal +++ b/pandoc-crossref.cabal @@ -4,7 +4,7 @@ cabal-version: 1.12 -- -- see: https://github.com/sol/hpack -- --- hash: 0ffe32c9178cfad80e92cf943e5bd35ba72f555de20840af5863dfdc0c25390b +-- hash: fb0025890a7dc67a63203364ebb9f5a88c9aea1b4631dd035bbb64b98704afb6 name: pandoc-crossref version: 0.4.0.0 @@ -85,6 +85,7 @@ library Text.Pandoc.CrossRef.References.Types Text.Pandoc.CrossRef.Util.CodeBlockCaptions Text.Pandoc.CrossRef.Util.CustomLabels + Text.Pandoc.CrossRef.Util.LatexPrefixes Text.Pandoc.CrossRef.Util.Meta Text.Pandoc.CrossRef.Util.ModifyMeta Text.Pandoc.CrossRef.Util.Options @@ -196,6 +197,7 @@ test-suite test-pandoc-crossref Text.Pandoc.CrossRef.References.Types Text.Pandoc.CrossRef.Util.CodeBlockCaptions Text.Pandoc.CrossRef.Util.CustomLabels + Text.Pandoc.CrossRef.Util.LatexPrefixes Text.Pandoc.CrossRef.Util.Meta Text.Pandoc.CrossRef.Util.ModifyMeta Text.Pandoc.CrossRef.Util.Options From 2483e350a5af1216d754dd891590c61d3efb652a Mon Sep 17 00:00:00 2001 From: Nikolay Yakimov Date: Thu, 10 Jan 2019 04:26:52 +0300 Subject: [PATCH 035/134] Fix #211 --- lib/Text/Pandoc/CrossRef/Util/ModifyMeta.hs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/Text/Pandoc/CrossRef/Util/ModifyMeta.hs b/lib/Text/Pandoc/CrossRef/Util/ModifyMeta.hs index bd74bed7..d30ec29c 100644 --- a/lib/Text/Pandoc/CrossRef/Util/ModifyMeta.hs +++ b/lib/Text/Pandoc/CrossRef/Util/ModifyMeta.hs @@ -81,7 +81,7 @@ modifyMeta opts meta usepackage [] "float" , "\\floatstyle{ruled}" , "\\@ifundefined{c@chapter}{\\newfloat{codelisting}{h}{lop}}{\\newfloat{codelisting}{h}{lop}[chapter]}" - , "\\floatname{codelisting}{"++getListOfTitle "lst"++"}" + , "\\floatname{codelisting}{"++getFloatCaption "lst"++"}" ] lolcommand | listings opts = [ From cb12fdf14f6f0ba9a978ced636ee20e1cb8839b9 Mon Sep 17 00:00:00 2001 From: Nikolay Yakimov Date: Fri, 15 Feb 2019 16:07:27 +0300 Subject: [PATCH 036/134] Test and fix for #219 --- lib/Text/Pandoc/CrossRef/References/Refs.hs | 2 +- pandoc-crossref.cabal | 5 ++++- test/m2m/regresssion-219/expect.md | 2 ++ test/m2m/regresssion-219/expect.tex | 2 ++ test/m2m/regresssion-219/input.md | 2 ++ 5 files changed, 11 insertions(+), 2 deletions(-) create mode 100644 test/m2m/regresssion-219/expect.md create mode 100644 test/m2m/regresssion-219/expect.tex create mode 100644 test/m2m/regresssion-219/input.md diff --git a/lib/Text/Pandoc/CrossRef/References/Refs.hs b/lib/Text/Pandoc/CrossRef/References/Refs.hs index da010e5d..e3a1092e 100644 --- a/lib/Text/Pandoc/CrossRef/References/Refs.hs +++ b/lib/Text/Pandoc/CrossRef/References/Refs.hs @@ -75,7 +75,7 @@ allCitsPrefix :: Options -> [Citation] -> Maybe String allCitsPrefix opts cits = find isCitationPrefix $ prefixList opts where isCitationPrefix p = - all (p `isPrefixOf`) $ map (uncapitalizeFirst . citationId) cits + all (p ==) $ map (takeWhile (/=':') . uncapitalizeFirst . citationId) cits replaceRefsLatex :: String -> Options -> [Citation] -> WS Inlines replaceRefsLatex prefix opts cits diff --git a/pandoc-crossref.cabal b/pandoc-crossref.cabal index 01398b52..952add9d 100644 --- a/pandoc-crossref.cabal +++ b/pandoc-crossref.cabal @@ -4,7 +4,7 @@ cabal-version: 1.12 -- -- see: https://github.com/sol/hpack -- --- hash: 7e8ea8006377ab15599e5d75415f742a04fb38a7e792859fd80eabb3c4b043cf +-- hash: b019c9e3e9e85522e4f62ec3b1985acbc6773ca9d58bc8568ecc2f4c2eb93e9e name: pandoc-crossref version: 0.4.0.0 @@ -52,6 +52,9 @@ data-files: test/m2m/listing-captions-ids/expect.md test/m2m/listing-captions-ids/expect.tex test/m2m/listing-captions-ids/input.md + test/m2m/regresssion-219/expect.md + test/m2m/regresssion-219/expect.tex + test/m2m/regresssion-219/input.md test/m2m/section-template/expect.md test/m2m/section-template/expect.tex test/m2m/section-template/input.md diff --git a/test/m2m/regresssion-219/expect.md b/test/m2m/regresssion-219/expect.md new file mode 100644 index 00000000..cef12d79 --- /dev/null +++ b/test/m2m/regresssion-219/expect.md @@ -0,0 +1,2 @@ +A citation starting with "fig", like @Figueroa2012-tu should not be +interpreted as a reference. diff --git a/test/m2m/regresssion-219/expect.tex b/test/m2m/regresssion-219/expect.tex new file mode 100644 index 00000000..dba69aae --- /dev/null +++ b/test/m2m/regresssion-219/expect.tex @@ -0,0 +1,2 @@ +A citation starting with ``fig'', like {[}@Figueroa2012-tu{]} should not +be interpreted as a reference. diff --git a/test/m2m/regresssion-219/input.md b/test/m2m/regresssion-219/input.md new file mode 100644 index 00000000..cef12d79 --- /dev/null +++ b/test/m2m/regresssion-219/input.md @@ -0,0 +1,2 @@ +A citation starting with "fig", like @Figueroa2012-tu should not be +interpreted as a reference. From 82473ca2e4d39dbd5b3db4eb56fd605518bdaba4 Mon Sep 17 00:00:00 2001 From: Nikolay Yakimov Date: Sat, 2 Mar 2019 03:20:57 +0300 Subject: [PATCH 037/134] Some groundwork for scoping; lot of stuff broken (see below) - tests are mostly broken - subfigures are broken - chapters are broken Notable changes: - Unrecognized references are converted to citations - Chapters should be possible via scoping rules, but it's not as easy as it should be - Subfigures should be possible via scoping rules to a limited extent, but there's a lot more to do for it to be feasible. --- lib/Text/Pandoc/CrossRef/References/Blocks.hs | 371 ++++++------------ lib/Text/Pandoc/CrossRef/References/List.hs | 11 +- lib/Text/Pandoc/CrossRef/References/Refs.hs | 220 ++++++----- .../Pandoc/CrossRef/References/Subfigures.hs | 143 +++++++ lib/Text/Pandoc/CrossRef/References/Types.hs | 30 +- lib/Text/Pandoc/CrossRef/Util/Meta.hs | 26 +- lib/Text/Pandoc/CrossRef/Util/ModifyMeta.hs | 24 +- lib/Text/Pandoc/CrossRef/Util/Options.hs | 14 +- lib/Text/Pandoc/CrossRef/Util/Prefixes.hs | 24 +- lib/Text/Pandoc/CrossRef/Util/Settings.hs | 42 +- lib/Text/Pandoc/CrossRef/Util/Settings/Gen.hs | 22 +- lib/Text/Pandoc/CrossRef/Util/Template.hs | 76 ++-- lib/Text/Pandoc/CrossRef/Util/Util.hs | 67 ++-- 13 files changed, 565 insertions(+), 505 deletions(-) create mode 100644 lib/Text/Pandoc/CrossRef/References/Subfigures.hs diff --git a/lib/Text/Pandoc/CrossRef/References/Blocks.hs b/lib/Text/Pandoc/CrossRef/References/Blocks.hs index 68849aa7..2714bb29 100644 --- a/lib/Text/Pandoc/CrossRef/References/Blocks.hs +++ b/lib/Text/Pandoc/CrossRef/References/Blocks.hs @@ -18,14 +18,14 @@ with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -} -{-# LANGUAGE Rank2Types, MultiWayIf #-} +{-# LANGUAGE Rank2Types, MultiWayIf, RecordWildCards #-} module Text.Pandoc.CrossRef.References.Blocks ( replaceAll ) where import Text.Pandoc.Definition import qualified Text.Pandoc.Builder as B -import Text.Pandoc.Shared (stringify) +import Text.Pandoc.Shared (stringify, hierarchicalize, Element(..)) import Control.Monad.State hiding (get, modify) import Data.List import Data.Maybe @@ -33,7 +33,7 @@ import Data.Monoid import qualified Data.Map as M import Data.Accessor.Monad.Trans.State -import Text.Pandoc.CrossRef.References.Types +import Text.Pandoc.CrossRef.References.Types as Types import Text.Pandoc.CrossRef.Util.Util import Text.Pandoc.CrossRef.Util.Options import Text.Pandoc.CrossRef.Util.Prefixes @@ -43,9 +43,11 @@ import Control.Applicative import Data.Default (def) import Prelude -replaceAll :: (Data a) => Options -> a -> WS a +replaceAll :: Options -> [Block] -> WS [Block] replaceAll opts = - runReplace (mkRR (replaceBlock opts) `extRR` replaceInline opts) + fmap unhierarchicalize + . runReplace [] (mkRR (replaceElement opts) `extRR` replaceBlock opts `extRR` replaceInline opts) + . hierarchicalize . runSplitMath . everywhere (mkT (divBlocks opts) `extT` spanInlines opts) . everywhere (mkT (mkCodeBlockCaptions opts)) @@ -55,238 +57,143 @@ replaceAll opts = = everywhere (mkT splitMath) | otherwise = id -getCurPfx :: String -> WS (Maybe Index) -getCurPfx pfx = M.lookup pfx <$> get curChap +replaceElement :: Options -> Scope -> Element -> WS (ReplacedResult Element) +replaceElement opts scope (Sec n ns (label, cls, attrs) text' body) = do + let label' = if autoSectionLabels opts && isNothing pfx + then "sec:"++label + else label + pfx = getRefPrefix opts label + if "unnumbered" `elem` cls + then replaceRecurse scope $ Sec n ns (label', cls, attrs) text' body + else do + let pfx' = getRefPrefix opts label' + ititle = B.fromList text' + defaultSecPfx = "sec" + rec' <- case pfx' of + Just p -> replaceAttr opts scope (Right label) (lookup "label" attrs) ititle p + Nothing -> replaceAttr opts scope (Left defaultSecPfx) (lookup "label" attrs) ititle defaultSecPfx + let title' = B.toList $ + case outFormat opts of + f | isLatexFormat f -> B.rawInline "latex" (mkLaTeXLabel label) <> ititle + _ -> applyTitleTemplate opts rec' + replaceRecurse (newScope rec' scope) $ Sec n ns (label', cls, attrs) title' body +replaceElement _ scope _ = noReplaceRecurse scope -replaceBlock :: Options -> Block -> WS (ReplacedResult Block) -replaceBlock opts (Header n (label, cls, attrs) text') - = do - let label' = if autoSectionLabels opts && not ("sec:" `isPrefixOf` label) - then "sec:"++label - else label - if "unnumbered" `elem` cls - then replaceNoRecurse $ Header n (label', cls, attrs) text' - else do - cur <- getCurPfx "sec" - let cc = fromMaybe [] cur - cl = lookup "label" attrs - inc l = let incd = fst (last l) + 1 - in init l ++ [(incd, fromMaybe (show incd) cl)] - cc' - | length cc >= n = inc $ take n cc - | otherwise = take (n-1) (cc ++ repeat (1, "1")) ++ [(1, fromMaybe "1" cl)] - modify curChap $ M.insert "sec" cc' - when (n <= chaptersDepth opts) $ do - modify pfxCounter $ M.singleton "sec" . fromMaybe 0 . M.lookup "sec" - when ("sec:" `isPrefixOf` label') $ do - modify referenceData $ M.insert label' RefRec { - refIndex = cc' - , refTitle = B.fromList text' - , refSubfigure = Nothing - } - let textCC | numberSections opts - , sectionsDepth opts < 0 - || n <= if sectionsDepth opts == 0 then chaptersDepth opts else sectionsDepth opts - = applyTemplate' (M.fromDistinctAscList [ - ("i", B.text (intercalate "." $ map snd cc')) - , ("n", B.text $ show $ n - 1) - , ("t", B.fromList text') - ]) $ secHeaderTemplate opts - | otherwise = B.fromList text' - replaceNoRecurse $ Header n (label', cls, attrs) $ B.toList textCC --- sub-objects -replaceBlock opts (Div (label,cls,attrs) images) - | Just pfx <- getRefPrefix opts label - , Para caption <- last images - = do - idxStr <- replaceAttr opts (Right label) (lookup "label" attrs) (B.fromList caption) pfx - let (cont, st) = runState (runReplace (mkRR $ replaceSubfigs opts') $ init images) def - collectedCaptions = B.toList $ - intercalate' (ccsDelim opts) - $ map (collectCaps . snd) - $ sortOn (refIndex . snd) - $ filter (not . null . refTitle . snd) - $ M.toList - $ referenceData_ st - collectCaps v = - applyTemplate - (chapPrefix (chapDelim opts) (refIndex v)) - (refTitle v) - (ccsTemplate opts) - vars = M.fromDistinctAscList - [ ("ccs", B.fromList collectedCaptions) - , ("i", idxStr) - , ("t", B.fromList caption) - ] - capt = applyTemplate' vars $ pfxCaptionTemplate opts pfx - opts' = opts { - prefixes = case M.lookup ("sub" <> pfx) $ prefixes opts of - Just sp -> M.insert pfx sp $ prefixes opts - Nothing -> prefixes opts - } - lastRef <- fromJust . M.lookup label <$> get referenceData - modify referenceData $ \old -> - M.union - old - (M.map (\v -> v{refIndex = refIndex lastRef, refSubfigure = Just $ refIndex v}) - $ referenceData_ st) - case outFormat opts of - f | isLatexFormat f, pfx == "fig" -> - replaceNoRecurse $ Div nullAttr $ - [ RawBlock (Format "latex") "\\begin{figure}\n\\centering" ] - ++ cont ++ - [ Para [RawInline (Format "latex") "\\caption" - , Span nullAttr caption] - , RawBlock (Format "latex") $ mkLaTeXLabel label - , RawBlock (Format "latex") "\\end{figure}"] - _ -> replaceNoRecurse $ Div (label, "subfigures":cls, attrs) $ toTable cont capt - where - toTable :: [Block] -> B.Inlines -> [Block] - toTable blks capt - | subfigGrid opts = [Table [] align widths [] $ map blkToRow blks, mkCaption opts "Image Caption" capt] - | otherwise = blks ++ [mkCaption opts "Image Caption" capt] - where - align | Para ils:_ <- blks = replicate (length $ mapMaybe getWidth ils) AlignCenter - | otherwise = error "Misformatted subfigures block" - widths | Para ils:_ <- blks - = fixZeros $ mapMaybe getWidth ils - | otherwise = error "Misformatted subfigures block" - getWidth (Image (_id, _class, as) _ _) - = Just $ maybe 0 percToDouble $ lookup "width" as - getWidth _ = Nothing - fixZeros :: [Double] -> [Double] - fixZeros ws - = let nz = length $ filter (== 0) ws - rzw = (0.99 - sum ws) / fromIntegral nz - in if nz>0 - then map (\x -> if x == 0 then rzw else x) ws - else ws - percToDouble :: String -> Double - percToDouble percs - | '%' <- last percs - , perc <- read $ init percs - = perc/100.0 - | otherwise = error "Only percent allowed in subfigure width!" - blkToRow :: Block -> [[Block]] - blkToRow (Para inls) = mapMaybe inlToCell inls - blkToRow x = [[x]] - inlToCell :: Inline -> Maybe [Block] - inlToCell (Image (id', cs, as) txt tgt) = Just [Para [Image (id', cs, setW as) txt tgt]] - inlToCell _ = Nothing - setW as = ("width", "100%"):filter ((/="width") . fst) as -replaceBlock opts (Div divOps@(label,_,attrs) [Table title align widths header cells]) +replaceBlock :: Options -> Scope -> Block -> WS (ReplacedResult Block) +replaceBlock opts scope (Div divOps@(label,_,attrs) [Table title align widths header cells]) | not $ null title , Just pfx <- getRefPrefix opts label = do let ititle = B.fromList title - idxStr <- replaceAttr opts (Right label) (lookup "label" attrs) ititle pfx + idxStr <- replaceAttr opts scope (Right label) (lookup "label" attrs) ititle pfx let title' = B.toList $ case outFormat opts of - f | isLatexFormat f -> - B.rawInline "latex" (mkLaTeXLabel label) <> ititle - _ -> applyTemplate idxStr ititle $ pfxCaptionTemplate opts pfx + f | isLatexFormat f -> B.rawInline "latex" (mkLaTeXLabel label) <> ititle + _ -> applyTitleTemplate opts idxStr replaceNoRecurse $ Div divOps [Table title' align widths header cells] -replaceBlock opts - (Div (label,"listing":_, []) - [Para caption, CodeBlock ([],classes,attrs) code]) +replaceBlock opts scope (Div (label,"listing":_, []) [Para caption, CodeBlock ([],classes,attrs) code]) | not $ null label , Just pfx <- getRefPrefix opts label - = case outFormat opts of - f - --if used with listings package, return code block with caption - | isLatexFormat f, listings opts -> - replaceNoRecurse $ CodeBlock (label,classes,("caption",stringify caption):attrs) code - --if not using listings, however, wrap it in a codelisting environment - | isLatexFormat f -> - replaceNoRecurse $ Div nullAttr [ - RawBlock (Format "latex") "\\begin{codelisting}" - , Para [ - RawInline (Format "latex") "\\caption" - , Span nullAttr caption + = do + let icaption = B.fromList caption + idxStr <- replaceAttr opts scope (Right label) (lookup "label" attrs) icaption pfx + let caption' = applyTitleTemplate opts idxStr + replaceNoRecurse $ case outFormat opts of + f --if used with listings package, return code block with caption + | isLatexFormat f, listings opts -> + CodeBlock (label,classes,("caption",stringify caption):attrs) code + --if not using listings, however, wrap it in a codelisting environment + | isLatexFormat f -> + Div nullAttr [ + RawBlock (Format "latex") "\\begin{codelisting}" + , Para [ + RawInline (Format "latex") "\\caption" + , Span nullAttr caption + ] + , CodeBlock (label,classes,attrs) code + , RawBlock (Format "latex") "\\end{codelisting}" ] - , CodeBlock (label,classes,attrs) code - , RawBlock (Format "latex") "\\end{codelisting}" - ] - _ -> do - let icaption = B.fromList caption - idxStr <- replaceAttr opts (Right label) (lookup "label" attrs) icaption pfx - let caption' = applyTemplate idxStr icaption $ pfxCaptionTemplate opts pfx - replaceNoRecurse $ Div (label, "listing":classes, []) [ + _ -> Div (label, "listing":classes, []) [ mkCaption opts "Caption" caption' , CodeBlock ([], classes, attrs) code ] -replaceBlock opts (Para [Span attrs@(label, _, _) [Math DisplayMath eq]]) +replaceBlock opts scope (Para [Span attrs@(label, _, _) [Math DisplayMath eq]]) | not $ isLatexFormat (outFormat opts) , tableEqns opts , pfx <- getRefPrefix opts label = do - (eq', idx) <- replaceEqn opts attrs eq pfx + (eq', idx) <- replaceEqn opts scope attrs eq pfx replaceNoRecurse $ Div attrs [Table [] [AlignCenter, AlignRight] [0.9, 0.09] [] [[[Plain [Math DisplayMath eq']], [Plain [Math DisplayMath $ "(" ++ idx ++ ")"]]]]] -replaceBlock opts x@(Div (label, _, attrs) _content) +replaceBlock opts scope x@(Div (label, _, attrs) _content) | Just pfx <- getRefPrefix opts label = do - void $ replaceAttr opts (Right label) (lookup "label" attrs) mempty pfx - replaceRecurse x -replaceBlock _ _ = noReplaceRecurse + rec' <- replaceAttr opts scope (Right label) (lookup "label" attrs) mempty pfx + replaceRecurse (newScope rec' scope) x +replaceBlock _ scope _ = noReplaceRecurse scope -replaceEqn :: Options -> Attr -> String -> Maybe String -> WS (String, String) -replaceEqn opts (label, _, attrs) eq pfx = do +replaceEqn :: Options -> Scope -> Attr -> String -> Maybe String -> WS (String, String) +replaceEqn opts scope (label, _, attrs) eq pfx = do let label' | null label = Left "eq" | otherwise = Right label - idxStr <- replaceAttr opts label' (lookup "label" attrs) mempty (fromMaybe "eq" pfx) + idxStr <- replaceAttr opts scope label' (lookup "label" attrs) mempty (fromMaybe "eq" pfx) let eq' | tableEqns opts = eq - | otherwise = eq++"\\qquad("++stringify idxStr++")" - return (eq', stringify idxStr) + | otherwise = eq++"\\qquad("++stringify (refIxInl idxStr)++")" + return (eq', stringify (refIxInl idxStr)) -replaceInline :: Options -> Inline -> WS (ReplacedResult Inline) -replaceInline opts (Span attrs@(label,_,_) [Math DisplayMath eq]) +replaceInline :: Options -> Scope -> Inline -> WS (ReplacedResult Inline) +replaceInline opts scope (Span attrs@(label,_,_) [Math DisplayMath eq]) | pfx <- getRefPrefix opts label , isJust pfx || null label && autoEqnLabels opts - = case outFormat opts of - f | isLatexFormat f -> - let eqn = "\\begin{equation}"++eq++mkLaTeXLabel label++"\\end{equation}" - in replaceNoRecurse $ RawInline (Format "latex") eqn - _ -> do - (eq', _) <- replaceEqn opts attrs eq pfx - replaceNoRecurse $ Span attrs [Math DisplayMath eq'] -replaceInline opts (Image attr@(label,_,attrs) alt img@(_, tit)) + = do + (eq', _) <- replaceEqn opts scope attrs eq pfx + replaceNoRecurse $ case outFormat opts of + f | isLatexFormat f -> + let eqn = "\\begin{equation}"++eq++mkLaTeXLabel label++"\\end{equation}" + in RawInline (Format "latex") eqn + _ -> Span attrs [Math DisplayMath eq'] +replaceInline opts scope (Image attr@(label,_,attrs) alt img@(_, tit)) | Just pfx <- getRefPrefix opts label , "fig:" `isPrefixOf` tit = do let ialt = B.fromList alt - idxStr <- replaceAttr opts (Right label) (lookup "label" attrs) ialt pfx + idxStr <- replaceAttr opts scope (Right label) (lookup "label" attrs) ialt pfx let alt' = B.toList $ case outFormat opts of f | isLatexFormat f -> ialt - _ -> applyTemplate idxStr ialt $ pfxCaptionTemplate opts pfx + _ -> applyTitleTemplate opts idxStr replaceNoRecurse $ Image attr alt' img -replaceInline opts x@(Span (label,_,attrs) _content) +replaceInline opts scope x@(Span (label,_,attrs) _content) | Just pfx <- getRefPrefix opts label = do - void $ replaceAttr opts (Right label) (lookup "label" attrs) mempty pfx - replaceRecurse x -replaceInline _ _ = noReplaceRecurse + rec' <- replaceAttr opts scope (Right label) (lookup "label" attrs) mempty pfx + replaceRecurse (newScope rec' scope) x +replaceInline _ scope _ = noReplaceRecurse scope -replaceSubfigs :: Options -> [Inline] -> WS (ReplacedResult [Inline]) -replaceSubfigs opts = (replaceNoRecurse . concat =<<) . mapM (replaceSubfig opts) +applyTitleTemplate :: Options -> RefRec -> B.Inlines +applyTitleTemplate opts rr@RefRec{..} = + applyTemplate vf $ pfxCaptionTemplate opts refPfx + where + vf x = case x of + "i" -> Just refIxInl + _ -> titleVarFunc opts rr x -replaceSubfig :: Options -> Inline -> WS [Inline] -replaceSubfig opts x@(Image (label,cls,attrs) alt (src, tit)) - = do - let label' | "fig:" `isPrefixOf` label = Right label - | null label = Left "fig" - | otherwise = Right $ "fig:" ++ label - let ialt = B.fromList alt - idxStr <- replaceAttr opts label' (lookup "label" attrs) ialt "fig" - case outFormat opts of - f | isLatexFormat f -> - return $ latexSubFigure x label - _ -> - let alt' = B.toList $ applyTemplate idxStr ialt $ pfxCaptionTemplate opts "fig" - tit' | "nocaption" `elem` cls = fromMaybe tit $ stripPrefix "fig:" tit - | "fig:" `isPrefixOf` tit = tit - | otherwise = "fig:" ++ tit - in return [Image (label, cls, attrs) alt' (src, tit')] -replaceSubfig _ x = return [x] +applyTitleIndexTemplate :: Options -> RefRec -> B.Inlines -> B.Inlines +applyTitleIndexTemplate opts rr@RefRec{..} label = + applyTemplate vf $ pfxCaptionIndexTemplate opts refPfx + where + vf x = case x of + "i" -> Just label + _ -> titleVarFunc opts rr x + +titleVarFunc :: Options -> RefRec -> String -> Maybe B.Inlines +titleVarFunc opts RefRec{..} x = case x of + "t" -> Just refTitle + "lvl" -> Just $ B.str $ show refLevel + _ -> case refScope of + Just rs -> case x of + "s" -> Just $ Types.refIxInl rs + "scp" -> Just $ applyTitleTemplate opts rs + _ -> Nothing + _ -> Nothing divBlocks :: Options -> Block -> Block divBlocks opts (Table title align widths header cells) @@ -322,52 +229,34 @@ spanInlines opts (math@(Math DisplayMath _eq):ils) = Span nullAttr [math]:ils spanInlines _ x = x -replaceAttr :: Options -> Either String String -> Maybe String -> B.Inlines -> String -> WS B.Inlines -replaceAttr o label refLabel title pfx +replaceAttr :: Options -> Scope -> Either String String -> Maybe String -> B.Inlines -> String -> WS RefRec +replaceAttr o scope label refLabel' title pfx = do let ropt = getPfx o pfx - cur <- get curChap - let chap = take (chaptersDepth o) . fromMaybe [] . M.lookup "sec" $ cur - i <- (1+) . fromMaybe 0 . M.lookup pfx <$> get pfxCounter - -- TODO: shouldReset should likely be a transitive closure... - let shouldReset = M.keys . M.filter (\p -> pfx `elem` prefixScope p) $ prefixes o - modify pfxCounter $ M.filterWithKey $ \k _ -> k `notElem` shouldReset - modify pfxCounter $ M.insert pfx i - let customLabel = prefixNumbering ropt - -- TODO: should we prepend scoped refrences with references to the scope they're in? - -- scop = join $ fmap (flip M.lookup cur) $ prefixScope ropt - index = chap ++ [(i, fromMaybe (customLabel i) refLabel)] - label' = either (++ ':':show index) id label - modify curChap $ M.insert pfx index + customLabel = prefixNumbering ropt + itemScope = find ((`elem` prefixScope ropt) . refPfx) scope + cr <- (\CounterRec{..} -> CounterRec{ + crIndex = crIndex+1 + , crIndexInScope = M.insertWith (+) itemScope 1 crIndexInScope + }) . fromMaybe def . M.lookup pfx <$> get pfxCounter + modify pfxCounter $ M.insert pfx cr + let label' = either (++ ':':'\0':show i) id label + iInSc = fromJust $ M.lookup itemScope $ crIndexInScope cr + i = crIndex cr hasLabel <- M.member label' <$> get referenceData - when hasLabel $ - error $ "Duplicate label: " ++ label' - modify referenceData $ M.insert label' RefRec { - refIndex= index - , refTitle= title - , refSubfigure = Nothing - } - return $ chapPrefix (chapDelim o) index - -latexSubFigure :: Inline -> String -> [Inline] -latexSubFigure (Image (_, cls, attrs) alt (src, title)) label = - let - title' = fromMaybe title $ stripPrefix "fig:" title - texlabel | null label = [] - | otherwise = [RawInline (Format "latex") $ mkLaTeXLabel label] - texalt | "nocaption" `elem` cls = [] - | otherwise = concat - [ [ RawInline (Format "latex") "["] - , alt - , [ RawInline (Format "latex") "]"] - ] - img = Image (label, cls, attrs) alt (src, title') - in concat [ - [ RawInline (Format "latex") "\\subfloat" ] - , texalt - , [Span nullAttr $ img:texlabel] - ] -latexSubFigure x _ = [x] + when hasLabel $ error $ "Duplicate label: " ++ label' + let rec' = RefRec { + refIndex = i + , refTitle = title + , refLabel = label' + , refIxInl = applyTitleIndexTemplate o rec' $ B.text $ fromMaybe (customLabel iInSc) refLabel' + , refScope = itemScope + , refLevel = length $ filter ((== pfx) . refPfx) scope + , refPfx = pfx + , refCaption = applyTitleTemplate o rec' + } + modify referenceData $ M.insert label' rec' + return rec' mkCaption :: Options -> String -> B.Inlines -> Block mkCaption opts style diff --git a/lib/Text/Pandoc/CrossRef/References/List.hs b/lib/Text/Pandoc/CrossRef/References/List.hs index 438b66c1..9715d4e6 100644 --- a/lib/Text/Pandoc/CrossRef/References/List.hs +++ b/lib/Text/Pandoc/CrossRef/References/List.hs @@ -54,17 +54,12 @@ getPfxData pfx = M.filterWithKey (\k _ -> (pfx <> ":") `isPrefixOf` k) <$> get r makeList :: Options -> String -> Blocks -> M.Map String RefRec -> WS Blocks makeList opts titlef xs refs = return $ - getTitleForListOf opts titlef <> - (if chaptersDepth opts > 0 - then divWith ("", ["list"], []) (mconcat $ map itemChap refsSorted) - else orderedList (map item refsSorted)) + getTitleForListOf opts titlef + <> divWith ("", ["list"], []) (mconcat $ map itemChap refsSorted) <> xs where refsSorted :: [(String, RefRec)] refsSorted = sortBy compare' $ M.toList refs compare' (_,RefRec{refIndex=i}) (_,RefRec{refIndex=j}) = compare i j - item = plain . refTitle . snd itemChap :: (String, RefRec) -> Blocks - itemChap = para . uncurry (\ x x0 -> x <> space <> x0) . ((numWithChap . refIndex) &&& refTitle) . snd - numWithChap :: Index -> Inlines - numWithChap = chapPrefix (chapDelim opts) + itemChap = para . uncurry (\ x x0 -> x <> space <> x0) . (refIxInl &&& refTitle) . snd diff --git a/lib/Text/Pandoc/CrossRef/References/Refs.hs b/lib/Text/Pandoc/CrossRef/References/Refs.hs index e3a1092e..714ae599 100644 --- a/lib/Text/Pandoc/CrossRef/References/Refs.hs +++ b/lib/Text/Pandoc/CrossRef/References/Refs.hs @@ -18,6 +18,8 @@ with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -} +{-# LANGUAGE RecordWildCards, NamedFieldPuns #-} + module Text.Pandoc.CrossRef.References.Refs (replaceRefs) where import Text.Pandoc.Definition @@ -37,47 +39,50 @@ import Text.Pandoc.CrossRef.Util.Util import Text.Pandoc.CrossRef.Util.Options hiding (getRefPrefix) import Text.Pandoc.CrossRef.Util.Prefixes import Control.Applicative -import Data.Char (toLower) import Debug.Trace import Prelude replaceRefs :: Options -> [Inline] -> WS [Inline] replaceRefs opts ils | Cite cits _:xs <- ils - = toList . (<> fromList xs) . intercalate' (text ", ") <$> mapM replaceRefs' (groupBy eqPrefix cits) + = do + refData <- mapM getRefData cits + toList . (<> fromList xs) . intercalate' (text ", ") <$> mapM replaceRefs' (groupBy eqPred refData) where - eqPrefix a b = uncurry (==) $ - (fmap uncapitalizeFirst . getLabelPrefix opts . citationId) <***> (a,b) - (<***>) = join (***) - replaceRefs' cits' - | Just prefix <- allCitsPrefix opts cits' - = replaceRefs'' prefix opts cits' + eqPred :: RefData -> RefData -> Bool + eqPred = (==) `on` liftM2 (,) rdScope rdPrefix + replaceRefs' refs + | ref@RefDataComplete{} : _ <- refs + = replaceRefs'' (fromJust $ rdPrefix ref) opts refs | otherwise = return $ cite cits' il' where + cits' = mapMaybe getCit refs + getCit RefDataIncomplete{rdCitation, rdiLabel} + | takeWhile (/=':') rdiLabel `elem` M.keys (prefixes opts) + = trace ("Undefined cross-reference: " ++ rdiLabel) $ Just rdCitation + | otherwise = Just rdCitation + getCit RefDataComplete{} = error "Converting RefDataComplete back to Citation. This should not happen, please report a bug" il' = str "[" <> intercalate' (text "; ") (map citationToInlines cits') <> str "]" citationToInlines c = fromList (citationPrefix c) <> text ("@" ++ citationId c) <> fromList (citationSuffix c) - replaceRefs'' = case outFormat opts of - f | isLatexFormat f -> replaceRefsLatex - _ -> replaceRefsOther + replaceRefs'' + | isLatexFormat (outFormat opts) = replaceRefsLatex + | otherwise = replaceRefsOther replaceRefs _ x = return x -getRefPrefix :: Options -> String -> Bool -> Int -> Inlines -> Inlines -getRefPrefix opts prefix capitalize num cit = - applyTemplate' (M.fromDistinctAscList [("i", cit), ("p", refprefix)]) reftempl +getRefPrefix :: Options -> String -> Bool -> Int -> Int -> Inlines -> Inlines +getRefPrefix opts prefix capitalize num lvl cit = + applyTemplate vf reftempl where Prefix{prefixRef=refprefixf, prefixReferenceTemplate=reftempl} = fromMaybe undefined $ M.lookup prefix $ prefixes opts - refprefix = refprefixf capitalize num - -allCitsPrefix :: Options -> [Citation] -> Maybe String -allCitsPrefix opts cits = find isCitationPrefix $ prefixList opts - where - isCitationPrefix p = - all (p ==) $ map (takeWhile (/=':') . uncapitalizeFirst . citationId) cits + refprefix = applyRefTemplate (refprefixf lvl) capitalize num + vf "i" = Just cit + vf "p" = Just refprefix + vf _ = Nothing -replaceRefsLatex :: String -> Options -> [Citation] -> WS Inlines +replaceRefsLatex :: String -> Options -> [RefData] -> WS Inlines replaceRefsLatex prefix opts cits | cref opts = replaceRefsLatex' prefix opts cits @@ -85,7 +90,7 @@ replaceRefsLatex prefix opts cits = intercalate' (text ", ") <$> mapM (replaceRefsLatex' prefix opts) (groupBy citationGroupPred cits) -replaceRefsLatex' :: String -> Options -> [Citation] -> WS Inlines +replaceRefsLatex' :: String -> Options -> [RefData] -> WS Inlines replaceRefsLatex' prefix opts cits = return $ p texcit where @@ -94,22 +99,22 @@ replaceRefsLatex' prefix opts cits = cref'++"{"++listLabels prefix "" "," "" cits++"}" else listLabels prefix "\\ref{" ", " "}" cits - suppressAuthor = all (==SuppressAuthor) $ map citationMode cits - noPrefix = all null $ map citationPrefix cits + suppressPrefix = all rdSuppresPrefix cits + noPrefix = all isNothing $ map rdCitPrefix cits p | cref opts = id - | suppressAuthor + | suppressPrefix = id | noPrefix - = getRefPrefix opts prefix cap (length cits - 1) - | otherwise = ((fromList (citationPrefix (head cits)) <> space) <>) - cap = maybe False isFirstUpper $ getLabelPrefix opts . citationId . head $ cits - cref' | suppressAuthor = "\\labelcref" + = getRefPrefix opts prefix cap (length cits - 1) (fromMaybe 0 . rdLvl $ head cits) + | otherwise = ((fromJust (rdCitPrefix (head cits)) <> space) <>) + cap = maybe False isFirstUpper $ getLabelPrefix opts . rdLabel . head $ cits + cref' | suppressPrefix = "\\labelcref" | cap = "\\Cref" | otherwise = "\\cref" -listLabels :: String -> String -> String -> String -> [Citation] -> String +listLabels :: String -> String -> String -> String -> [RefData] -> String listLabels _prefix p sep s = - intercalate sep . map ((p ++) . (++ s) . mkLaTeXLabel' . citationId) + intercalate sep . map ((p ++) . (++ s) . mkLaTeXLabel' . rdLabel) getLabelPrefix :: Options -> String -> Maybe String getLabelPrefix opts lab @@ -117,55 +122,88 @@ getLabelPrefix opts lab | otherwise = Nothing where p = takeWhile (/=':') lab -replaceRefsOther :: String -> Options -> [Citation] -> WS Inlines +replaceRefsOther :: String -> Options -> [RefData] -> WS Inlines replaceRefsOther prefix opts cits = intercalate' (text ", ") <$> mapM (replaceRefsOther' prefix opts) (groupBy citationGroupPred cits) -citationGroupPred :: Citation -> Citation -> Bool -citationGroupPred = (==) `on` liftM2 (,) citationPrefix citationMode +citationGroupPred :: RefData -> RefData -> Bool +citationGroupPred = (==) `on` liftM2 (,) rdCitPrefix rdSuppresPrefix -replaceRefsOther' :: String -> Options -> [Citation] -> WS Inlines -replaceRefsOther' prefix opts cits = do - indices <- mapM getRefIndex cits +replaceRefsOther' :: String -> Options -> [RefData] -> WS Inlines +replaceRefsOther' prefix opts indices = do let - cap = maybe False isFirstUpper $ getLabelPrefix opts . citationId . head $ cits - writePrefix | all (==SuppressAuthor) $ map citationMode cits + firstRef@RefDataComplete{..} = head indices + cap = rdUpperCase + depth = fromMaybe 0 $ rdLvl firstRef + writePrefix | rdSuppresPrefix = id - | all null $ map citationPrefix cits - = cmap $ getRefPrefix opts prefix cap (length cits - 1) + | isNothing rdCitPrefix + = cmap $ getRefPrefix opts prefix cap (length indices - 1) depth | otherwise - = cmap ((fromList (citationPrefix (head cits)) <> space) <>) + = cmap ((fromJust rdCitPrefix <> space) <>) cmap f x | nameInLink opts , [Link attr t (y, z)] <- toList x = linkWith attr y z (f $ fromList t) cmap f x = f x return $ writePrefix (makeIndices opts indices) -data RefData = RefData { rdLabel :: String - , rdIdx :: Maybe Index - , rdSubfig :: Maybe Index - , rdSuffix :: Inlines - } deriving (Eq, Show) +data RefData = RefDataIncomplete + { rdiLabel :: String + , rdSuffix :: Inlines + , rdCitation :: Citation + } + | RefDataComplete + { rdRec :: RefRec + , rdSuffix :: Inlines + , rdCitPrefix :: Maybe Inlines + , rdUpperCase :: Bool + , rdSuppresPrefix :: Bool + } deriving (Eq, Show) + +rdIdx :: RefData -> Maybe Int +rdIdx RefDataIncomplete{} = Nothing +rdIdx RefDataComplete{rdRec} = Just $ refIndex rdRec + +rdScope :: RefData -> Maybe RefRec +rdScope RefDataIncomplete{} = Nothing +rdScope RefDataComplete{rdRec} = refScope rdRec + +rdPrefix :: RefData -> Maybe String +rdPrefix RefDataIncomplete{} = Nothing +rdPrefix RefDataComplete{rdRec} = Just $ refPfx rdRec + +rdLvl :: RefData -> Maybe Int +rdLvl RefDataIncomplete{} = Nothing +rdLvl RefDataComplete{rdRec} = Just $ refLevel rdRec + +rdLabel :: RefData -> String +rdLabel RefDataIncomplete{rdiLabel} = rdiLabel +rdLabel RefDataComplete{rdRec} = refLabel rdRec instance Ord RefData where (<=) = (<=) `on` rdIdx -getRefIndex :: Citation -> WS RefData -getRefIndex Citation{citationId=cid,citationSuffix=suf} +getRefData :: Citation -> WS RefData +getRefData c@Citation{..} = do ref <- M.lookup llab <$> get referenceData - let sub = refSubfigure <$> ref - idx = refIndex <$> ref - return RefData - { rdLabel = llab - , rdIdx = idx - , rdSubfig = join sub - , rdSuffix = fromList suf - } - where - (pfx, lab) = span (/=':') cid - lpfx = map toLower pfx - llab = lpfx <> lab + return $ case ref of + Nothing -> RefDataIncomplete + { rdiLabel = llab + , rdSuffix = suf' + , rdCitation = c + } + Just x -> RefDataComplete + { rdRec = x + , rdSuffix = suf' + , rdCitPrefix = if null citationPrefix + then Nothing + else Just $ fromList citationPrefix + , rdUpperCase = isFirstUpper citationId + , rdSuppresPrefix = SuppressAuthor == citationMode + } + where llab = uncapitalizeFirst citationId + suf' = fromList citationSuffix data RefItem = RefRange RefData RefData | RefSingle RefData @@ -174,17 +212,11 @@ makeIndices o s = format $ concatMap f $ HT.groupBy g $ sort $ nub s where g :: RefData -> RefData -> Bool g a b = all (null . rdSuffix) [a, b] && ( - all (isNothing . rdSubfig) [a, b] && - fromMaybe False ((liftM2 follows `on` rdIdx) b a) || - rdIdx a == rdIdx b && - fromMaybe False ((liftM2 follows `on` rdSubfig) b a) + fromMaybe False ((liftM2 follows `on` rdIdx) b a) && + ((==) `on` rdScope) a b ) - follows :: Index -> Index -> Bool - follows a b - | Just (ai, al) <- HT.viewR a - , Just (bi, bl) <- HT.viewR b - = ai == bi && fst bl + 1 == fst al - follows _ _ = False + follows :: Int -> Int -> Bool + follows a b = b + 1 == a f :: [RefData] -> [RefItem] f [] = [] -- drop empty lists f [w] = [RefSingle w] -- single value @@ -203,24 +235,28 @@ makeIndices o s = format $ concatMap f $ HT.groupBy g $ sort $ nub s show'' (RefSingle x) = show' x show'' (RefRange x y) = show' x <> rangeDelim o <> show' y show' :: RefData -> Inlines - show' RefData{rdLabel=l, rdIdx=Just i, rdSubfig = sub, rdSuffix = suf} - | linkReferences o = link ('#':l) "" txt + show' RefDataComplete{..} + | linkReferences o = link ('#':refLabel rdRec) "" txt | otherwise = txt - where - txt - | Just sub' <- sub - = let vars = M.fromDistinctAscList - [ ("i", chapPrefix (chapDelim o) i) - , ("s", chapPrefix (chapDelim o) sub') - , ("suf", suf) - ] - in applyTemplate' vars $ subfigureRefIndexTemplate o - | otherwise - = let vars = M.fromDistinctAscList - [ ("i", chapPrefix (chapDelim o) i) - , ("suf", suf) - ] - in applyTemplate' vars $ refIndexTemplate o - show' RefData{rdLabel=l, rdIdx=Nothing, rdSuffix = suf} = - trace ("Undefined cross-reference: " ++ l) - (strong (text $ "¿" ++ l ++ "?") <> suf) + where txt = applyIndexTemplate o rdSuffix rdRec + show' RefDataIncomplete{..} = + error ("Undefined cross-reference: " <> rdiLabel + <> ". This should not be possible, please report a bug") + +applyIndexTemplate :: Options -> Many Inline -> RefRec -> Inlines +applyIndexTemplate opts suf RefRec{..} = + let vars x = case x of + "i" -> Just refIxInl + "suf" -> Just suf + _ -> case refScope of + Just v -> case x of + "s" -> Just $ applyIndexTemplate opts mempty v + "scp" -> Just $ inlines False v + "Scp" -> Just $ inlines True v + _ -> Nothing + _ -> Nothing + template = prefixReferenceIndexTemplate pfxRec + pfxRec = getPfx opts refPfx + inlines cap ref@RefRec{refPfx=refPfx', refLevel=refLevel'} = + getRefPrefix opts refPfx' cap 0 refLevel' $ applyIndexTemplate opts mempty ref + in applyTemplate vars template diff --git a/lib/Text/Pandoc/CrossRef/References/Subfigures.hs b/lib/Text/Pandoc/CrossRef/References/Subfigures.hs new file mode 100644 index 00000000..e50779b7 --- /dev/null +++ b/lib/Text/Pandoc/CrossRef/References/Subfigures.hs @@ -0,0 +1,143 @@ + +module Text.Pandoc.CrossRef.References.Subfigures where + +-- import Text.Pandoc.Definition +-- import qualified Text.Pandoc.Builder as B +-- import Text.Pandoc.Shared (stringify, hierarchicalize, Element(..)) +-- import Control.Monad.State hiding (get, modify) +-- import Data.List +-- import Data.Maybe +-- import Data.Monoid +-- import qualified Data.Map as M +-- +-- import Data.Accessor.Monad.Trans.State +-- import Text.Pandoc.CrossRef.References.Types +-- import Text.Pandoc.CrossRef.Util.Util +-- import Text.Pandoc.CrossRef.Util.Options +-- import Text.Pandoc.CrossRef.Util.Prefixes +-- import Text.Pandoc.CrossRef.Util.Template +-- import Text.Pandoc.CrossRef.Util.CodeBlockCaptions +-- import Control.Applicative +-- import Data.Default (def) +-- import Prelude +-- +-- replaceBlock opts scope (Div (label,cls,attrs) images) +-- | Just pfx <- getRefPrefix opts label +-- , Para caption <- last images +-- = do +-- idxStr <- replaceAttr opts scope (Right label) (lookup "label" attrs) (B.fromList caption) pfx +-- let (cont, st) = runState (runReplace scope (mkRR $ replaceSubfigs opts') $ init images) def +-- collectedCaptions = B.toList $ +-- intercalate' (ccsDelim opts) +-- $ map (collectCaps . snd) +-- $ sortOn (refIndex . snd) +-- $ filter (not . null . refTitle . snd) +-- $ M.toList +-- $ referenceData_ st +-- collectCaps v = +-- applyTemplate +-- (chapPrefix (chapDelim opts) (refIndex v)) +-- (refTitle v) +-- (ccsTemplate opts) +-- vars = M.fromDistinctAscList +-- [ ("ccs", B.fromList collectedCaptions) +-- , ("i", idxStr) +-- , ("t", B.fromList caption) +-- ] +-- capt = applyTemplate' vars $ pfxCaptionTemplate opts pfx +-- opts' = opts { +-- prefixes = case M.lookup ("sub" <> pfx) $ prefixes opts of +-- Just sp -> M.insert pfx sp $ prefixes opts +-- Nothing -> prefixes opts +-- } +-- lastRef <- fromJust . M.lookup label <$> get referenceData +-- modify referenceData $ \old -> +-- M.union +-- old +-- (M.map (\v -> v{refIndex = refIndex lastRef, refSubfigure = Just $ refIndex v}) +-- $ referenceData_ st) +-- case outFormat opts of +-- f | isLatexFormat f, pfx == "fig" -> +-- replaceNoRecurse $ Div nullAttr $ +-- [ RawBlock (Format "latex") "\\begin{figure}\n\\centering" ] +-- ++ cont ++ +-- [ Para [RawInline (Format "latex") "\\caption" +-- , Span nullAttr caption] +-- , RawBlock (Format "latex") $ mkLaTeXLabel label +-- , RawBlock (Format "latex") "\\end{figure}"] +-- _ -> replaceNoRecurse $ Div (label, "subfigures":cls, attrs) $ toTable cont capt +-- where +-- toTable :: [Block] -> B.Inlines -> [Block] +-- toTable blks capt +-- | subfigGrid opts = [Table [] align widths [] $ map blkToRow blks, mkCaption opts "Image Caption" capt] +-- | otherwise = blks ++ [mkCaption opts "Image Caption" capt] +-- where +-- align | Para ils:_ <- blks = replicate (length $ mapMaybe getWidth ils) AlignCenter +-- | otherwise = error "Misformatted subfigures block" +-- widths | Para ils:_ <- blks +-- = fixZeros $ mapMaybe getWidth ils +-- | otherwise = error "Misformatted subfigures block" +-- getWidth (Image (_id, _class, as) _ _) +-- = Just $ maybe 0 percToDouble $ lookup "width" as +-- getWidth _ = Nothing +-- fixZeros :: [Double] -> [Double] +-- fixZeros ws +-- = let nz = length $ filter (== 0) ws +-- rzw = (0.99 - sum ws) / fromIntegral nz +-- in if nz>0 +-- then map (\x -> if x == 0 then rzw else x) ws +-- else ws +-- percToDouble :: String -> Double +-- percToDouble percs +-- | '%' <- last percs +-- , perc <- read $ init percs +-- = perc/100.0 +-- | otherwise = error "Only percent allowed in subfigure width!" +-- blkToRow :: Block -> [[Block]] +-- blkToRow (Para inls) = mapMaybe inlToCell inls +-- blkToRow x = [[x]] +-- inlToCell :: Inline -> Maybe [Block] +-- inlToCell (Image (id', cs, as) txt tgt) = Just [Para [Image (id', cs, setW as) txt tgt]] +-- inlToCell _ = Nothing +-- setW as = ("width", "100%"):filter ((/="width") . fst) as +-- +-- replaceSubfigs :: Options -> Scope -> [Inline] -> WS (ReplacedResult [Inline]) +-- replaceSubfigs opts scope = (replaceNoRecurse scope . concat =<<) . mapM (replaceSubfig opts) +-- +-- replaceSubfig :: Options -> Inline -> WS [Inline] +-- replaceSubfig opts x@(Image (label,cls,attrs) alt (src, tit)) +-- = do +-- let label' | "fig:" `isPrefixOf` label = Right label +-- | null label = Left "fig" +-- | otherwise = Right $ "fig:" ++ label +-- let ialt = B.fromList alt +-- idxStr <- replaceAttr opts scope label' (lookup "label" attrs) ialt "fig" +-- case outFormat opts of +-- f | isLatexFormat f -> +-- return $ latexSubFigure x label +-- _ -> +-- let alt' = B.toList $ applyTemplate idxStr ialt $ pfxCaptionTemplate opts "fig" +-- tit' | "nocaption" `elem` cls = fromMaybe tit $ stripPrefix "fig:" tit +-- | "fig:" `isPrefixOf` tit = tit +-- | otherwise = "fig:" ++ tit +-- in return [Image (label, cls, attrs) alt' (src, tit')] +-- replaceSubfig _ x = return [x] +-- latexSubFigure :: Inline -> String -> [Inline] +-- latexSubFigure (Image (_, cls, attrs) alt (src, title)) label = +-- let +-- title' = fromMaybe title $ stripPrefix "fig:" title +-- texlabel | null label = [] +-- | otherwise = [RawInline (Format "latex") $ mkLaTeXLabel label] +-- texalt | "nocaption" `elem` cls = [] +-- | otherwise = concat +-- [ [ RawInline (Format "latex") "["] +-- , alt +-- , [ RawInline (Format "latex") "]"] +-- ] +-- img = Image (label, cls, attrs) alt (src, title') +-- in concat [ +-- [ RawInline (Format "latex") "\\subfloat" ] +-- , texalt +-- , [Span nullAttr $ img:texlabel] +-- ] +-- latexSubFigure x _ = [x] diff --git a/lib/Text/Pandoc/CrossRef/References/Types.hs b/lib/Text/Pandoc/CrossRef/References/Types.hs index ee6d5e0e..e25c3b39 100644 --- a/lib/Text/Pandoc/CrossRef/References/Types.hs +++ b/lib/Text/Pandoc/CrossRef/References/Types.hs @@ -27,25 +27,37 @@ import Data.Default import Data.Accessor.Template import Text.Pandoc.Builder -type Index = [(Int, String)] - -data RefRec = RefRec { refIndex :: !Index - , refTitle :: !Inlines - , refSubfigure :: !(Maybe Index) - } deriving (Show, Eq) +data RefRec = RefRec { refIndex :: !Int -- global ordinal number for prefix + , refIxInl :: Inlines -- index as inilnes + , refTitle :: !Inlines -- title text + , refScope :: !(Maybe RefRec) -- reference to parent label + , refLevel :: !Int -- number of upper scopes of the same prefix + , refLabel :: !String -- label, i.e. pfx:label string + , refPfx :: !String -- reference prefix, the part in label before : + , refCaption :: Inlines -- caption after applying template; must be non-strict + } deriving (Show, Eq, Ord) type RefMap = M.Map String RefRec -- state data type data References = References { referenceData_ :: !RefMap - , curChap_ :: !(M.Map String Index) - , pfxCounter_ :: !(M.Map String Int) + , pfxCounter_ :: !(M.Map String CounterRec) } deriving (Show, Eq) +data CounterRec = CounterRec { + crIndex :: Int + , crIndexInScope :: M.Map (Maybe RefRec) Int + } deriving (Show, Eq) + --state monad type WS a = State References a +type Scope = [RefRec] + instance Default References where - def = References M.empty M.empty M.empty + def = References M.empty M.empty + +instance Default CounterRec where + def = CounterRec 0 M.empty deriveAccessors ''References diff --git a/lib/Text/Pandoc/CrossRef/Util/Meta.hs b/lib/Text/Pandoc/CrossRef/Util/Meta.hs index 9377a5c8..01d89f2a 100644 --- a/lib/Text/Pandoc/CrossRef/Util/Meta.hs +++ b/lib/Text/Pandoc/CrossRef/Util/Meta.hs @@ -26,10 +26,11 @@ module Text.Pandoc.CrossRef.Util.Meta ( , getMetaBlock , getMetaString , getMetaStringMaybe + , getMetaStringList , getList , toString , toInlines - , tryCapitalizeM + , capitalize ) where import Text.Pandoc.CrossRef.Util.Util @@ -44,6 +45,12 @@ import Data.Maybe getMetaList :: (Default a) => (MetaValue -> a) -> String -> Settings -> Int -> a getMetaList f name (Settings meta) i = maybe def f $ lookupMeta name meta >>= getList i +getMetaStringList :: String -> Settings -> [String] +getMetaStringList name (Settings meta) = maybe [] (getList' name) $ lookupMeta name meta + where + getList' n (MetaList l) = map (toString n) l + getList' n x = [toString n x] + getMetaBool :: String -> Settings -> Bool getMetaBool = getScalar toBool @@ -120,15 +127,10 @@ getList i (MetaList l) = l !!? i | otherwise = Nothing getList _ x = Just x -tryCapitalizeM :: (Functor m, Monad m, Walkable Inline a, Default a, Eq a) => - (String -> m a) -> String -> Bool -> m a -tryCapitalizeM f varname capitalize - | capitalize = do - res <- f (capitalizeFirst varname) - case res of - xs | xs == def -> f varname >>= walkM capStrFst - | otherwise -> return xs - | otherwise = f varname +capitalize :: (Walkable Inline a) => (String -> Maybe a) -> String -> Maybe a +capitalize f varname = case f (capitalizeFirst varname) of + Nothing -> walk capStrFst <$> f varname + Just xs -> Just xs where - capStrFst (Str s) = return $ Str $ capitalizeFirst s - capStrFst x = return x + capStrFst (Str s) = Str $ capitalizeFirst s + capStrFst x = x diff --git a/lib/Text/Pandoc/CrossRef/Util/ModifyMeta.hs b/lib/Text/Pandoc/CrossRef/Util/ModifyMeta.hs index d30ec29c..41813b31 100644 --- a/lib/Text/Pandoc/CrossRef/Util/ModifyMeta.hs +++ b/lib/Text/Pandoc/CrossRef/Util/ModifyMeta.hs @@ -92,27 +92,27 @@ modifyMeta opts meta ] | otherwise = ["\\newcommand*\\listoflistings{\\listof{codelisting}{"++getListOfTitle "lst"++"}}"] cleveref = [ usepackage cleverefOpts "cleveref" ] - <> crefname "figure" (pfxRef "fig") - <> crefname "table" (pfxRef "tbl") - <> crefname "equation" (pfxRef "eq") - <> crefname "listing" (pfxRef "lst") - <> crefname "section" (pfxRef "sec") - pfxRef labelPrefix = prefixRef . flip getPfx labelPrefix + -- <> crefname "figure" (pfxRef "fig") + -- <> crefname "table" (pfxRef "tbl") + -- <> crefname "equation" (pfxRef "eq") + -- <> crefname "listing" (pfxRef "lst") + -- <> crefname "section" (pfxRef "sec") + -- pfxRef labelPrefix = prefixRef . flip getPfx labelPrefix cleverefCodelisting = [ "\\crefname{codelisting}{\\cref@listing@name}{\\cref@listing@name@plural}" , "\\Crefname{codelisting}{\\Cref@listing@name}{\\Cref@listing@name@plural}" ] cleverefOpts | nameInLink opts = [ "nameinlink" ] | otherwise = [] - crefname n f = [ - "\\crefname{" ++ n ++ "}" ++ prefix f False - , "\\Crefname{" ++ n ++ "}" ++ prefix f True - ] + -- crefname n f = [ + -- "\\crefname{" ++ n ++ "}" ++ prefix f False + -- , "\\Crefname{" ++ n ++ "}" ++ prefix f True + -- ] usepackage [] p = "\\@ifpackageloaded{"++p++"}{}{\\usepackage{"++p++"}}" usepackage xs p = "\\@ifpackageloaded{"++p++"}{}{\\usepackage"++o++"{"++p++"}}" where o = "[" ++ intercalate "," xs ++ "]" toLatex = either (error . show) T.unpack . runPure . writeLaTeX def . Pandoc nullMeta . return . Plain getListOfTitle = toLatex . blocksToInlines . toList . getTitleForListOf opts getFloatCaption = toLatex . toList . prefixTitle . getPfx opts - prefix f uc = "{" ++ toLatex (toList $ f opts uc 0) ++ "}" ++ - "{" ++ toLatex (toList $ f opts uc 1) ++ "}" + -- prefix f uc = "{" ++ toLatex (toList $ f opts uc 0) ++ "}" ++ + -- "{" ++ toLatex (toList $ f opts uc 1) ++ "}" diff --git a/lib/Text/Pandoc/CrossRef/Util/Options.hs b/lib/Text/Pandoc/CrossRef/Util/Options.hs index 4ef3bbf0..169a94fb 100644 --- a/lib/Text/Pandoc/CrossRef/Util/Options.hs +++ b/lib/Text/Pandoc/CrossRef/Util/Options.hs @@ -30,27 +30,16 @@ import Data.List.Extra import Text.Pandoc.CrossRef.Util.LatexPrefixes data Options = Options { cref :: Bool - , chaptersDepth :: Int , listings :: Bool , codeBlockCaptions :: Bool , autoSectionLabels :: Bool - , numberSections :: Bool - , sectionsDepth :: Int - , refIndexTemplate :: Template - , subfigureRefIndexTemplate :: Template - , secHeaderTemplate :: Template - , chapDelim :: Inlines , rangeDelim :: Inlines , pairDelim :: Inlines , lastDelim :: Inlines , refDelim :: Inlines , outFormat :: Maybe Format - , ccsTemplate :: Template - , ccsDelim :: Inlines - , ccsLabelSep :: Inlines , tableEqns :: Bool , autoEqnLabels :: Bool - , subfigGrid :: Bool , linkReferences :: Bool , nameInLink :: Bool , prefixes :: Prefixes @@ -63,6 +52,9 @@ prefixList = M.keys . prefixes pfxCaptionTemplate :: Options -> String -> Template pfxCaptionTemplate opts pfx = prefixCaptionTemplate $ getPfx opts pfx +pfxCaptionIndexTemplate :: Options -> String -> Template +pfxCaptionIndexTemplate opts pfx = prefixCaptionIndexTemplate $ getPfx opts pfx + getPfx :: Options -> String -> Prefix getPfx o pn = fromMaybe defaultPfx $ M.lookup pn $ prefixes o where diff --git a/lib/Text/Pandoc/CrossRef/Util/Prefixes.hs b/lib/Text/Pandoc/CrossRef/Util/Prefixes.hs index c80c943b..5f488756 100644 --- a/lib/Text/Pandoc/CrossRef/Util/Prefixes.hs +++ b/lib/Text/Pandoc/CrossRef/Util/Prefixes.hs @@ -48,19 +48,31 @@ getPrefixes varN dtv where var = displayMath m2p _ (MetaMap kv') = Prefix { - prefixRef = (fromInlines' .) . tryCapitalizeM (flip (getMetaList (Inlines' . toInlines "ref")) kv) "ref" + prefixRef = makeRefTemplate kv . + if isJust $ lookupSettings "refTemplate" kv + then fromInlines' . getMetaList (Inlines' . toInlines "refTemplate") "refTemplate" kv + else const $ var "Ref[n]" + -- tryCapitalizeM (\y -> getMetaList (Inlines' . toInlines "ref") y kv) "ref" , prefixCaptionTemplate = makeTemplate kv $ if isJust $ lookupSettings "captionTemplate" kv then getMetaInlines "captionTemplate" kv - else var "title" <> space <> var "i" <> var "titleDelim" <> space <> var "t" <> var "ccs#. " + else var "title" <> space <> var "i" <> var "titleDelim" <> space <> var "t" , prefixReferenceTemplate = makeTemplate kv $ if isJust $ lookupSettings "referenceTemplate" kv then getMetaInlines "referenceTemplate" kv else var "p" <> str "\160" <> var "i" - , prefixScope = getMetaStringMaybe "scope" kv + , prefixScope = getMetaStringList "scope" kv , prefixNumbering = mkLabel (varN <> "." <> "numbering") (fromMaybe (MetaString "arabic") $ lookupSettings "numbering" kv) , prefixListOfTitle = getMetaBlock "listOfTitle" kv , prefixTitle = getMetaInlines "title" kv + , prefixReferenceIndexTemplate = makeTemplate kv $ + if isJust $ lookupSettings "referenceIndexTemplate" kv + then getMetaInlines "referenceIndexTemplate" kv + else var "i" <> var "suf" + , prefixCaptionIndexTemplate = makeTemplate kv $ + if isJust $ lookupSettings "captionIndexTemplate" kv + then getMetaInlines "captionIndexTemplate" kv + else var "i" } where kv = Settings (Meta kv') <> dtv m2p k _ = error $ "Invalid value for prefix " <> k @@ -68,12 +80,14 @@ getPrefixes varN dtv type Prefixes = M.Map String Prefix data Prefix = Prefix { - prefixRef :: !(Bool -> Int -> Inlines) + prefixRef :: !(Int -> RefTemplate) , prefixCaptionTemplate :: !Template , prefixReferenceTemplate :: !Template - , prefixScope :: !(Maybe String) + , prefixScope :: ![String] , prefixNumbering :: !(Int -> String) , prefixListOfTitle :: !Blocks + , prefixReferenceIndexTemplate :: !Template + , prefixCaptionIndexTemplate :: !Template -- Used for LaTeX metadata; the same value is used in -- default value for prefixCaptionTemplate , prefixTitle :: Inlines diff --git a/lib/Text/Pandoc/CrossRef/Util/Settings.hs b/lib/Text/Pandoc/CrossRef/Util/Settings.hs index b080e2fe..589f1235 100644 --- a/lib/Text/Pandoc/CrossRef/Util/Settings.hs +++ b/lib/Text/Pandoc/CrossRef/Util/Settings.hs @@ -60,58 +60,18 @@ getSettings fmt inMeta = do defaultMeta :: Settings defaultMeta = Settings $ cref False - <> chapters False - <> chaptersDepth "1" <> listings False <> codeBlockCaptions False <> autoSectionLabels False - <> numberSections False - <> sectionsDepth "0" - -- <> figLabels "arabic" - -- <> eqnLabels "arabic" - -- <> tblLabels "arabic" - -- <> lstLabels "arabic" - -- <> secLabels "arabic" - -- <> figureTitle (str "Figure") - -- <> tableTitle (str "Table") - -- <> listingTitle (str "Listing") + -- <> numberSections False <> titleDelim (str ":") - <> chapDelim (str ".") <> rangeDelim (str "-") <> pairDelim (str "," <> space) <> lastDelim (str "," <> space) <> refDelim (str "," <> space) - -- <> figPrefix [str "fig.", str "figs."] - -- <> eqnPrefix [str "eq." , str "eqns."] - -- <> tblPrefix [str "tbl.", str "tbls."] - -- <> lstPrefix [str "lst.", str "lsts."] - -- <> secPrefix [str "sec.", str "secs."] - -- <> figPrefixTemplate (var "p" <> str "\160" <> var "i") - -- <> eqnPrefixTemplate (var "p" <> str "\160" <> var "i") - -- <> tblPrefixTemplate (var "p" <> str "\160" <> var "i") - -- <> lstPrefixTemplate (var "p" <> str "\160" <> var "i") - -- <> secPrefixTemplate (var "p" <> str "\160" <> var "i") - <> refIndexTemplate (var "i" <> var "suf") - <> subfigureRefIndexTemplate (var "i" <> var "suf" <> space <> str "(" <> var "s" <> str ")") - <> secHeaderTemplate (var "i" <> var "secHeaderDelim" <> var "t") - <> secHeaderDelim space - -- <> lofTitle (header 1 $ text "List of Figures") - -- <> lotTitle (header 1 $ text "List of Tables") - -- <> lolTitle (header 1 $ text "List of Listings") - -- <> figureTemplate (var "figureTitle" <> space <> var "i" <> var "titleDelim" <> space <> var "t") - -- <> tableTemplate (var "tableTitle" <> space <> var "i" <> var "titleDelim" <> space <> var "t") - -- <> listingTemplate (var "listingTitle" <> space <> var "i" <> var "titleDelim" <> space <> var "t") <> crossrefYaml "pandoc-crossref.yaml" - <> chaptersDepth "1" - -- <> subfigureChildTemplate (var "i") - -- <> subfigureTemplate (var "figureTitle" <> space <> var "i" <> var "titleDelim" <> space <> var "t" <> str "." <> space <> var "ccs") - -- <> subfigLabels "alpha a" - <> ccsDelim (str "," <> space) - <> ccsLabelSep (space <> str "—" <> space) - <> ccsTemplate (var "i" <> var "ccsLabelSep" <> var "t") <> tableEqns False <> autoEqnLabels False - <> subfigGrid False <> linkReferences False <> nameInLink False <> latexPrefixes' [ diff --git a/lib/Text/Pandoc/CrossRef/Util/Settings/Gen.hs b/lib/Text/Pandoc/CrossRef/Util/Settings/Gen.hs index ddfc2dd8..9a7b9259 100644 --- a/lib/Text/Pandoc/CrossRef/Util/Settings/Gen.hs +++ b/lib/Text/Pandoc/CrossRef/Util/Settings/Gen.hs @@ -24,7 +24,6 @@ module Text.Pandoc.CrossRef.Util.Settings.Gen where import Text.Pandoc.CrossRef.Util.Settings.Template import Text.Pandoc.CrossRef.Util.Settings.Types -import Text.Pandoc.CrossRef.Util.Meta import Text.Pandoc.CrossRef.Util.Options as O (Options(..)) import Language.Haskell.TH (mkName) import Text.Pandoc.Definition @@ -32,24 +31,9 @@ import Text.Pandoc.Definition nameDeriveSetters ''Options fmap concat $ mapM (makeAcc . mkName) - -- [ "figureTitle" - -- , "tableTitle" - -- , "listingTitle" - [ "titleDelim" - , "crossrefYaml" - -- , "subfigLabels" - , "chapters" - -- , "figLabels" - -- , "eqnLabels" - -- , "tblLabels" - -- , "lstLabels" - -- , "secLabels" - , "secHeaderDelim" + [ "crossrefYaml" + , "titleDelim" ] getOptions :: Settings -> Maybe Format -> Options -getOptions dtv fmt = - let opts = $(makeCon ''Options 'Options) - in if getMetaBool "chapters" dtv - then opts - else opts{O.chaptersDepth = 0} +getOptions dtv fmt = $(makeCon ''Options 'Options) diff --git a/lib/Text/Pandoc/CrossRef/Util/Template.hs b/lib/Text/Pandoc/CrossRef/Util/Template.hs index 78c06b12..5493ddff 100644 --- a/lib/Text/Pandoc/CrossRef/Util/Template.hs +++ b/lib/Text/Pandoc/CrossRef/Util/Template.hs @@ -18,55 +18,79 @@ with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -} +{-# LANGUAGE RecordWildCards #-} + module Text.Pandoc.CrossRef.Util.Template ( Template + , RefTemplate , makeTemplate + , makeRefTemplate , applyTemplate - , applyTemplate' + , applyRefTemplate ) where import Text.Pandoc.Definition import Text.Pandoc.Builder import Text.Pandoc.Generic -import qualified Data.Map as M hiding (toList, fromList, singleton) import Text.Pandoc.CrossRef.Util.Meta import Text.Pandoc.CrossRef.Util.Settings.Types import Control.Applicative import Text.Read +import Data.Char (isAlphaNum, isUpper, toLower) +import Control.Monad (join) type VarFunc = String -> Maybe MetaValue newtype Template = Template (VarFunc -> Inlines) +newtype RefTemplate = RefTemplate (Bool -> Int -> Inlines) + +data State = StFirstVar | StIndex | StAfterIndex | StPrefix | StSuffix +data ParseRes = ParseRes { prVar :: String, prIdx :: Maybe String, prPfx :: String, prSfx :: String } deriving Show + +parse :: State -> String -> ParseRes +parse _ [] = ParseRes [] Nothing [] [] +parse StFirstVar cs@(c:_) | isAlphaNum c = let (var, rest) = span isAlphaNum cs in (parse StFirstVar rest){prVar = var} +parse StFirstVar ('[':cs) = let (idx, rest) = span isAlphaNum cs in (parse StIndex rest){prIdx = Just idx} +parse StIndex (']':cs) = parse StAfterIndex cs +parse StIndex _ = error "Unterminated [ in indexed variable" +parse _ ('%':cs) = parse StSuffix cs +parse _ ('#':cs) = parse StPrefix cs +parse StFirstVar s = error $ "Invalid variable name in " <> s +parse StAfterIndex (c:_) = error $ "Unexpected character " <> [c] <> " after parsing indexed variable" +parse StPrefix cs = let (pfx, rest) = span (`notElem` "%#") cs in (parse StPrefix rest){prPfx = pfx} +parse StSuffix cs = let (sfx, rest) = span (`notElem` "%#") cs in (parse StSuffix rest){prSfx = sfx} makeTemplate :: Settings -> Inlines -> Template makeTemplate dtv xs' = Template $ \vf -> fromList $ scan (\var -> vf var <|> lookupSettings var dtv) $ toList xs' where scan :: (String -> Maybe MetaValue) -> [Inline] -> [Inline] scan = bottomUp . go - go vf ((Math DisplayMath var):xs) - | '[' `elem` var && ']' == last var = - let (vn, idxBr) = span (/='[') var - idxVar = drop 1 $ takeWhile (/=']') idxBr - idx = readMaybe . toString ("index variable " ++ idxVar) =<< vf idxVar - arr = do - i <- idx - v <- lookupSettings vn dtv - getList i v - in toList $ (replaceVar arr id) <> fromList xs - | '#' `elem` var = - let (vn, pfx') = span (/='#') var - pfx = drop 1 pfx' - in toList $ (replaceVar (vf vn) (text pfx <>)) <> fromList xs - | otherwise = toList $ (replaceVar (vf var) id) <> fromList xs - where replaceVar val m = maybe mempty (m . toInlines ("variable " ++ var)) val + go vf (Math DisplayMath var:xs) + | ParseRes{..} <- parse StFirstVar var + = let replaceVar = maybe mempty (modifier . toInlines ("variable " ++ var)) + modifier = (<> text prSfx) . (text prPfx <>) + in case prIdx of + Just idxVar -> + let + idx = readMaybe . toString ("index variable " ++ idxVar) =<< vf idxVar + arr = join $ getList <$> idx <*> vf prVar + in toList $ replaceVar arr <> fromList xs + Nothing -> toList $ replaceVar (vf prVar) <> fromList xs go _ (x:xs) = toList $ singleton x <> fromList xs go _ [] = [] -applyTemplate' :: M.Map String Inlines -> Template -> Inlines -applyTemplate' vars (Template g) = g internalVars - where - internalVars x | Just v <- M.lookup x vars = Just $ MetaInlines $ toList v - internalVars _ = Nothing +makeRefTemplate :: Settings -> Inlines -> RefTemplate +makeRefTemplate dtv xs' = + let Template g = makeTemplate dtv xs' + vf _ n "n" = Just $ MetaInlines [Str $ show n] + vf cap _ (vc:vs) + | isUpper vc && cap = capitalize (`lookupSettings` dtv) var + | otherwise = lookupSettings var dtv + where var = toLower vc : vs + vf _ _ [] = error "Empty variable name" + in RefTemplate $ \cap n -> g (vf cap n) + +applyRefTemplate :: RefTemplate -> Bool -> Int -> Inlines +applyRefTemplate (RefTemplate g) = g -applyTemplate :: Inlines -> Inlines -> Template -> Inlines -applyTemplate i t = - applyTemplate' (M.fromDistinctAscList [("i", i), ("t", t)]) +applyTemplate :: (String -> Maybe Inlines) -> Template -> Inlines +applyTemplate vars (Template g) = g $ fmap (MetaInlines . toList) . vars diff --git a/lib/Text/Pandoc/CrossRef/Util/Util.hs b/lib/Text/Pandoc/CrossRef/Util/Util.hs index 3a3e4fd6..4e792c39 100644 --- a/lib/Text/Pandoc/CrossRef/Util/Util.hs +++ b/lib/Text/Pandoc/CrossRef/Util/Util.hs @@ -26,8 +26,8 @@ module Text.Pandoc.CrossRef.Util.Util import Text.Pandoc.CrossRef.References.Types import Text.Pandoc.Definition -import Text.Pandoc.Builder hiding ((<>)) import Text.Pandoc.Class +import Text.Pandoc.Shared (Element(..)) import Data.Char (toUpper, toLower, isUpper) import Data.Generics hiding (Prefix) import Text.Pandoc.Writers.LaTeX @@ -58,47 +58,44 @@ isFirstUpper :: String -> Bool isFirstUpper (x:_) = isUpper x isFirstUpper [] = False -chapPrefix :: Inlines -> Index -> Inlines -chapPrefix delim index = intercalate' delim (map (str . snd) index) +data ReplacedResult a = ReplacedRecurse Scope a + | NotReplacedRecurse Scope + | ReplacedNoRecurse a + | NotReplacedNoRecurse +type GenRR m = forall a. Data a => (Scope -> a -> m (ReplacedResult a)) +newtype RR m a = RR {unRR :: Scope -> a -> m (ReplacedResult a)} -data ReplacedResult a = Replaced Bool a | NotReplaced Bool -type GenRR m = forall a. Data a => (a -> m (ReplacedResult a)) -newtype RR m a = RR {unRR :: a -> m (ReplacedResult a)} - -runReplace :: (Monad m) => GenRR m -> GenericM m -runReplace f x = do - res <- f x +runReplace :: (Monad m) => Scope -> GenRR m -> GenericM m +runReplace s f x = do + res <- f s x case res of - Replaced True x' -> gmapM (runReplace f) x' - Replaced False x' -> return x' - NotReplaced True -> gmapM (runReplace f) x - NotReplaced False -> return x + ReplacedRecurse s' x' -> gmapM (runReplace s' f) x' + ReplacedNoRecurse x' -> return x' + NotReplacedRecurse s' -> gmapM (runReplace s' f) x + NotReplacedNoRecurse -> return x mkRR :: (Monad m, Typeable a, Typeable b) - => (b -> m (ReplacedResult b)) - -> (a -> m (ReplacedResult a)) -mkRR = extRR (const noReplaceRecurse) + => (Scope -> b -> m (ReplacedResult b)) + -> (Scope -> a -> m (ReplacedResult a)) +mkRR = extRR (\s _ -> noReplaceRecurse s) extRR :: ( Monad m, Typeable a, Typeable b) - => (a -> m (ReplacedResult a)) - -> (b -> m (ReplacedResult b)) - -> (a -> m (ReplacedResult a)) + => (Scope -> a -> m (ReplacedResult a)) + -> (Scope -> b -> m (ReplacedResult b)) + -> (Scope -> a -> m (ReplacedResult a)) extRR def' ext = unRR (RR def' `ext0` RR ext) -replaceRecurse :: Monad m => a -> m (ReplacedResult a) -replaceRecurse = return . Replaced True +replaceRecurse :: Monad m => Scope -> a -> m (ReplacedResult a) +replaceRecurse s = return . ReplacedRecurse s replaceNoRecurse :: Monad m => a -> m (ReplacedResult a) -replaceNoRecurse = return . Replaced False - -noReplace :: Monad m => Bool -> m (ReplacedResult a) -noReplace recurse = return $ NotReplaced recurse +replaceNoRecurse = return . ReplacedNoRecurse -noReplaceRecurse :: Monad m => m (ReplacedResult a) -noReplaceRecurse = noReplace True +noReplaceRecurse :: Monad m => Scope -> m (ReplacedResult a) +noReplaceRecurse = return . NotReplacedRecurse noReplaceNoRecurse :: Monad m => m (ReplacedResult a) -noReplaceNoRecurse = noReplace False +noReplaceNoRecurse = return NotReplacedNoRecurse mkLaTeXLabel :: String -> String mkLaTeXLabel l @@ -118,3 +115,15 @@ isLaTeXRawBlockFmt :: Format -> Bool isLaTeXRawBlockFmt (Format "latex") = True isLaTeXRawBlockFmt (Format "tex") = True isLaTeXRawBlockFmt _ = False + +safeHead :: [a] -> Maybe a +safeHead [] = Nothing +safeHead x = Just $ head x + +unhierarchicalize :: [Element] -> [Block] +unhierarchicalize (Sec l _n attr title body:xs) = Header l attr title : unhierarchicalize body ++ unhierarchicalize xs +unhierarchicalize (Blk bs:xs) = bs : unhierarchicalize xs +unhierarchicalize [] = [] + +newScope :: RefRec -> Scope -> Scope +newScope = (:) From 6cfc90d349511030be40a47c29bfa49a0940efb6 Mon Sep 17 00:00:00 2001 From: Nikolay Yakimov Date: Sat, 2 Mar 2019 03:21:42 +0300 Subject: [PATCH 038/134] Minimal tests for scoping --- test/m2m/scoping/expect.md | 43 +++++++++++++++++++++++ test/m2m/scoping/expect.tex | 70 +++++++++++++++++++++++++++++++++++++ test/m2m/scoping/input.md | 69 ++++++++++++++++++++++++++++++++++++ 3 files changed, 182 insertions(+) create mode 100644 test/m2m/scoping/expect.md create mode 100644 test/m2m/scoping/expect.tex create mode 100644 test/m2m/scoping/input.md diff --git a/test/m2m/scoping/expect.md b/test/m2m/scoping/expect.md new file mode 100644 index 00000000..e4279ac0 --- /dev/null +++ b/test/m2m/scoping/expect.md @@ -0,0 +1,43 @@ +Chapter 1. Section 1 {#sec:1} +==================== + +Section 1.1. Section 1.1 {#sec:11} +------------------------ + +::: {#dfn:group} +A *group* is a pair $(R,*)$ satisfying: + +1. [$*$ is a monoid]{#cl:grpmul} +::: + +Chapter 2. Section 2 {#sec:2} +==================== + +Section 2.1. Section 2.1 {#sec:21} +------------------------ + +### Paragraph 2.1.1. Section 2.1.1 {#sec:211} + +### Paragraph 2.1.2. Section 2.1.2 {#sec:212} + +::: {#dfn:ring} +A *ring* is a triple $(R,+,*)$ satisfying: + +1. [$+$ is an abelian group]{#cl:addgp} +2. [$*$ is a monoid]{#cl:multmon} +3. [$*$ distributes over $+$]{#cl:distrib} +::: + +Chapter 3. Section 3 {#section-3} +==================== + +- chp. 1 +- sec. 1.1 (chp. 1) +- dfn. 1 (sec. 1.1 (chp. 1)) +- cl. 1 (dfn. 1 (sec. 1.1 (chp. 1))) + +- chp. 2 +- dfn. 1 (sec. 2.1.2 (sec. 2.1 (chp. 2))) +- cl. 1 (dfn. 1 (sec. 2.1.2 (sec. 2.1 (chp. 2)))) +- Cl. 2 (dfn. 1 (sec. 2.1.2 (sec. 2.1 (chp. 2)))) +- Cl. 3 (dfn. 1 (sec. 2.1.2 (sec. 2.1 (chp. 2)))) diff --git a/test/m2m/scoping/expect.tex b/test/m2m/scoping/expect.tex new file mode 100644 index 00000000..d02a982e --- /dev/null +++ b/test/m2m/scoping/expect.tex @@ -0,0 +1,70 @@ +\hypertarget{sec:1}{% +\section{\texorpdfstring{\label{sec:1}Section +1}{Section 1}}\label{sec:1}} + +\hypertarget{sec:11}{% +\subsection{\texorpdfstring{\label{sec:11}Section +1.1}{Section 1.1}}\label{sec:11}} + +\leavevmode\hypertarget{dfn:group}{}% +A \emph{group} is a pair \((R,*)\) satisfying: + +\begin{enumerate} +\tightlist +\item + \protect\hypertarget{cl:grpmul}{}{\(*\) is a monoid} +\end{enumerate} + +\hypertarget{sec:2}{% +\section{\texorpdfstring{\label{sec:2}Section +2}{Section 2}}\label{sec:2}} + +\hypertarget{sec:21}{% +\subsection{\texorpdfstring{\label{sec:21}Section +2.1}{Section 2.1}}\label{sec:21}} + +\hypertarget{sec:211}{% +\subsubsection{\texorpdfstring{\label{sec:211}Section +2.1.1}{Section 2.1.1}}\label{sec:211}} + +\hypertarget{sec:212}{% +\subsubsection{\texorpdfstring{\label{sec:212}Section +2.1.2}{Section 2.1.2}}\label{sec:212}} + +\leavevmode\hypertarget{dfn:ring}{}% +A \emph{ring} is a triple \((R,+,*)\) satisfying: + +\begin{enumerate} +\tightlist +\item + \protect\hypertarget{cl:addgp}{}{\(+\) is an abelian group} +\item + \protect\hypertarget{cl:multmon}{}{\(*\) is a monoid} +\item + \protect\hypertarget{cl:distrib}{}{\(*\) distributes over \(+\)} +\end{enumerate} + +\hypertarget{section-3}{% +\section{\texorpdfstring{\label{section-3}Section +3}{Section 3}}\label{section-3}} + +\begin{itemize} +\item + chp.~\ref{sec:1} +\item + sec.~\ref{sec:11} +\item + dfn.~\ref{dfn:group} +\item + cl.~\ref{cl:grpmul} +\item + chp.~\ref{sec:2} +\item + dfn.~\ref{dfn:ring} +\item + cl.~\ref{cl:addgp} +\item + cl.~\ref{cl:multmon} +\item + cl.~\ref{cl:distrib} +\end{itemize} diff --git a/test/m2m/scoping/input.md b/test/m2m/scoping/input.md new file mode 100644 index 00000000..ea546da0 --- /dev/null +++ b/test/m2m/scoping/input.md @@ -0,0 +1,69 @@ +--- +prefixes: + dfn: + ref: ["dfn.", "dfns."] + title: "Definition" + scope: "sec" + referenceIndexTemplate: "$$i$$$$scp# (%)$$" + cl: + ref: ["cl.", "cls."] + scope: "dfn" + referenceIndexTemplate: "$$i$$$$scp# (%)$$" + sec: + captionTemplate: '$$titleName[lvl]% $$$$i$$$$titleDelim$$ $$t$$' + captionIndexTemplate: '$$s%.$$$$i$$' + referenceIndexTemplate: '$$i$$$$scp# (%)$$' + scope: sec + titleName: + - Chapter + - Section + - Paragraph + refTemplate: + - $$Chap[n]$$ + - $$Ref[n]$$ + chap: + - chp. + - chps. + title: Section + titleDelim: '.' +chapters: false +... + +# Section 1 {#sec:1} + +## Section 1.1 {#sec:11} + +
+A _group_ is a pair $(R,*)$ satisfying: + +#. [$*$ is a monoid]{#cl:grpmul} +
+ +# Section 2 {#sec:2} + +## Section 2.1 {#sec:21} + +### Section 2.1.1 {#sec:211} + +### Section 2.1.2 {#sec:212} + +
+A _ring_ is a triple $(R,+,*)$ satisfying: + +#. [$+$ is an abelian group]{#cl:addgp} +#. [$*$ is a monoid]{#cl:multmon} +#. [$*$ distributes over $+$]{#cl:distrib} +
+ +# Section 3 + +- @sec:1 +- @sec:11 +- @dfn:group +- @cl:grpmul + +- @sec:2 +- @dfn:ring +- @cl:addgp +- @Cl:multmon +- @Cl:distrib From 7c19f171e03c50260c6427e147d0ca1d255bf6b6 Mon Sep 17 00:00:00 2001 From: Nikolay Yakimov Date: Sat, 2 Mar 2019 03:23:03 +0300 Subject: [PATCH 039/134] Fix some tests with minimal breakage --- test/m2m/delim/expect.md | 2 +- test/m2m/delim/expect.tex | 4 ++-- test/m2m/equations/expect.md | 2 +- test/m2m/equations/expect.tex | 4 ++-- test/m2m/links-names/expect.md | 4 ++-- test/m2m/links-names/expect.tex | 4 ++-- test/m2m/links/expect.md | 4 ++-- test/m2m/links/expect.tex | 4 ++-- test/m2m/section-template/expect.tex | 20 +++++++++++--------- test/m2m/section-template/input.md | 18 ++++++++++-------- 10 files changed, 35 insertions(+), 31 deletions(-) diff --git a/test/m2m/delim/expect.md b/test/m2m/delim/expect.md index 597d23b6..444cb491 100644 --- a/test/m2m/delim/expect.md +++ b/test/m2m/delim/expect.md @@ -34,7 +34,7 @@ Or in groups eqns. 1ref2last4 Groups will be compacted eqns. 1range4 -Unknown references will print labels eqns. **¿eq:none?**ref1ref3last4 +Unknown references will print labels eq. 1, [@eq:none], eqns. 3pair4 Reference prefix will override default prefix Equation 1, eqns. 3pair4 diff --git a/test/m2m/delim/expect.tex b/test/m2m/delim/expect.tex index cbea60be..832eb2c5 100644 --- a/test/m2m/delim/expect.tex +++ b/test/m2m/delim/expect.tex @@ -36,8 +36,8 @@ Groups will be compacted eqns.~\ref{eq:0}, \ref{eq:1}, \ref{eq:3}, \ref{eq:2} -Unknown references will print labels -eqns.~\ref{eq:0}, \ref{eq:none}, \ref{eq:3}, \ref{eq:2} +Unknown references will print labels eq.~\ref{eq:0}, {[}@eq:none{]}, +eqns.~\ref{eq:3}, \ref{eq:2} Reference prefix will override default prefix Equation \ref{eq:0}, eqns.~\ref{eq:3}, \ref{eq:2} diff --git a/test/m2m/equations/expect.md b/test/m2m/equations/expect.md index 6585dc43..190153d8 100644 --- a/test/m2m/equations/expect.md +++ b/test/m2m/equations/expect.md @@ -34,7 +34,7 @@ Or in groups eqns. 1, 2, 4 Groups will be compacted eqns. 1-4 -Unknown references will print labels eqns. **¿eq:none?**, 1, 3, 4 +Unknown references will print labels eq. 1, [@eq:none], eqns. 3, 4 Reference prefix will override default prefix Equation 1, eqns. 3, 4 diff --git a/test/m2m/equations/expect.tex b/test/m2m/equations/expect.tex index cbea60be..832eb2c5 100644 --- a/test/m2m/equations/expect.tex +++ b/test/m2m/equations/expect.tex @@ -36,8 +36,8 @@ Groups will be compacted eqns.~\ref{eq:0}, \ref{eq:1}, \ref{eq:3}, \ref{eq:2} -Unknown references will print labels -eqns.~\ref{eq:0}, \ref{eq:none}, \ref{eq:3}, \ref{eq:2} +Unknown references will print labels eq.~\ref{eq:0}, {[}@eq:none{]}, +eqns.~\ref{eq:3}, \ref{eq:2} Reference prefix will override default prefix Equation \ref{eq:0}, eqns.~\ref{eq:3}, \ref{eq:2} diff --git a/test/m2m/links-names/expect.md b/test/m2m/links-names/expect.md index 5077c43b..88388a0e 100644 --- a/test/m2m/links-names/expect.md +++ b/test/m2m/links-names/expect.md @@ -35,8 +35,8 @@ Or in groups eqns. [1](#eq:0), [2](#eq:1), [4](#eq:3) Groups will be compacted eqns. [1](#eq:0)-[4](#eq:3) -Unknown references will print labels eqns. **¿eq:none?**, [1](#eq:0), -[3](#eq:2), [4](#eq:3) +Unknown references will print labels [eq. 1](#eq:0), [@eq:none], +eqns. [3](#eq:2), [4](#eq:3) Reference prefix will override default prefix [Equation 1](#eq:0), eqns. [3](#eq:2), [4](#eq:3) diff --git a/test/m2m/links-names/expect.tex b/test/m2m/links-names/expect.tex index cbea60be..832eb2c5 100644 --- a/test/m2m/links-names/expect.tex +++ b/test/m2m/links-names/expect.tex @@ -36,8 +36,8 @@ Groups will be compacted eqns.~\ref{eq:0}, \ref{eq:1}, \ref{eq:3}, \ref{eq:2} -Unknown references will print labels -eqns.~\ref{eq:0}, \ref{eq:none}, \ref{eq:3}, \ref{eq:2} +Unknown references will print labels eq.~\ref{eq:0}, {[}@eq:none{]}, +eqns.~\ref{eq:3}, \ref{eq:2} Reference prefix will override default prefix Equation \ref{eq:0}, eqns.~\ref{eq:3}, \ref{eq:2} diff --git a/test/m2m/links/expect.md b/test/m2m/links/expect.md index fc9b0d1f..fe31332a 100644 --- a/test/m2m/links/expect.md +++ b/test/m2m/links/expect.md @@ -35,8 +35,8 @@ Or in groups eqns. [1](#eq:0), [2](#eq:1), [4](#eq:3) Groups will be compacted eqns. [1](#eq:0)-[4](#eq:3) -Unknown references will print labels eqns. **¿eq:none?**, [1](#eq:0), -[3](#eq:2), [4](#eq:3) +Unknown references will print labels eq. [1](#eq:0), [@eq:none], +eqns. [3](#eq:2), [4](#eq:3) Reference prefix will override default prefix Equation [1](#eq:0), eqns. [3](#eq:2), [4](#eq:3) diff --git a/test/m2m/links/expect.tex b/test/m2m/links/expect.tex index cbea60be..832eb2c5 100644 --- a/test/m2m/links/expect.tex +++ b/test/m2m/links/expect.tex @@ -36,8 +36,8 @@ Groups will be compacted eqns.~\ref{eq:0}, \ref{eq:1}, \ref{eq:3}, \ref{eq:2} -Unknown references will print labels -eqns.~\ref{eq:0}, \ref{eq:none}, \ref{eq:3}, \ref{eq:2} +Unknown references will print labels eq.~\ref{eq:0}, {[}@eq:none{]}, +eqns.~\ref{eq:3}, \ref{eq:2} Reference prefix will override default prefix Equation \ref{eq:0}, eqns.~\ref{eq:3}, \ref{eq:2} diff --git a/test/m2m/section-template/expect.tex b/test/m2m/section-template/expect.tex index 101c9178..8df4679e 100644 --- a/test/m2m/section-template/expect.tex +++ b/test/m2m/section-template/expect.tex @@ -1,19 +1,21 @@ \hypertarget{first-level-section}{% -\section{Chapter 1. First Level Section}\label{first-level-section}} +\section{\texorpdfstring{\label{first-level-section}First Level +Section}{First Level Section}}\label{first-level-section}} \hypertarget{second-level-section}{% -\subsection{Section 1.1. Second Level -Section}\label{second-level-section}} +\subsection{\texorpdfstring{\label{second-level-section}Second Level +Section}{Second Level Section}}\label{second-level-section}} \hypertarget{thrid-level-section}{% -\subsubsection{Paragraph 1.1.1. Thrid Level -Section}\label{thrid-level-section}} +\subsubsection{\texorpdfstring{\label{thrid-level-section}Thrid Level +Section}{Thrid Level Section}}\label{thrid-level-section}} \hypertarget{fourth-level-section}{% -\paragraph{1.1.1.1. Fourth Level Section}\label{fourth-level-section}} +\paragraph{\texorpdfstring{\label{fourth-level-section}Fourth Level +Section}{Fourth Level Section}}\label{fourth-level-section}} \hypertarget{fifth-level-section}{% -\subparagraph{1.1.1.1.1. Fifth Level -Section}\label{fifth-level-section}} +\subparagraph{\texorpdfstring{\label{fifth-level-section}Fifth Level +Section}{Fifth Level Section}}\label{fifth-level-section}} -1.1.1.1.1.1. Sixth Level Section +\label{sixth-level-section}Sixth Level Section diff --git a/test/m2m/section-template/input.md b/test/m2m/section-template/input.md index 4a9d6063..84ce8242 100644 --- a/test/m2m/section-template/input.md +++ b/test/m2m/section-template/input.md @@ -1,12 +1,14 @@ --- -secHeaderTemplate: $$secHeaderPrefix[n]$$$$i$$. $$t$$ -secHeaderPrefix: - - "Chapter " - - "Section " - - "Paragraph " - - "" -sectionsDepth: -1 -numberSections: true +prefixes: + sec: + captionTemplate: $$titleName[lvl]$$$$i$$. $$t$$ + captionIndexTemplate: '$$s%.$$$$i$$' + scope: sec + titleName: + - "Chapter " + - "Section " + - "Paragraph " + - "" --- # First Level Section From a7c057bd9c55fad5880c02e50a04ec0c30b4f8fc Mon Sep 17 00:00:00 2001 From: Nikolay Yakimov Date: Sat, 2 Mar 2019 03:23:39 +0300 Subject: [PATCH 040/134] Update cabalfile --- pandoc-crossref.cabal | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/pandoc-crossref.cabal b/pandoc-crossref.cabal index 952add9d..93b1b752 100644 --- a/pandoc-crossref.cabal +++ b/pandoc-crossref.cabal @@ -4,7 +4,7 @@ cabal-version: 1.12 -- -- see: https://github.com/sol/hpack -- --- hash: b019c9e3e9e85522e4f62ec3b1985acbc6773ca9d58bc8568ecc2f4c2eb93e9e +-- hash: e3ea32bb6edb5ccd9e7c0db0bab27822c16dc6f9f31ea5601642db3bbbfb7609 name: pandoc-crossref version: 0.4.0.0 @@ -55,6 +55,9 @@ data-files: test/m2m/regresssion-219/expect.md test/m2m/regresssion-219/expect.tex test/m2m/regresssion-219/input.md + test/m2m/scoping/expect.md + test/m2m/scoping/expect.tex + test/m2m/scoping/input.md test/m2m/section-template/expect.md test/m2m/section-template/expect.tex test/m2m/section-template/input.md @@ -85,6 +88,7 @@ library Text.Pandoc.CrossRef.References.Blocks Text.Pandoc.CrossRef.References.List Text.Pandoc.CrossRef.References.Refs + Text.Pandoc.CrossRef.References.Subfigures Text.Pandoc.CrossRef.References.Types Text.Pandoc.CrossRef.Util.CodeBlockCaptions Text.Pandoc.CrossRef.Util.CustomLabels @@ -197,6 +201,7 @@ test-suite test-pandoc-crossref Text.Pandoc.CrossRef.References.Blocks Text.Pandoc.CrossRef.References.List Text.Pandoc.CrossRef.References.Refs + Text.Pandoc.CrossRef.References.Subfigures Text.Pandoc.CrossRef.References.Types Text.Pandoc.CrossRef.Util.CodeBlockCaptions Text.Pandoc.CrossRef.Util.CustomLabels From d75667663828b0be74f9acc85fef8ad379151ba3 Mon Sep 17 00:00:00 2001 From: Nikolay Yakimov Date: Sat, 2 Mar 2019 04:15:27 +0300 Subject: [PATCH 041/134] Fix `ref` meta prefix option type to inlines --- lib/Text/Pandoc/CrossRef/Util/Settings.hs | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/lib/Text/Pandoc/CrossRef/Util/Settings.hs b/lib/Text/Pandoc/CrossRef/Util/Settings.hs index 589f1235..19b9d931 100644 --- a/lib/Text/Pandoc/CrossRef/Util/Settings.hs +++ b/lib/Text/Pandoc/CrossRef/Util/Settings.hs @@ -83,12 +83,12 @@ defaultMeta = Settings $ ] <> prefixes' [ "eq" .: [ - "ref" .= ["eq.", "eqns."], + "ref" .= map str ["eq.", "eqns."], "captionTemplate" .= var "i", "listOfTitle" .= header 1 $ text "List of Equations" ], "fig" .: [ - "ref" .= ["fig.", "figs."], + "ref" .= map str ["fig.", "figs."], "title" .= text "Figure", "listOfTitle" .= header 1 $ text "List of Figures" ], @@ -97,17 +97,17 @@ defaultMeta = Settings $ "numbering" .= "alpha a" ], "lst" .: [ - "ref" .= ["lst.", "lsts."], + "ref" .= map str ["lst.", "lsts."], "title" .= text "Listing", "listOfTitle" .= header 1 $ text "List of Listings" ], "tbl" .: [ - "ref" .= ["tbl.", "tbls."], + "ref" .= map str ["tbl.", "tbls."], "title" .= text "Table", "listOfTitle" .= header 1 $ text "List of Tables" ], "sec" .: [ - "ref" .= ["sec.", "secs."], + "ref" .= map str ["sec.", "secs."], "title" .= text "Section", "listOfTitle" .= header 1 $ text "List of Sections" ] From 728a512d243036d76271e3ff9eeecb8b1742e828 Mon Sep 17 00:00:00 2001 From: Nikolay Yakimov Date: Sat, 2 Mar 2019 04:16:13 +0300 Subject: [PATCH 042/134] Add capitalization integrative test --- pandoc-crossref.cabal | 5 ++++- test/m2m/capitalization/expect.md | 19 ++++++++++++++++ test/m2m/capitalization/expect.tex | 36 ++++++++++++++++++++++++++++++ test/m2m/capitalization/input.md | 25 +++++++++++++++++++++ 4 files changed, 84 insertions(+), 1 deletion(-) create mode 100644 test/m2m/capitalization/expect.md create mode 100644 test/m2m/capitalization/expect.tex create mode 100644 test/m2m/capitalization/input.md diff --git a/pandoc-crossref.cabal b/pandoc-crossref.cabal index 93b1b752..172c0186 100644 --- a/pandoc-crossref.cabal +++ b/pandoc-crossref.cabal @@ -4,7 +4,7 @@ cabal-version: 1.12 -- -- see: https://github.com/sol/hpack -- --- hash: e3ea32bb6edb5ccd9e7c0db0bab27822c16dc6f9f31ea5601642db3bbbfb7609 +-- hash: 37debaedf7757f2b50323af19ffaa0b1a750a9e31e925ed0d35bc6e41c92370a name: pandoc-crossref version: 0.4.0.0 @@ -25,6 +25,9 @@ extra-source-files: data-files: docs/demo/demo.md docs/index.md + test/m2m/capitalization/expect.md + test/m2m/capitalization/expect.tex + test/m2m/capitalization/input.md test/m2m/custom-prefixes/expect.md test/m2m/custom-prefixes/expect.tex test/m2m/custom-prefixes/input.md diff --git a/test/m2m/capitalization/expect.md b/test/m2m/capitalization/expect.md new file mode 100644 index 00000000..3f385014 --- /dev/null +++ b/test/m2m/capitalization/expect.md @@ -0,0 +1,19 @@ +[$$eqn\qquad(1)$$]{#eq:1} + +![Figure 1: Image](img.png){#fig:1} + +::: {#tbl:1} + a b + --- --- + c d + + : Table 1: Table +::: + +eq. 1, Eq. 1, fig. 1, Fig. 1, tbl. 1, Tbl. 1 + +eq. 1, Eq. 1, fig. 1, Fig. 1, tbl. 1, Tbl. 1 + +eqs. 1, 1, figs. 1, 1, tbls. 1, 1 + +Eqs. 1, 1, Figs. 1, 1, Tbls. 1, 1 diff --git a/test/m2m/capitalization/expect.tex b/test/m2m/capitalization/expect.tex new file mode 100644 index 00000000..686895e1 --- /dev/null +++ b/test/m2m/capitalization/expect.tex @@ -0,0 +1,36 @@ +\begin{equation}eqn\label{eq:1}\end{equation} + +\begin{figure} +\hypertarget{fig:1}{% +\centering +\includegraphics{img.png} +\caption{Image}\label{fig:1} +} +\end{figure} + +\hypertarget{tbl:1}{} +\begin{longtable}[]{@{}ll@{}} +\caption{\label{tbl:1}Table}\tabularnewline +\toprule +a & b\tabularnewline +\midrule +\endfirsthead +\toprule +a & b\tabularnewline +\midrule +\endhead +c & d\tabularnewline +\bottomrule +\end{longtable} + +eq.~\ref{eq:1}, eq.~\ref{eq:1}, fig.~\ref{fig:1}, fig.~\ref{fig:1}, +tbl.~\ref{tbl:1}, tbl.~\ref{tbl:1} + +eq.~\ref{eq:1}, eq.~\ref{eq:1}, fig.~\ref{fig:1}, fig.~\ref{fig:1}, +tbl.~\ref{tbl:1}, tbl.~\ref{tbl:1} + +eqs.~\ref{eq:1}, \ref{eq:1}, figs.~\ref{fig:1}, \ref{fig:1}, +tbls.~\ref{tbl:1}, \ref{tbl:1} + +eqs.~\ref{eq:1}, \ref{eq:1}, figs.~\ref{fig:1}, \ref{fig:1}, +tbls.~\ref{tbl:1}, \ref{tbl:1} diff --git a/test/m2m/capitalization/input.md b/test/m2m/capitalization/input.md new file mode 100644 index 00000000..1ac6ea1a --- /dev/null +++ b/test/m2m/capitalization/input.md @@ -0,0 +1,25 @@ +--- +prefixes: + eq: + ref: + - eq. + - eqs. +--- + +$$eqn$${#eq:1} + +![Image](img.png){#fig:1} + +| a | b | +|:--|:--| +| c | d | + +: Table {#tbl:1} + +@eq:1, @Eq:1, @fig:1, @Fig:1, @tbl:1, @Tbl:1 + +[@eq:1], [@Eq:1], [@fig:1], [@Fig:1], [@tbl:1], [@Tbl:1] + +[@eq:1; @Eq:1; @fig:1; @Fig:1; @tbl:1; @Tbl:1] + +[@Eq:1; @eq:1; @Fig:1; @fig:1; @Tbl:1; @tbl:1] From 181c43aa23939d78fbeb38e4e41716d71b506972 Mon Sep 17 00:00:00 2001 From: Nikolay Yakimov Date: Sat, 2 Mar 2019 04:30:12 +0300 Subject: [PATCH 043/134] Fix some primary tests; disable subfigure tests for now --- test/test-pandoc-crossref.hs | 201 ++++++++++++++++++----------------- 1 file changed, 102 insertions(+), 99 deletions(-) diff --git a/test/test-pandoc-crossref.hs b/test/test-pandoc-crossref.hs index 131d03c7..b41eea54 100644 --- a/test/test-pandoc-crossref.hs +++ b/test/test-pandoc-crossref.hs @@ -50,46 +50,42 @@ main :: IO () main = hspec $ do describe "References.Blocks.replaceInlines" $ do it "Labels equations" $ - testAll (equation' "a^2+b^2=c^2" "equation") - (spanWith ("eq:equation", [], []) (equation' "a^2+b^2=c^2\\qquad(1)" []), + testAll (plain $ equation' "a^2+b^2=c^2" "equation") + (plain $ spanWith ("eq:equation", [], []) (equation' "a^2+b^2=c^2\\qquad(1)" []), (referenceData =: M.fromList $ refRec'' "eq:equation" 1) . - (pfxCounter =: M.singleton "eq" 1) . - (curChap =: M.singleton "eq" [(1, "1")]) + (pfxCounter =: M.singleton "eq" $ CounterRec {crIndex = 1, crIndexInScope = M.singleton Nothing 1}) ) it "Labels equations in the middle of text" $ - testAll ( + testAll (plain $ text "This is an equation: " <> equation' "a^2+b^2=c^2" "equation" <> text " it should be labeled") - ( + (plain $ text "This is an equation: " <> spanWith ("eq:equation", [], []) (equation' "a^2+b^2=c^2\\qquad(1)" []) <> text " it should be labeled", (referenceData =: M.fromList $ refRec'' "eq:equation" 1) . - (pfxCounter =: M.singleton "eq" 1) . - (curChap =: M.singleton "eq" [(1, "1")]) + (pfxCounter =: M.singleton "eq" $ CounterRec {crIndex = 1, crIndexInScope = M.singleton Nothing 1}) ) it "Labels equations in the beginning of text" $ - testAll ( + testAll (plain $ equation' "a^2+b^2=c^2" "equation" <> text " it should be labeled") - ( + (plain $ spanWith ("eq:equation", [], []) (equation' "a^2+b^2=c^2\\qquad(1)" []) <> text " it should be labeled", (referenceData =: M.fromList $ refRec'' "eq:equation" 1) . - (pfxCounter =: M.singleton "eq" 1) . - (curChap =: M.singleton "eq" [(1, "1")]) + (pfxCounter =: M.singleton "eq" $ CounterRec {crIndex = 1, crIndexInScope = M.singleton Nothing 1}) ) it "Labels equations in the end of text" $ - testAll ( + testAll (plain $ text "This is an equation: " <> equation' "a^2+b^2=c^2" "equation") - ( + (plain $ text "This is an equation: " <> spanWith ("eq:equation", [], []) (equation' "a^2+b^2=c^2\\qquad(1)" []), (referenceData =: M.fromList $ refRec'' "eq:equation" 1) . - (pfxCounter =: M.singleton "eq" 1) . - (curChap =: M.singleton "eq" [(1, "1")]) + (pfxCounter =: M.singleton "eq" $ CounterRec {crIndex = 1, crIndexInScope = M.singleton Nothing 1}) ) -- TODO: @@ -100,69 +96,79 @@ main = hspec $ do it "Labels images" $ testAll (figure "test.jpg" [] "Test figure" "figure") (figure "test.jpg" [] "Figure 1: Test figure" "figure", - (referenceData =: M.fromList $ refRec' "fig:figure" 1 "Test figure") . - (pfxCounter =: M.singleton "fig" 1) . - (curChap =: M.singleton "fig" [(1, "1")]) + (referenceData =: M.fromList $ refRec' "fig:figure" 1 "Test figure" "Figure 1: Test figure") . + (pfxCounter =: M.singleton "fig" $ CounterRec {crIndex = 1, crIndexInScope = M.singleton Nothing 1}) ) - it "Labels subfigures" $ - testAll ( - divWith ("fig:subfigure",[],[]) ( - para (figure' "fig:" "test1.jpg" [] "Test figure 1" "figure1") - <>para (figure' "fig:" "test2.jpg" [] "Test figure 2" "figure2") - <>para (text "figure caption") - ) <> - divWith ("fig:subfigure2",[],[]) ( - para (figure' "fig:" "test21.jpg" [] "Test figure 21" "figure21") - <>para (figure' "fig:" "test22.jpg" [] "Test figure 22" "figure22") - <>para (text "figure caption 2") - ) - ) - ( - divWith ("fig:subfigure",["subfigures"],[]) ( - para (figure' "fig:" "test1.jpg" [] "a" "figure1") - <> para (figure' "fig:" "test2.jpg" [] "b" "figure2") - <> para (text "Figure 1: figure caption. a — Test figure 1, b — Test figure 2") - ) <> - divWith ("fig:subfigure2",["subfigures"],[]) ( - para (figure' "fig:" "test21.jpg" [] "a" "figure21") - <> para (figure' "fig:" "test22.jpg" [] "b" "figure22") - <> para (text "Figure 2: figure caption 2. a — Test figure 21, b — Test figure 22") - ) - , (referenceData =: M.fromList [("fig:figure1",RefRec { - refIndex = [(1,"1")], - refTitle = fromList [Str "Test",Space,Str "figure",Space,Str "1"], - refSubfigure = Just [(1, "a")]}), - ("fig:figure2",RefRec { - refIndex = [(1,"1")], - refTitle = fromList [Str "Test",Space,Str "figure",Space,Str "2"], - refSubfigure = Just [(2, "b")]}), - ("fig:subfigure",RefRec { - refIndex = [(1,"1")], - refTitle = fromList [Str "figure",Space,Str "caption"], - refSubfigure = Nothing}), - ("fig:figure21",RefRec { - refIndex = [(2,"2")], - refTitle = fromList [Str "Test",Space,Str "figure",Space,Str "21"], - refSubfigure = Just [(1, "a")]}), - ("fig:figure22",RefRec { - refIndex = [(2,"2")], - refTitle = fromList [Str "Test",Space,Str "figure",Space,Str "22"], - refSubfigure = Just [(2, "b")]}), - ("fig:subfigure2",RefRec { - refIndex = [(2,"2")], - refTitle = fromList [Str "figure",Space,Str "caption",Space,Str "2"], - refSubfigure = Nothing}) - ] - ) . - (pfxCounter =: M.singleton "fig" 2) . - (curChap =: M.singleton "fig" [(2, "2")]) - ) + -- it "Labels subfigures" $ + -- testAll ( + -- divWith ("fig:subfigure",[],[]) ( + -- para (figure' "fig:" "test1.jpg" [] "Test figure 1" "figure1") + -- <>para (figure' "fig:" "test2.jpg" [] "Test figure 2" "figure2") + -- <>para (text "figure caption") + -- ) <> + -- divWith ("fig:subfigure2",[],[]) ( + -- para (figure' "fig:" "test21.jpg" [] "Test figure 21" "figure21") + -- <>para (figure' "fig:" "test22.jpg" [] "Test figure 22" "figure22") + -- <>para (text "figure caption 2") + -- ) + -- ) + -- ( + -- divWith ("fig:subfigure",["subfigures"],[]) ( + -- para (figure' "fig:" "test1.jpg" [] "a" "figure1") + -- <> para (figure' "fig:" "test2.jpg" [] "b" "figure2") + -- <> para (text "Figure 1: figure caption. a — Test figure 1, b — Test figure 2") + -- ) <> + -- divWith ("fig:subfigure2",["subfigures"],[]) ( + -- para (figure' "fig:" "test21.jpg" [] "a" "figure21") + -- <> para (figure' "fig:" "test22.jpg" [] "b" "figure22") + -- <> para (text "Figure 2: figure caption 2. a — Test figure 21, b — Test figure 22") + -- ) + -- , (referenceData =: M.fromList [("fig:figure1",RefRec { + -- refIndex = [(1,"1")], + -- refTitle = fromList [Str "Test",Space,Str "figure",Space,Str "1"], + -- refScope = Nothing, + -- refLabel = "fig:figure1", + -- refSubfigure = Just [(1, "a")]}), + -- ("fig:figure2",RefRec { + -- refIndex = [(1,"1")], + -- refTitle = fromList [Str "Test",Space,Str "figure",Space,Str "2"], + -- refScope = Nothing, + -- refLabel = "fig:figure2", + -- refSubfigure = Just [(2, "b")]}), + -- ("fig:subfigure",RefRec { + -- refIndex = [(1,"1")], + -- refTitle = fromList [Str "figure",Space,Str "caption"], + -- refScope = Nothing, + -- refLabel = "fig:subfigure", + -- refSubfigure = Nothing}), + -- ("fig:figure21",RefRec { + -- refIndex = [(2,"2")], + -- refTitle = fromList [Str "Test",Space,Str "figure",Space,Str "21"], + -- refScope = Nothing, + -- refLabel = "fig:figure21", + -- refSubfigure = Just [(1, "a")]}), + -- ("fig:figure22",RefRec { + -- refIndex = [(2,"2")], + -- refTitle = fromList [Str "Test",Space,Str "figure",Space,Str "22"], + -- refScope = Nothing, + -- refLabel = "fig:figure22", + -- refSubfigure = Just [(2, "b")]}), + -- ("fig:subfigure2",RefRec { + -- refIndex = [(2,"2")], + -- refTitle = fromList [Str "figure",Space,Str "caption",Space,Str "2"], + -- refScope = Nothing, + -- refLabel = "fig:subfigure2", + -- refSubfigure = Nothing}) + -- ] + -- ) . + -- (pfxCounter =: M.singleton "fig" 2) . + -- (curChap =: M.singleton "fig" "fig:subfigure2") + -- ) it "Labels equations" $ testAll (equation "a^2+b^2=c^2" "equation") (para $ spanWith ("eq:equation", [], []) (equation' "a^2+b^2=c^2\\qquad(1)" []), (referenceData =: M.fromList $ refRec'' "eq:equation" 1) . - (pfxCounter =: M.singleton "eq" 1) . - (curChap =: M.singleton "eq" [(1, "1")]) + (pfxCounter =: M.singleton "eq" $ CounterRec {crIndex = 1, crIndexInScope = M.singleton Nothing 1}) ) it "Labels equations in the middle of text" $ testAll (para $ @@ -174,8 +180,7 @@ main = hspec $ do <> spanWith ("eq:equation", [], []) (equation' "a^2+b^2=c^2\\qquad(1)" []) <> text " it should be labeled", (referenceData =: M.fromList $ refRec'' "eq:equation" 1) . - (pfxCounter =: M.singleton "eq" 1) . - (curChap =: M.singleton "eq" [(1, "1")]) + (pfxCounter =: M.singleton "eq" $ CounterRec {crIndex = 1, crIndexInScope = M.singleton Nothing 1}) ) it "Labels equations in the beginning of text" $ testAll (para $ @@ -185,8 +190,7 @@ main = hspec $ do spanWith ("eq:equation", [], []) (equation' "a^2+b^2=c^2\\qquad(1)" []) <> text " it should be labeled", (referenceData =: M.fromList $ refRec'' "eq:equation" 1) . - (pfxCounter =: M.singleton "eq" 1) . - (curChap =: M.singleton "eq" [(1, "1")]) + (pfxCounter =: M.singleton "eq" $ CounterRec {crIndex = 1, crIndexInScope = M.singleton Nothing 1}) ) it "Labels equations in the end of text" $ testAll (para $ @@ -196,35 +200,31 @@ main = hspec $ do text "This is an equation: " <> spanWith ("eq:equation", [], []) (equation' "a^2+b^2=c^2\\qquad(1)" []), (referenceData =: M.fromList $ refRec'' "eq:equation" 1) . - (pfxCounter =: M.singleton "eq" 1) . - (curChap =: M.singleton "eq" [(1, "1")]) + (pfxCounter =: M.singleton "eq" $ CounterRec {crIndex = 1, crIndexInScope = M.singleton Nothing 1}) ) it "Labels tables" $ testAll (table' "Test table" "table") (divWith ("tbl:table", [], []) $ table' "Table 1: Test table" [], - (referenceData =: M.fromList $ refRec' "tbl:table" 1 "Test table") . - (pfxCounter =: M.singleton "tbl" 1) . - (curChap =: M.singleton "tbl" [(1, "1")]) + (referenceData =: M.fromList $ refRec' "tbl:table" 1 "Test table" "Table 1: Test table") . + (pfxCounter =: M.singleton "tbl" $ CounterRec {crIndex = 1, crIndexInScope = M.singleton Nothing 1}) ) it "Labels code blocks" $ testAll (codeBlock' "Test code block" "codeblock") (codeBlockDiv "Listing 1: Test code block" "codeblock", - (referenceData =: M.fromList $ refRec' "lst:codeblock" 1 "Test code block") . - (pfxCounter =: M.singleton "lst" 1) . - (curChap =: M.singleton "lst" [(1, "1")]) + (referenceData =: M.fromList $ refRec' "lst:codeblock" 1 "Test code block" "Listing 1: Test code block") . + (pfxCounter =: M.singleton "lst" $ CounterRec {crIndex = 1, crIndexInScope = M.singleton Nothing 1}) ) it "Labels code block divs" $ testAll (codeBlockDiv "Test code block" "codeblock") (codeBlockDiv "Listing 1: Test code block" "codeblock", - (referenceData =: M.fromList $ refRec' "lst:codeblock" 1 "Test code block") . - (pfxCounter =: M.singleton "lst" 1) . - (curChap =: M.singleton "lst" [(1, "1")]) + (referenceData =: M.fromList $ refRec' "lst:codeblock" 1 "Test code block" "Listing 1: Test code block") . + (pfxCounter =: M.singleton "lst" $ CounterRec {crIndex = 1, crIndexInScope = M.singleton Nothing 1}) ) it "Labels sections divs" $ testAll (section "Section Header" 1 "section") (section "Section Header" 1 "section", - (referenceData ^= M.fromList (refRec' "sec:section" 1 "Section Header")) . - (curChap ^= M.singleton "sec" [(1,"1")])) + (referenceData ^= M.fromList (refRec' "sec:section" 1 "Section Header" "")) + ) describe "References.Refs.replaceRefs" $ do it "References one image" $ @@ -275,11 +275,11 @@ main = hspec $ do describe "References.List.listOf" $ do it "Generates list of tables" $ testList (rawBlock "latex" "\\listoftables") - (referenceData =: M.fromList $ refRec' "tbl:1" 4 "4" <> refRec' "tbl:2" 5 "5" <> refRec' "tbl:3" 6 "6") + (referenceData =: M.fromList $ refRec' "tbl:1" 4 "4" "Table 4: 4" <> refRec' "tbl:2" 5 "5" "Table 5: 5" <> refRec' "tbl:3" 6 "6" "Table 6: 6") (header 1 (text "List of Tables") <> orderedList ((plain . str . show) `map` [4..6 :: Int])) it "Generates list of figures" $ testList (rawBlock "latex" "\\listoffigures") - (referenceData =: M.fromList $ refRec' "fig:1" 4 "4" <> refRec' "fig:2" 5 "5" <> refRec' "fig:3" 6 "6") + (referenceData =: M.fromList $ refRec' "fig:1" 4 "4" "Figure 4: 4" <> refRec' "fig:2" 5 "5" "Figure 5: 5" <> refRec' "fig:3" 6 "6" "Figure 6: 6") (header 1 (text "List of Figures") <> orderedList ((plain . str . show) `map` [4..6 :: Int])) describe "Util.CodeBlockCaptions" $ @@ -295,7 +295,10 @@ main = hspec $ do let template=Util.Template.makeTemplate (defaultMeta <> Settings (Meta (M.singleton "figureTitle" (toMetaValue $ text "Figure")))) (displayMath "figureTitle" <> displayMath "i" <> displayMath "t") - in Util.Template.applyTemplate (text "1") (text "title") template `shouldBe` + vf "i" = Just $ text "1" + vf "t" = Just $ text "title" + vf _ = Nothing + in Util.Template.applyTemplate vf template `shouldBe` (str "Figure" <> str "1" <> str "title") describe "Citation groups shouldn't be separated (#22 regression test)" $ do @@ -381,14 +384,14 @@ refGen p l1 l2 = M.fromList $ mconcat $ zipWith refRec'' (((uncapitalizeFirst p+ refGen' :: String -> [Int] -> [(Int, Int)] -> M.Map String RefRec refGen' p l1 l2 = M.fromList $ mconcat $ zipWith refRec''' (((uncapitalizeFirst p++) . show) `map` l1) l2 -refRec' :: String -> Int -> String -> [(String, RefRec)] -refRec' ref i tit = [(ref, RefRec{refIndex=[(i,show i)],refTitle=text tit,refSubfigure=Nothing})] +refRec' :: String -> Int -> String -> String -> [(String, RefRec)] +refRec' ref i tit cap = [(ref, RefRec{refIndex=i, refIxInl = str $ show i, refCaption= text cap,refTitle=text tit,refScope=Nothing, refLevel=0, refPfx=takeWhile (/=':') ref, refLabel=ref})] refRec'' :: String -> Int -> [(String, RefRec)] -refRec'' ref i = refRec' ref i [] +refRec'' ref i = refRec' ref i [] (show i) refRec''' :: String -> (Int, Int) -> [(String, RefRec)] -refRec''' ref (c,i) = [(ref, RefRec{refIndex=[(c,show c), (i,show i)],refTitle=text [],refSubfigure=Nothing})] +refRec''' ref (c,i) = [(ref, RefRec{refIndex=c+i,refIxInl = str $ show i, refCaption=str $ show i,refTitle=text [],refScope=Nothing, refLevel=0, refPfx=takeWhile (/=':') ref, refLabel=ref})] testRefs' :: String -> [Int] -> [Int] -> Accessor References (M.Map String RefRec) -> String -> Expectation testRefs' p l1 l2 prop res = testRefs (para $ citeGen p l1) (setVal prop (refGen p l1 l2) def) (para $ text res) @@ -396,7 +399,7 @@ testRefs' p l1 l2 prop res = testRefs (para $ citeGen p l1) (setVal prop (refGen testRefs'' :: String -> [Int] -> [(Int, Int)] -> Accessor References (M.Map String RefRec) -> String -> Expectation testRefs'' p l1 l2 prop res = testRefs (para $ citeGen p l1) (setVal prop (refGen' p l1 l2) def) (para $ text res) -testAll :: (Eq a, Data a, Show a) => Many a -> (Many a, References -> References) -> Expectation +testAll :: Many Block -> (Many Block, References -> References) -> Expectation testAll = testState f def where f = References.Blocks.replaceAll defaultOptions From cc71955003155a1d824d470b7f11a1dd0f87af3f Mon Sep 17 00:00:00 2001 From: Nikolay Yakimov Date: Sat, 2 Mar 2019 06:01:51 +0300 Subject: [PATCH 044/134] Move default prefix config to settings; simplify reference templates --- lib/Text/Pandoc/CrossRef/References/Refs.hs | 8 ++-- lib/Text/Pandoc/CrossRef/Util/Prefixes.hs | 41 +++++++------------ lib/Text/Pandoc/CrossRef/Util/Settings.hs | 5 +++ lib/Text/Pandoc/CrossRef/Util/Settings/Gen.hs | 4 ++ lib/Text/Pandoc/CrossRef/Util/Template.hs | 35 ++++++++-------- test/m2m/scoping/expect.md | 8 ++-- test/m2m/scoping/input.md | 9 ++-- 7 files changed, 53 insertions(+), 57 deletions(-) diff --git a/lib/Text/Pandoc/CrossRef/References/Refs.hs b/lib/Text/Pandoc/CrossRef/References/Refs.hs index 714ae599..7b406d05 100644 --- a/lib/Text/Pandoc/CrossRef/References/Refs.hs +++ b/lib/Text/Pandoc/CrossRef/References/Refs.hs @@ -75,11 +75,11 @@ replaceRefs _ x = return x getRefPrefix :: Options -> String -> Bool -> Int -> Int -> Inlines -> Inlines getRefPrefix opts prefix capitalize num lvl cit = - applyTemplate vf reftempl - where Prefix{prefixRef=refprefixf, prefixReferenceTemplate=reftempl} = fromMaybe undefined $ M.lookup prefix $ prefixes opts - refprefix = applyRefTemplate (refprefixf lvl) capitalize num + applyRefTemplate reftempl vf capitalize + where Prefix{prefixReferenceTemplate=reftempl} = fromMaybe undefined $ M.lookup prefix $ prefixes opts vf "i" = Just cit - vf "p" = Just refprefix + vf "n" = Just $ str $ show num + vf "lvl" = Just $ str $ show lvl vf _ = Nothing replaceRefsLatex :: String -> Options -> [RefData] -> WS Inlines diff --git a/lib/Text/Pandoc/CrossRef/Util/Prefixes.hs b/lib/Text/Pandoc/CrossRef/Util/Prefixes.hs index 5f488756..3dd818a0 100644 --- a/lib/Text/Pandoc/CrossRef/Util/Prefixes.hs +++ b/lib/Text/Pandoc/CrossRef/Util/Prefixes.hs @@ -46,43 +46,30 @@ getPrefixes varN dtv | Just (MetaMap m) <- lookupSettings varN dtv = M.mapWithKey m2p m | otherwise = error "Prefixes not defined" where - var = displayMath - m2p _ (MetaMap kv') = Prefix { - prefixRef = makeRefTemplate kv . - if isJust $ lookupSettings "refTemplate" kv - then fromInlines' . getMetaList (Inlines' . toInlines "refTemplate") "refTemplate" kv - else const $ var "Ref[n]" - -- tryCapitalizeM (\y -> getMetaList (Inlines' . toInlines "ref") y kv) "ref" - , prefixCaptionTemplate = makeTemplate kv $ - if isJust $ lookupSettings "captionTemplate" kv - then getMetaInlines "captionTemplate" kv - else var "title" <> space <> var "i" <> var "titleDelim" <> space <> var "t" - , prefixReferenceTemplate = makeTemplate kv $ - if isJust $ lookupSettings "referenceTemplate" kv - then getMetaInlines "referenceTemplate" kv - else var "p" <> str "\160" <> var "i" + m2p k (MetaMap kv') = Prefix { + prefixCaptionTemplate = makeTemplate kv $ getTemplDefault "captionTemplate" + , prefixReferenceTemplate = makeRefTemplate kv $ getTemplDefault "referenceTemplate" + , prefixReferenceIndexTemplate = makeTemplate kv $ getTemplDefault "referenceIndexTemplate" + , prefixCaptionIndexTemplate = makeTemplate kv $ getTemplDefault "captionIndexTemplate" , prefixScope = getMetaStringList "scope" kv - , prefixNumbering = mkLabel (varN <> "." <> "numbering") (fromMaybe (MetaString "arabic") $ lookupSettings "numbering" kv) + , prefixNumbering = mkLabel (varN <> "." <> k <> "." <> "numbering") + (fromMaybe (MetaString "arabic") $ lookupSettings "numbering" kv) , prefixListOfTitle = getMetaBlock "listOfTitle" kv , prefixTitle = getMetaInlines "title" kv - , prefixReferenceIndexTemplate = makeTemplate kv $ - if isJust $ lookupSettings "referenceIndexTemplate" kv - then getMetaInlines "referenceIndexTemplate" kv - else var "i" <> var "suf" - , prefixCaptionIndexTemplate = makeTemplate kv $ - if isJust $ lookupSettings "captionIndexTemplate" kv - then getMetaInlines "captionIndexTemplate" kv - else var "i" } where kv = Settings (Meta kv') <> dtv + getTemplDefault n = + if isJust $ lookupSettings n kv + then getMetaInlines n kv + else error $ "Template meta variable " <> n <> " not set for " <> varN <> "." <> k + <> ". This should not happen. Please report a bug" m2p k _ = error $ "Invalid value for prefix " <> k type Prefixes = M.Map String Prefix data Prefix = Prefix { - prefixRef :: !(Int -> RefTemplate) - , prefixCaptionTemplate :: !Template - , prefixReferenceTemplate :: !Template + prefixCaptionTemplate :: !Template + , prefixReferenceTemplate :: !RefTemplate , prefixScope :: ![String] , prefixNumbering :: !(Int -> String) , prefixListOfTitle :: !Blocks diff --git a/lib/Text/Pandoc/CrossRef/Util/Settings.hs b/lib/Text/Pandoc/CrossRef/Util/Settings.hs index 19b9d931..7366cb54 100644 --- a/lib/Text/Pandoc/CrossRef/Util/Settings.hs +++ b/lib/Text/Pandoc/CrossRef/Util/Settings.hs @@ -81,6 +81,11 @@ defaultMeta = Settings $ , "listing" .= "lst" , "section" .= "sec" ] + -- these are merely the defaults, can (and will) be overridden in prefix configs + <> captionTemplate (var "title" <> space <> var "i" <> var "titleDelim" <> space <> var "t") + <> referenceTemplate (var "Ref[n][lvl]" <> str "\160" <> var "i") + <> referenceIndexTemplate (var "i" <> var "suf") + <> captionIndexTemplate (var "i") <> prefixes' [ "eq" .: [ "ref" .= map str ["eq.", "eqns."], diff --git a/lib/Text/Pandoc/CrossRef/Util/Settings/Gen.hs b/lib/Text/Pandoc/CrossRef/Util/Settings/Gen.hs index 9a7b9259..4417e5b8 100644 --- a/lib/Text/Pandoc/CrossRef/Util/Settings/Gen.hs +++ b/lib/Text/Pandoc/CrossRef/Util/Settings/Gen.hs @@ -33,6 +33,10 @@ nameDeriveSetters ''Options fmap concat $ mapM (makeAcc . mkName) [ "crossrefYaml" , "titleDelim" + , "captionTemplate" + , "referenceTemplate" + , "referenceIndexTemplate" + , "captionIndexTemplate" ] getOptions :: Settings -> Maybe Format -> Options diff --git a/lib/Text/Pandoc/CrossRef/Util/Template.hs b/lib/Text/Pandoc/CrossRef/Util/Template.hs index 5493ddff..2efa4011 100644 --- a/lib/Text/Pandoc/CrossRef/Util/Template.hs +++ b/lib/Text/Pandoc/CrossRef/Util/Template.hs @@ -37,21 +37,24 @@ import Text.Pandoc.CrossRef.Util.Settings.Types import Control.Applicative import Text.Read import Data.Char (isAlphaNum, isUpper, toLower) -import Control.Monad (join) +import Control.Monad ((<=<)) type VarFunc = String -> Maybe MetaValue newtype Template = Template (VarFunc -> Inlines) -newtype RefTemplate = RefTemplate (Bool -> Int -> Inlines) +newtype RefTemplate = RefTemplate (VarFunc -> Bool -> Inlines) -data State = StFirstVar | StIndex | StAfterIndex | StPrefix | StSuffix -data ParseRes = ParseRes { prVar :: String, prIdx :: Maybe String, prPfx :: String, prSfx :: String } deriving Show +data State = StFirstVar | StIndex | StAfterIndex | StPrefix | StSuffix deriving Eq +data ParseRes = ParseRes { prVar :: String, prIdx :: [String], prPfx :: String, prSfx :: String } deriving Show parse :: State -> String -> ParseRes -parse _ [] = ParseRes [] Nothing [] [] +parse _ [] = ParseRes [] [] [] [] parse StFirstVar cs@(c:_) | isAlphaNum c = let (var, rest) = span isAlphaNum cs in (parse StFirstVar rest){prVar = var} -parse StFirstVar ('[':cs) = let (idx, rest) = span isAlphaNum cs in (parse StIndex rest){prIdx = Just idx} +parse s ('[':cs) + | s == StAfterIndex || s == StFirstVar + = let (idx, rest) = span isAlphaNum cs in (\r -> r{prIdx = idx : prIdx r})(parse StIndex rest) parse StIndex (']':cs) = parse StAfterIndex cs parse StIndex _ = error "Unterminated [ in indexed variable" +parse StAfterIndex ('[':cs) = parse StIndex cs parse _ ('%':cs) = parse StSuffix cs parse _ ('#':cs) = parse StPrefix cs parse StFirstVar s = error $ "Invalid variable name in " <> s @@ -69,28 +72,28 @@ makeTemplate dtv xs' = Template $ \vf -> fromList $ scan (\var -> vf var <|> loo = let replaceVar = maybe mempty (modifier . toInlines ("variable " ++ var)) modifier = (<> text prSfx) . (text prPfx <>) in case prIdx of - Just idxVar -> + [] -> toList $ replaceVar (vf prVar) <> fromList xs + idxVars -> let - idx = readMaybe . toString ("index variable " ++ idxVar) =<< vf idxVar - arr = join $ getList <$> idx <*> vf prVar + idxs :: Maybe [Int] + idxs = mapM (readMaybe . toString ("index variables " ++ show idxVars) <=< vf) idxVars + arr = foldr (\i a -> getList i =<< a) (vf prVar) . reverse =<< idxs in toList $ replaceVar arr <> fromList xs - Nothing -> toList $ replaceVar (vf prVar) <> fromList xs go _ (x:xs) = toList $ singleton x <> fromList xs go _ [] = [] makeRefTemplate :: Settings -> Inlines -> RefTemplate makeRefTemplate dtv xs' = let Template g = makeTemplate dtv xs' - vf _ n "n" = Just $ MetaInlines [Str $ show n] - vf cap _ (vc:vs) + vf cap (vc:vs) | isUpper vc && cap = capitalize (`lookupSettings` dtv) var | otherwise = lookupSettings var dtv where var = toLower vc : vs - vf _ _ [] = error "Empty variable name" - in RefTemplate $ \cap n -> g (vf cap n) + vf _ [] = error "Empty variable name" + in RefTemplate $ \vars cap -> g (\v -> vars v <|> vf cap v) -applyRefTemplate :: RefTemplate -> Bool -> Int -> Inlines -applyRefTemplate (RefTemplate g) = g +applyRefTemplate :: RefTemplate -> (String -> Maybe Inlines) -> Bool -> Inlines +applyRefTemplate (RefTemplate g) vars cap = g (fmap (MetaInlines . toList) . vars) cap applyTemplate :: (String -> Maybe Inlines) -> Template -> Inlines applyTemplate vars (Template g) = g $ fmap (MetaInlines . toList) . vars diff --git a/test/m2m/scoping/expect.md b/test/m2m/scoping/expect.md index e4279ac0..9ff19471 100644 --- a/test/m2m/scoping/expect.md +++ b/test/m2m/scoping/expect.md @@ -37,7 +37,7 @@ Chapter 3. Section 3 {#section-3} - cl. 1 (dfn. 1 (sec. 1.1 (chp. 1))) - chp. 2 -- dfn. 1 (sec. 2.1.2 (sec. 2.1 (chp. 2))) -- cl. 1 (dfn. 1 (sec. 2.1.2 (sec. 2.1 (chp. 2)))) -- Cl. 2 (dfn. 1 (sec. 2.1.2 (sec. 2.1 (chp. 2)))) -- Cl. 3 (dfn. 1 (sec. 2.1.2 (sec. 2.1 (chp. 2)))) +- dfn. 1 (par. 2.1.2 (sec. 2.1 (chp. 2))) +- cl. 1 (dfn. 1 (par. 2.1.2 (sec. 2.1 (chp. 2)))) +- Cl. 2 (dfn. 1 (par. 2.1.2 (sec. 2.1 (chp. 2)))) +- Cl. 3 (dfn. 1 (par. 2.1.2 (sec. 2.1 (chp. 2)))) diff --git a/test/m2m/scoping/input.md b/test/m2m/scoping/input.md index ea546da0..b19919f9 100644 --- a/test/m2m/scoping/input.md +++ b/test/m2m/scoping/input.md @@ -18,12 +18,9 @@ prefixes: - Chapter - Section - Paragraph - refTemplate: - - $$Chap[n]$$ - - $$Ref[n]$$ - chap: - - chp. - - chps. + ref: + - ["chp.", "sec.", "par."] + - ["chps.", "secs.", "pars."] title: Section titleDelim: '.' chapters: false From f5a0b29996fff77fe2e3d1c7ad130bd5387da975 Mon Sep 17 00:00:00 2001 From: Nikolay Yakimov Date: Sat, 2 Mar 2019 06:37:58 +0300 Subject: [PATCH 045/134] Lints --- lib/Text/Pandoc/CrossRef/Util/Template.hs | 4 ++-- test/test-pandoc-crossref.hs | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/lib/Text/Pandoc/CrossRef/Util/Template.hs b/lib/Text/Pandoc/CrossRef/Util/Template.hs index 2efa4011..9d76b5d1 100644 --- a/lib/Text/Pandoc/CrossRef/Util/Template.hs +++ b/lib/Text/Pandoc/CrossRef/Util/Template.hs @@ -77,7 +77,7 @@ makeTemplate dtv xs' = Template $ \vf -> fromList $ scan (\var -> vf var <|> loo let idxs :: Maybe [Int] idxs = mapM (readMaybe . toString ("index variables " ++ show idxVars) <=< vf) idxVars - arr = foldr (\i a -> getList i =<< a) (vf prVar) . reverse =<< idxs + arr = foldr (\i a -> getList i =<< a) (vf prVar) . reverse =<< idxs in toList $ replaceVar arr <> fromList xs go _ (x:xs) = toList $ singleton x <> fromList xs go _ [] = [] @@ -93,7 +93,7 @@ makeRefTemplate dtv xs' = in RefTemplate $ \vars cap -> g (\v -> vars v <|> vf cap v) applyRefTemplate :: RefTemplate -> (String -> Maybe Inlines) -> Bool -> Inlines -applyRefTemplate (RefTemplate g) vars cap = g (fmap (MetaInlines . toList) . vars) cap +applyRefTemplate (RefTemplate g) vars = g (fmap (MetaInlines . toList) . vars) applyTemplate :: (String -> Maybe Inlines) -> Template -> Inlines applyTemplate vars (Template g) = g $ fmap (MetaInlines . toList) . vars diff --git a/test/test-pandoc-crossref.hs b/test/test-pandoc-crossref.hs index b41eea54..29606765 100644 --- a/test/test-pandoc-crossref.hs +++ b/test/test-pandoc-crossref.hs @@ -223,7 +223,7 @@ main = hspec $ do it "Labels sections divs" $ testAll (section "Section Header" 1 "section") (section "Section Header" 1 "section", - (referenceData ^= M.fromList (refRec' "sec:section" 1 "Section Header" "")) + referenceData ^= M.fromList (refRec' "sec:section" 1 "Section Header" "") ) describe "References.Refs.replaceRefs" $ do From c7b0e1c38e29e9f5d147e1797ec000b03bbefe37 Mon Sep 17 00:00:00 2001 From: Nikolay Yakimov Date: Sat, 2 Mar 2019 14:36:05 +0300 Subject: [PATCH 046/134] Let numbering type depend on scope level; move default to settings --- lib/Text/Pandoc/CrossRef/References/Blocks.hs | 5 +++-- lib/Text/Pandoc/CrossRef/Util/Prefixes.hs | 15 ++++++++++----- lib/Text/Pandoc/CrossRef/Util/Settings.hs | 1 + lib/Text/Pandoc/CrossRef/Util/Settings/Gen.hs | 1 + 4 files changed, 15 insertions(+), 7 deletions(-) diff --git a/lib/Text/Pandoc/CrossRef/References/Blocks.hs b/lib/Text/Pandoc/CrossRef/References/Blocks.hs index 2714bb29..52b4a342 100644 --- a/lib/Text/Pandoc/CrossRef/References/Blocks.hs +++ b/lib/Text/Pandoc/CrossRef/References/Blocks.hs @@ -233,7 +233,6 @@ replaceAttr :: Options -> Scope -> Either String String -> Maybe String -> B.Inl replaceAttr o scope label refLabel' title pfx = do let ropt = getPfx o pfx - customLabel = prefixNumbering ropt itemScope = find ((`elem` prefixScope ropt) . refPfx) scope cr <- (\CounterRec{..} -> CounterRec{ crIndex = crIndex+1 @@ -243,6 +242,8 @@ replaceAttr o scope label refLabel' title pfx let label' = either (++ ':':'\0':show i) id label iInSc = fromJust $ M.lookup itemScope $ crIndexInScope cr i = crIndex cr + lvl = length $ filter ((== pfx) . refPfx) scope + customLabel = prefixNumbering ropt lvl hasLabel <- M.member label' <$> get referenceData when hasLabel $ error $ "Duplicate label: " ++ label' let rec' = RefRec { @@ -251,7 +252,7 @@ replaceAttr o scope label refLabel' title pfx , refLabel = label' , refIxInl = applyTitleIndexTemplate o rec' $ B.text $ fromMaybe (customLabel iInSc) refLabel' , refScope = itemScope - , refLevel = length $ filter ((== pfx) . refPfx) scope + , refLevel = lvl , refPfx = pfx , refCaption = applyTitleTemplate o rec' } diff --git a/lib/Text/Pandoc/CrossRef/Util/Prefixes.hs b/lib/Text/Pandoc/CrossRef/Util/Prefixes.hs index 3dd818a0..7fcafda6 100644 --- a/lib/Text/Pandoc/CrossRef/Util/Prefixes.hs +++ b/lib/Text/Pandoc/CrossRef/Util/Prefixes.hs @@ -52,17 +52,22 @@ getPrefixes varN dtv , prefixReferenceIndexTemplate = makeTemplate kv $ getTemplDefault "referenceIndexTemplate" , prefixCaptionIndexTemplate = makeTemplate kv $ getTemplDefault "captionIndexTemplate" , prefixScope = getMetaStringList "scope" kv - , prefixNumbering = mkLabel (varN <> "." <> k <> "." <> "numbering") - (fromMaybe (MetaString "arabic") $ lookupSettings "numbering" kv) , prefixListOfTitle = getMetaBlock "listOfTitle" kv + , prefixNumbering = \lvl -> + let prettyVarName = varN <> "." <> k <> "." <> varName + varName = "numbering" + in mkLabel prettyVarName + (fromMaybe (reportError prettyVarName "Numbering") + $ lookupSettings varName kv >>= getList lvl) , prefixTitle = getMetaInlines "title" kv } where kv = Settings (Meta kv') <> dtv getTemplDefault n = if isJust $ lookupSettings n kv then getMetaInlines n kv - else error $ "Template meta variable " <> n <> " not set for " <> varN <> "." <> k - <> ". This should not happen. Please report a bug" + else reportError n "Template" + reportError n what = error $ what <> " meta variable " <> n <> " not set for " + <> varN <> "." <> k <> ". This should not happen. Please report a bug" m2p k _ = error $ "Invalid value for prefix " <> k type Prefixes = M.Map String Prefix @@ -71,8 +76,8 @@ data Prefix = Prefix { prefixCaptionTemplate :: !Template , prefixReferenceTemplate :: !RefTemplate , prefixScope :: ![String] - , prefixNumbering :: !(Int -> String) , prefixListOfTitle :: !Blocks + , prefixNumbering :: !(Int -> Int -> String) , prefixReferenceIndexTemplate :: !Template , prefixCaptionIndexTemplate :: !Template -- Used for LaTeX metadata; the same value is used in diff --git a/lib/Text/Pandoc/CrossRef/Util/Settings.hs b/lib/Text/Pandoc/CrossRef/Util/Settings.hs index 7366cb54..88cef8ec 100644 --- a/lib/Text/Pandoc/CrossRef/Util/Settings.hs +++ b/lib/Text/Pandoc/CrossRef/Util/Settings.hs @@ -86,6 +86,7 @@ defaultMeta = Settings $ <> referenceTemplate (var "Ref[n][lvl]" <> str "\160" <> var "i") <> referenceIndexTemplate (var "i" <> var "suf") <> captionIndexTemplate (var "i") + <> numbering "arabic" <> prefixes' [ "eq" .: [ "ref" .= map str ["eq.", "eqns."], diff --git a/lib/Text/Pandoc/CrossRef/Util/Settings/Gen.hs b/lib/Text/Pandoc/CrossRef/Util/Settings/Gen.hs index 4417e5b8..8b2a0c74 100644 --- a/lib/Text/Pandoc/CrossRef/Util/Settings/Gen.hs +++ b/lib/Text/Pandoc/CrossRef/Util/Settings/Gen.hs @@ -37,6 +37,7 @@ fmap concat $ mapM (makeAcc . mkName) , "referenceTemplate" , "referenceIndexTemplate" , "captionIndexTemplate" + , "numbering" ] getOptions :: Settings -> Maybe Format -> Options From 2d704af604e285b31e5f351d2cf21c972238c3db Mon Sep 17 00:00:00 2001 From: Nikolay Yakimov Date: Sat, 2 Mar 2019 14:38:51 +0300 Subject: [PATCH 047/134] Make listOfTitle into a template, too --- lib/Text/Pandoc/CrossRef/Util/Options.hs | 2 +- lib/Text/Pandoc/CrossRef/Util/Prefixes.hs | 4 +-- lib/Text/Pandoc/CrossRef/Util/Settings.hs | 19 +++++--------- lib/Text/Pandoc/CrossRef/Util/Settings/Gen.hs | 1 + lib/Text/Pandoc/CrossRef/Util/Template.hs | 25 ++++++++++++++++--- 5 files changed, 31 insertions(+), 20 deletions(-) diff --git a/lib/Text/Pandoc/CrossRef/Util/Options.hs b/lib/Text/Pandoc/CrossRef/Util/Options.hs index 169a94fb..76fed66b 100644 --- a/lib/Text/Pandoc/CrossRef/Util/Options.hs +++ b/lib/Text/Pandoc/CrossRef/Util/Options.hs @@ -80,4 +80,4 @@ getRefLabel opts ils getRefLabel _ _ = Nothing getTitleForListOf :: Options -> String -> Blocks -getTitleForListOf opts = prefixListOfTitle . getPfx opts +getTitleForListOf opts = applyBlockTemplate (const Nothing) . prefixListOfTitle . getPfx opts diff --git a/lib/Text/Pandoc/CrossRef/Util/Prefixes.hs b/lib/Text/Pandoc/CrossRef/Util/Prefixes.hs index 7fcafda6..d5ba9fff 100644 --- a/lib/Text/Pandoc/CrossRef/Util/Prefixes.hs +++ b/lib/Text/Pandoc/CrossRef/Util/Prefixes.hs @@ -52,13 +52,13 @@ getPrefixes varN dtv , prefixReferenceIndexTemplate = makeTemplate kv $ getTemplDefault "referenceIndexTemplate" , prefixCaptionIndexTemplate = makeTemplate kv $ getTemplDefault "captionIndexTemplate" , prefixScope = getMetaStringList "scope" kv - , prefixListOfTitle = getMetaBlock "listOfTitle" kv , prefixNumbering = \lvl -> let prettyVarName = varN <> "." <> k <> "." <> varName varName = "numbering" in mkLabel prettyVarName (fromMaybe (reportError prettyVarName "Numbering") $ lookupSettings varName kv >>= getList lvl) + , prefixListOfTitle = makeBlockTemplate kv $ getMetaBlock "listOfTitle" kv , prefixTitle = getMetaInlines "title" kv } where kv = Settings (Meta kv') <> dtv @@ -76,8 +76,8 @@ data Prefix = Prefix { prefixCaptionTemplate :: !Template , prefixReferenceTemplate :: !RefTemplate , prefixScope :: ![String] - , prefixListOfTitle :: !Blocks , prefixNumbering :: !(Int -> Int -> String) + , prefixListOfTitle :: !BlockTemplate , prefixReferenceIndexTemplate :: !Template , prefixCaptionIndexTemplate :: !Template -- Used for LaTeX metadata; the same value is used in diff --git a/lib/Text/Pandoc/CrossRef/Util/Settings.hs b/lib/Text/Pandoc/CrossRef/Util/Settings.hs index 88cef8ec..a3bf8ecf 100644 --- a/lib/Text/Pandoc/CrossRef/Util/Settings.hs +++ b/lib/Text/Pandoc/CrossRef/Util/Settings.hs @@ -87,35 +87,28 @@ defaultMeta = Settings $ <> referenceIndexTemplate (var "i" <> var "suf") <> captionIndexTemplate (var "i") <> numbering "arabic" + <> listOfTitle (header 1 $ text "List of $$title$$s") <> prefixes' [ "eq" .: [ "ref" .= map str ["eq.", "eqns."], "captionTemplate" .= var "i", - "listOfTitle" .= header 1 $ text "List of Equations" + "title" .= "Equation" ], "fig" .: [ "ref" .= map str ["fig.", "figs."], - "title" .= text "Figure", - "listOfTitle" .= header 1 $ text "List of Figures" - ], - "subfig" .: [ - "captionTemplate" .= var "i", - "numbering" .= "alpha a" + "title" .= text "Figure" ], "lst" .: [ "ref" .= map str ["lst.", "lsts."], - "title" .= text "Listing", - "listOfTitle" .= header 1 $ text "List of Listings" + "title" .= text "Listing" ], "tbl" .: [ "ref" .= map str ["tbl.", "tbls."], - "title" .= text "Table", - "listOfTitle" .= header 1 $ text "List of Tables" + "title" .= text "Table" ], "sec" .: [ "ref" .= map str ["sec.", "secs."], - "title" .= text "Section", - "listOfTitle" .= header 1 $ text "List of Sections" + "title" .= text "Section" ] ] where var = displayMath diff --git a/lib/Text/Pandoc/CrossRef/Util/Settings/Gen.hs b/lib/Text/Pandoc/CrossRef/Util/Settings/Gen.hs index 8b2a0c74..96fe7b75 100644 --- a/lib/Text/Pandoc/CrossRef/Util/Settings/Gen.hs +++ b/lib/Text/Pandoc/CrossRef/Util/Settings/Gen.hs @@ -38,6 +38,7 @@ fmap concat $ mapM (makeAcc . mkName) , "referenceIndexTemplate" , "captionIndexTemplate" , "numbering" + , "listOfTitle" ] getOptions :: Settings -> Maybe Format -> Options diff --git a/lib/Text/Pandoc/CrossRef/Util/Template.hs b/lib/Text/Pandoc/CrossRef/Util/Template.hs index 9d76b5d1..15f35a55 100644 --- a/lib/Text/Pandoc/CrossRef/Util/Template.hs +++ b/lib/Text/Pandoc/CrossRef/Util/Template.hs @@ -23,10 +23,13 @@ with this program; if not, write to the Free Software Foundation, Inc., module Text.Pandoc.CrossRef.Util.Template ( Template , RefTemplate + , BlockTemplate , makeTemplate + , makeBlockTemplate , makeRefTemplate , applyTemplate , applyRefTemplate + , applyBlockTemplate ) where import Text.Pandoc.Definition @@ -38,20 +41,27 @@ import Control.Applicative import Text.Read import Data.Char (isAlphaNum, isUpper, toLower) import Control.Monad ((<=<)) +import Data.Data (Data) type VarFunc = String -> Maybe MetaValue newtype Template = Template (VarFunc -> Inlines) newtype RefTemplate = RefTemplate (VarFunc -> Bool -> Inlines) +newtype BlockTemplate = BlockTemplate (VarFunc -> Blocks) data State = StFirstVar | StIndex | StAfterIndex | StPrefix | StSuffix deriving Eq data ParseRes = ParseRes { prVar :: String, prIdx :: [String], prPfx :: String, prSfx :: String } deriving Show +isVariableSym :: Char -> Bool +isVariableSym '.' = True +isVariableSym '_' = True +isVariableSym c = isAlphaNum c + parse :: State -> String -> ParseRes parse _ [] = ParseRes [] [] [] [] -parse StFirstVar cs@(c:_) | isAlphaNum c = let (var, rest) = span isAlphaNum cs in (parse StFirstVar rest){prVar = var} +parse StFirstVar cs@(c:_) | isVariableSym c = let (var, rest) = span isVariableSym cs in (parse StFirstVar rest){prVar = var} parse s ('[':cs) | s == StAfterIndex || s == StFirstVar - = let (idx, rest) = span isAlphaNum cs in (\r -> r{prIdx = idx : prIdx r})(parse StIndex rest) + = let (idx, rest) = span isVariableSym cs in (\r -> r{prIdx = idx : prIdx r})(parse StIndex rest) parse StIndex (']':cs) = parse StAfterIndex cs parse StIndex _ = error "Unterminated [ in indexed variable" parse StAfterIndex ('[':cs) = parse StIndex cs @@ -64,9 +74,13 @@ parse StSuffix cs = let (sfx, rest) = span (`notElem` "%#") cs in (parse StSuffi makeTemplate :: Settings -> Inlines -> Template makeTemplate dtv xs' = Template $ \vf -> fromList $ scan (\var -> vf var <|> lookupSettings var dtv) $ toList xs' + +makeBlockTemplate :: Settings -> Blocks -> BlockTemplate +makeBlockTemplate dtv xs' = BlockTemplate $ \vf -> fromList $ scan (\var -> vf var <|> lookupSettings var dtv) $ toList xs' + +scan :: (Data a) => (String -> Maybe MetaValue) -> [a] -> [a] +scan = bottomUp . go where - scan :: (String -> Maybe MetaValue) -> [Inline] -> [Inline] - scan = bottomUp . go go vf (Math DisplayMath var:xs) | ParseRes{..} <- parse StFirstVar var = let replaceVar = maybe mempty (modifier . toInlines ("variable " ++ var)) @@ -97,3 +111,6 @@ applyRefTemplate (RefTemplate g) vars = g (fmap (MetaInlines . toList) . vars) applyTemplate :: (String -> Maybe Inlines) -> Template -> Inlines applyTemplate vars (Template g) = g $ fmap (MetaInlines . toList) . vars + +applyBlockTemplate :: VarFunc -> BlockTemplate -> Blocks +applyBlockTemplate vars (BlockTemplate g) = g vars From 4209dd1d9189081c7fcc35229a0af2e65e9c9c3a Mon Sep 17 00:00:00 2001 From: Nikolay Yakimov Date: Sat, 2 Mar 2019 14:41:01 +0300 Subject: [PATCH 048/134] Unify template variable interface --- lib/Text/Pandoc/CrossRef/References/Blocks.hs | 27 ++------ lib/Text/Pandoc/CrossRef/References/Refs.hs | 69 ++++++++----------- lib/Text/Pandoc/CrossRef/Util/Settings.hs | 4 +- lib/Text/Pandoc/CrossRef/Util/VarFunction.hs | 42 +++++++++++ pandoc-crossref.cabal | 4 +- test/m2m/scoping/input.md | 8 +-- test/m2m/section-template/input.md | 2 +- 7 files changed, 87 insertions(+), 69 deletions(-) create mode 100644 lib/Text/Pandoc/CrossRef/Util/VarFunction.hs diff --git a/lib/Text/Pandoc/CrossRef/References/Blocks.hs b/lib/Text/Pandoc/CrossRef/References/Blocks.hs index 52b4a342..7deed9d2 100644 --- a/lib/Text/Pandoc/CrossRef/References/Blocks.hs +++ b/lib/Text/Pandoc/CrossRef/References/Blocks.hs @@ -18,7 +18,7 @@ with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -} -{-# LANGUAGE Rank2Types, MultiWayIf, RecordWildCards #-} +{-# LANGUAGE Rank2Types, MultiWayIf, RecordWildCards, NamedFieldPuns #-} module Text.Pandoc.CrossRef.References.Blocks ( replaceAll ) where @@ -39,6 +39,7 @@ import Text.Pandoc.CrossRef.Util.Options import Text.Pandoc.CrossRef.Util.Prefixes import Text.Pandoc.CrossRef.Util.Template import Text.Pandoc.CrossRef.Util.CodeBlockCaptions +import Text.Pandoc.CrossRef.Util.VarFunction import Control.Applicative import Data.Default (def) import Prelude @@ -169,31 +170,15 @@ replaceInline opts scope x@(Span (label,_,attrs) _content) replaceInline _ scope _ = noReplaceRecurse scope applyTitleTemplate :: Options -> RefRec -> B.Inlines -applyTitleTemplate opts rr@RefRec{..} = - applyTemplate vf $ pfxCaptionTemplate opts refPfx - where - vf x = case x of - "i" -> Just refIxInl - _ -> titleVarFunc opts rr x +applyTitleTemplate opts rr@RefRec{refPfx} = + applyTemplate (fix defaultVarFunc rr) $ pfxCaptionTemplate opts refPfx applyTitleIndexTemplate :: Options -> RefRec -> B.Inlines -> B.Inlines applyTitleIndexTemplate opts rr@RefRec{..} label = applyTemplate vf $ pfxCaptionIndexTemplate opts refPfx where - vf x = case x of - "i" -> Just label - _ -> titleVarFunc opts rr x - -titleVarFunc :: Options -> RefRec -> String -> Maybe B.Inlines -titleVarFunc opts RefRec{..} x = case x of - "t" -> Just refTitle - "lvl" -> Just $ B.str $ show refLevel - _ -> case refScope of - Just rs -> case x of - "s" -> Just $ Types.refIxInl rs - "scp" -> Just $ applyTitleTemplate opts rs - _ -> Nothing - _ -> Nothing + vf "i" = Just label + vf x = fix defaultVarFunc rr x divBlocks :: Options -> Block -> Block divBlocks opts (Table title align widths header cells) diff --git a/lib/Text/Pandoc/CrossRef/References/Refs.hs b/lib/Text/Pandoc/CrossRef/References/Refs.hs index 7b406d05..73c62200 100644 --- a/lib/Text/Pandoc/CrossRef/References/Refs.hs +++ b/lib/Text/Pandoc/CrossRef/References/Refs.hs @@ -38,6 +38,7 @@ import Text.Pandoc.CrossRef.Util.Template import Text.Pandoc.CrossRef.Util.Util import Text.Pandoc.CrossRef.Util.Options hiding (getRefPrefix) import Text.Pandoc.CrossRef.Util.Prefixes +import Text.Pandoc.CrossRef.Util.VarFunction import Control.Applicative import Debug.Trace import Prelude @@ -73,14 +74,13 @@ replaceRefs opts ils | otherwise = replaceRefsOther replaceRefs _ x = return x -getRefPrefix :: Options -> String -> Bool -> Int -> Int -> Inlines -> Inlines -getRefPrefix opts prefix capitalize num lvl cit = +getRefPrefix :: Options -> Bool -> Int -> RefRec -> Inlines -> Inlines +getRefPrefix opts capitalize num rr@RefRec{..} cit = applyRefTemplate reftempl vf capitalize - where Prefix{prefixReferenceTemplate=reftempl} = fromMaybe undefined $ M.lookup prefix $ prefixes opts - vf "i" = Just cit + where Prefix{prefixReferenceTemplate=reftempl} = fromMaybe undefined $ M.lookup refPfx $ prefixes opts + vf "rs" = Just cit vf "n" = Just $ str $ show num - vf "lvl" = Just $ str $ show lvl - vf _ = Nothing + vf x = fix defaultVarFunc rr x replaceRefsLatex :: String -> Options -> [RefData] -> WS Inlines replaceRefsLatex prefix opts cits @@ -99,16 +99,15 @@ replaceRefsLatex' prefix opts cits = cref'++"{"++listLabels prefix "" "," "" cits++"}" else listLabels prefix "\\ref{" ", " "}" cits - suppressPrefix = all rdSuppresPrefix cits - noPrefix = all isNothing $ map rdCitPrefix cits + RefDataComplete{..} = head cits p | cref opts = id - | suppressPrefix + | rdSuppressPrefix = id - | noPrefix - = getRefPrefix opts prefix cap (length cits - 1) (fromMaybe 0 . rdLvl $ head cits) - | otherwise = ((fromJust (rdCitPrefix (head cits)) <> space) <>) + | isNothing rdCitPrefix + = getRefPrefix opts cap (length cits - 1) rdRec + | otherwise = ((fromJust rdCitPrefix <> space) <>) cap = maybe False isFirstUpper $ getLabelPrefix opts . rdLabel . head $ cits - cref' | suppressPrefix = "\\labelcref" + cref' | rdSuppressPrefix = "\\labelcref" | cap = "\\Cref" | otherwise = "\\cref" @@ -127,18 +126,17 @@ replaceRefsOther prefix opts cits = intercalate' (text ", ") <$> mapM (replaceRefsOther' prefix opts) (groupBy citationGroupPred cits) citationGroupPred :: RefData -> RefData -> Bool -citationGroupPred = (==) `on` liftM2 (,) rdCitPrefix rdSuppresPrefix +citationGroupPred = (==) `on` liftM2 (,) rdCitPrefix rdSuppressPrefix replaceRefsOther' :: String -> Options -> [RefData] -> WS Inlines -replaceRefsOther' prefix opts indices = do +replaceRefsOther' _prefix opts indices = do let - firstRef@RefDataComplete{..} = head indices + RefDataComplete{..} = head indices cap = rdUpperCase - depth = fromMaybe 0 $ rdLvl firstRef - writePrefix | rdSuppresPrefix + writePrefix | rdSuppressPrefix = id | isNothing rdCitPrefix - = cmap $ getRefPrefix opts prefix cap (length indices - 1) depth + = cmap $ getRefPrefix opts cap (length indices - 1) rdRec | otherwise = cmap ((fromJust rdCitPrefix <> space) <>) cmap f x @@ -157,7 +155,7 @@ data RefData = RefDataIncomplete , rdSuffix :: Inlines , rdCitPrefix :: Maybe Inlines , rdUpperCase :: Bool - , rdSuppresPrefix :: Bool + , rdSuppressPrefix :: Bool } deriving (Eq, Show) rdIdx :: RefData -> Maybe Int @@ -172,10 +170,6 @@ rdPrefix :: RefData -> Maybe String rdPrefix RefDataIncomplete{} = Nothing rdPrefix RefDataComplete{rdRec} = Just $ refPfx rdRec -rdLvl :: RefData -> Maybe Int -rdLvl RefDataIncomplete{} = Nothing -rdLvl RefDataComplete{rdRec} = Just $ refLevel rdRec - rdLabel :: RefData -> String rdLabel RefDataIncomplete{rdiLabel} = rdiLabel rdLabel RefDataComplete{rdRec} = refLabel rdRec @@ -200,7 +194,7 @@ getRefData c@Citation{..} then Nothing else Just $ fromList citationPrefix , rdUpperCase = isFirstUpper citationId - , rdSuppresPrefix = SuppressAuthor == citationMode + , rdSuppressPrefix = SuppressAuthor == citationMode } where llab = uncapitalizeFirst citationId suf' = fromList citationSuffix @@ -244,19 +238,14 @@ makeIndices o s = format $ concatMap f $ HT.groupBy g $ sort $ nub s <> ". This should not be possible, please report a bug") applyIndexTemplate :: Options -> Many Inline -> RefRec -> Inlines -applyIndexTemplate opts suf RefRec{..} = - let vars x = case x of - "i" -> Just refIxInl - "suf" -> Just suf - _ -> case refScope of - Just v -> case x of - "s" -> Just $ applyIndexTemplate opts mempty v - "scp" -> Just $ inlines False v - "Scp" -> Just $ inlines True v - _ -> Nothing - _ -> Nothing +applyIndexTemplate opts suf rr = + let varsSc rr' "ref" = Just $ inlines False rr' + varsSc rr' "Ref" = Just $ inlines True rr' + varsSc rr' x = defaultVarFunc varsSc rr' x + vars _ "suf" = Just suf + vars rr' x = defaultVarFunc varsSc rr' x template = prefixReferenceIndexTemplate pfxRec - pfxRec = getPfx opts refPfx - inlines cap ref@RefRec{refPfx=refPfx', refLevel=refLevel'} = - getRefPrefix opts refPfx' cap 0 refLevel' $ applyIndexTemplate opts mempty ref - in applyTemplate vars template + pfxRec = getPfx opts (refPfx rr) + inlines cap ref = + getRefPrefix opts cap 0 ref $ applyIndexTemplate opts mempty ref + in applyTemplate (vars rr) template diff --git a/lib/Text/Pandoc/CrossRef/Util/Settings.hs b/lib/Text/Pandoc/CrossRef/Util/Settings.hs index a3bf8ecf..db37bf4a 100644 --- a/lib/Text/Pandoc/CrossRef/Util/Settings.hs +++ b/lib/Text/Pandoc/CrossRef/Util/Settings.hs @@ -83,9 +83,9 @@ defaultMeta = Settings $ ] -- these are merely the defaults, can (and will) be overridden in prefix configs <> captionTemplate (var "title" <> space <> var "i" <> var "titleDelim" <> space <> var "t") - <> referenceTemplate (var "Ref[n][lvl]" <> str "\160" <> var "i") - <> referenceIndexTemplate (var "i" <> var "suf") <> captionIndexTemplate (var "i") + <> referenceTemplate (var "Ref[n][lvl]" <> str "\160" <> var "rs") + <> referenceIndexTemplate (var "i" <> var "suf") <> numbering "arabic" <> listOfTitle (header 1 $ text "List of $$title$$s") <> prefixes' [ diff --git a/lib/Text/Pandoc/CrossRef/Util/VarFunction.hs b/lib/Text/Pandoc/CrossRef/Util/VarFunction.hs new file mode 100644 index 00000000..2e370ce0 --- /dev/null +++ b/lib/Text/Pandoc/CrossRef/Util/VarFunction.hs @@ -0,0 +1,42 @@ +{- +pandoc-crossref is a pandoc filter for numbering figures, +equations, tables and cross-references to them. +Copyright (C) 2019 Nikolay Yakimov + +This program is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License along +with this program; if not, write to the Free Software Foundation, Inc., +51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +-} + +{-# LANGUAGE Rank2Types, MultiWayIf, RecordWildCards #-} + +module Text.Pandoc.CrossRef.Util.VarFunction where + +import qualified Text.Pandoc.Builder as B + +import Data.List +import Text.Pandoc.CrossRef.References.Types as Types + +defaultVarFunc :: (RefRec -> String -> Maybe B.Inlines) + -> RefRec -> String -> Maybe B.Inlines +defaultVarFunc self RefRec{..} x = case x of + "idx" -> Just $ B.str $ show refIndex + "i" -> Just refIxInl + "t" -> Just refTitle + "lvl" -> Just $ B.str $ show refLevel + "lbl" -> Just $ B.str refLabel + "pfx" -> Just $ B.str refPfx + _ | Just y <- stripPrefix "s." x + , Just rs <- refScope + -> self rs y + _ -> Nothing diff --git a/pandoc-crossref.cabal b/pandoc-crossref.cabal index 172c0186..86541eb2 100644 --- a/pandoc-crossref.cabal +++ b/pandoc-crossref.cabal @@ -4,7 +4,7 @@ cabal-version: 1.12 -- -- see: https://github.com/sol/hpack -- --- hash: 37debaedf7757f2b50323af19ffaa0b1a750a9e31e925ed0d35bc6e41c92370a +-- hash: 1a825dfb1b800854a6d5884a234137795be747e35a04aa40aabcaf4f0d759e5f name: pandoc-crossref version: 0.4.0.0 @@ -106,6 +106,7 @@ library Text.Pandoc.CrossRef.Util.Settings.Types Text.Pandoc.CrossRef.Util.Template Text.Pandoc.CrossRef.Util.Util + Text.Pandoc.CrossRef.Util.VarFunction Paths_pandoc_crossref hs-source-dirs: lib @@ -219,6 +220,7 @@ test-suite test-pandoc-crossref Text.Pandoc.CrossRef.Util.Settings.Types Text.Pandoc.CrossRef.Util.Template Text.Pandoc.CrossRef.Util.Util + Text.Pandoc.CrossRef.Util.VarFunction Paths_pandoc_crossref hs-source-dirs: test diff --git a/test/m2m/scoping/input.md b/test/m2m/scoping/input.md index b19919f9..d296edcb 100644 --- a/test/m2m/scoping/input.md +++ b/test/m2m/scoping/input.md @@ -4,15 +4,15 @@ prefixes: ref: ["dfn.", "dfns."] title: "Definition" scope: "sec" - referenceIndexTemplate: "$$i$$$$scp# (%)$$" + referenceIndexTemplate: "$$i$$$$s.ref# (%)$$" cl: ref: ["cl.", "cls."] scope: "dfn" - referenceIndexTemplate: "$$i$$$$scp# (%)$$" + referenceIndexTemplate: "$$i$$$$s.ref# (%)$$" sec: captionTemplate: '$$titleName[lvl]% $$$$i$$$$titleDelim$$ $$t$$' - captionIndexTemplate: '$$s%.$$$$i$$' - referenceIndexTemplate: '$$i$$$$scp# (%)$$' + captionIndexTemplate: '$$s.i%.$$$$i$$' + referenceIndexTemplate: '$$i$$$$s.ref# (%)$$' scope: sec titleName: - Chapter diff --git a/test/m2m/section-template/input.md b/test/m2m/section-template/input.md index 84ce8242..badb2e94 100644 --- a/test/m2m/section-template/input.md +++ b/test/m2m/section-template/input.md @@ -2,7 +2,7 @@ prefixes: sec: captionTemplate: $$titleName[lvl]$$$$i$$. $$t$$ - captionIndexTemplate: '$$s%.$$$$i$$' + captionIndexTemplate: '$$s.i%.$$$$i$$' scope: sec titleName: - "Chapter " From 8b638bdafa7199aa4184a2585a45ecc7fdd0e535 Mon Sep 17 00:00:00 2001 From: Nikolay Yakimov Date: Sat, 2 Mar 2019 15:37:22 +0300 Subject: [PATCH 049/134] Fix prefixes.eq.title meta type --- lib/Text/Pandoc/CrossRef/Util/Settings.hs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/Text/Pandoc/CrossRef/Util/Settings.hs b/lib/Text/Pandoc/CrossRef/Util/Settings.hs index db37bf4a..aca3d890 100644 --- a/lib/Text/Pandoc/CrossRef/Util/Settings.hs +++ b/lib/Text/Pandoc/CrossRef/Util/Settings.hs @@ -92,7 +92,7 @@ defaultMeta = Settings $ "eq" .: [ "ref" .= map str ["eq.", "eqns."], "captionTemplate" .= var "i", - "title" .= "Equation" + "title" .= text "Equation" ], "fig" .: [ "ref" .= map str ["fig.", "figs."], From 434fb4508ba21cb2d2ec5bd4b99d0171095e5cda Mon Sep 17 00:00:00 2001 From: Nikolay Yakimov Date: Sat, 2 Mar 2019 16:26:06 +0300 Subject: [PATCH 050/134] Add list-of integrative test --- pandoc-crossref.cabal | 5 +- test/m2m/list-of/expect.md | 87 +++++++++++++++++++++++++++++++ test/m2m/list-of/expect.tex | 100 ++++++++++++++++++++++++++++++++++++ test/m2m/list-of/input.md | 37 +++++++++++++ 4 files changed, 228 insertions(+), 1 deletion(-) create mode 100644 test/m2m/list-of/expect.md create mode 100644 test/m2m/list-of/expect.tex create mode 100644 test/m2m/list-of/input.md diff --git a/pandoc-crossref.cabal b/pandoc-crossref.cabal index 86541eb2..20d59841 100644 --- a/pandoc-crossref.cabal +++ b/pandoc-crossref.cabal @@ -4,7 +4,7 @@ cabal-version: 1.12 -- -- see: https://github.com/sol/hpack -- --- hash: 1a825dfb1b800854a6d5884a234137795be747e35a04aa40aabcaf4f0d759e5f +-- hash: cdd762fd29fa9e48896393d0ca4b3b90a1c029bf28453ec58af6c605090268b1 name: pandoc-crossref version: 0.4.0.0 @@ -52,6 +52,9 @@ data-files: test/m2m/links/expect.md test/m2m/links/expect.tex test/m2m/links/input.md + test/m2m/list-of/expect.md + test/m2m/list-of/expect.tex + test/m2m/list-of/input.md test/m2m/listing-captions-ids/expect.md test/m2m/listing-captions-ids/expect.tex test/m2m/listing-captions-ids/input.md diff --git a/test/m2m/list-of/expect.md b/test/m2m/list-of/expect.md new file mode 100644 index 00000000..a04d791b --- /dev/null +++ b/test/m2m/list-of/expect.md @@ -0,0 +1,87 @@ +[$$eqn1\qquad(1)$$]{#eq:1} [$$eqn2\qquad(2)$$]{#eq:2} +[$$eqn3\qquad(3)$$]{#eq:3} + +![Figure 1: Image 1](img.png){#fig:1} + +![Figure 2: Image 2](img.png){#fig:2} + +![Figure 3: Image 3](img.png){#fig:3} + +::: {#tbl:1} + a b + --- --- + c d + + : Table 1: Table 1 +::: + +::: {#tbl:2} + a b + --- --- + c d + + : Table 2: Table 2 +::: + +::: {#tbl:3} + a b + --- --- + c d + + : Table 3: Table 3 +::: + +List of Figures +=============== + +::: {.list} +1\. Image 1 + +2\. Image 2 + +3\. Image 3 +::: + +List of Equations +================= + +::: {.list} +1\. $eqn1$ + +2\. $eqn2$ + +3\. $eqn3$ +::: + +List of Tables +============== + +::: {.list} +1\. Table 1 + +2\. Table 2 + +3\. Table 3 +::: + +List of Figures +=============== + +::: {.list} +1\. Image 1 + +2\. Image 2 + +3\. Image 3 +::: + +List of Tables +============== + +::: {.list} +1\. Table 1 + +2\. Table 2 + +3\. Table 3 +::: diff --git a/test/m2m/list-of/expect.tex b/test/m2m/list-of/expect.tex new file mode 100644 index 00000000..85efe989 --- /dev/null +++ b/test/m2m/list-of/expect.tex @@ -0,0 +1,100 @@ +\begin{equation}eqn1\label{eq:1}\end{equation} +\begin{equation}eqn2\label{eq:2}\end{equation} +\begin{equation}eqn3\label{eq:3}\end{equation} + +\begin{figure} +\hypertarget{fig:1}{% +\centering +\includegraphics{img.png} +\caption{Image 1}\label{fig:1} +} +\end{figure} + +\begin{figure} +\hypertarget{fig:2}{% +\centering +\includegraphics{img.png} +\caption{Image 2}\label{fig:2} +} +\end{figure} + +\begin{figure} +\hypertarget{fig:3}{% +\centering +\includegraphics{img.png} +\caption{Image 3}\label{fig:3} +} +\end{figure} + +\hypertarget{tbl:1}{} +\begin{longtable}[]{@{}ll@{}} +\caption{\label{tbl:1}Table 1}\tabularnewline +\toprule +a & b\tabularnewline +\midrule +\endfirsthead +\toprule +a & b\tabularnewline +\midrule +\endhead +c & d\tabularnewline +\bottomrule +\end{longtable} + +\hypertarget{tbl:2}{} +\begin{longtable}[]{@{}ll@{}} +\caption{\label{tbl:2}Table 2}\tabularnewline +\toprule +a & b\tabularnewline +\midrule +\endfirsthead +\toprule +a & b\tabularnewline +\midrule +\endhead +c & d\tabularnewline +\bottomrule +\end{longtable} + +\hypertarget{tbl:3}{} +\begin{longtable}[]{@{}ll@{}} +\caption{\label{tbl:3}Table 3}\tabularnewline +\toprule +a & b\tabularnewline +\midrule +\endfirsthead +\toprule +a & b\tabularnewline +\midrule +\endhead +c & d\tabularnewline +\bottomrule +\end{longtable} + +\section{List of Figures} + +1. Image 1 + +2. Image 2 + +3. Image 3 + +\section{List of Equations} + +1. \(eqn1\) + +2. \(eqn2\) + +3. \(eqn3\) + +\section{List of Tables} + +1. Table 1 + +2. Table 2 + +3. Table 3 + +\listoffigures + +\listoftables diff --git a/test/m2m/list-of/input.md b/test/m2m/list-of/input.md new file mode 100644 index 00000000..b341d4fc --- /dev/null +++ b/test/m2m/list-of/input.md @@ -0,0 +1,37 @@ +$$eqn1$${#eq:1} +$$eqn2$${#eq:2} +$$eqn3$${#eq:3} + +![Image 1](img.png){#fig:1} + +![Image 2](img.png){#fig:2} + +![Image 3](img.png){#fig:3} + +| a | b | +|:--|:--| +| c | d | + +: Table 1 {#tbl:1} + +| a | b | +|:--|:--| +| c | d | + +: Table 2 {#tbl:2} + +| a | b | +|:--|:--| +| c | d | + +: Table 3 {#tbl:3} + +\listof{fig} + +\listof{eq} + +\listof{tbl} + +\listoffigures + +\listoftables From f7805c5b54e22a914e95fc8914a5a92513cf0e55 Mon Sep 17 00:00:00 2001 From: Nikolay Yakimov Date: Sat, 2 Mar 2019 16:27:49 +0300 Subject: [PATCH 051/134] Use content as title for inline objects without title. TODO: perhaps allow overriding via an attribute --- lib/Text/Pandoc/CrossRef/References/Blocks.hs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/lib/Text/Pandoc/CrossRef/References/Blocks.hs b/lib/Text/Pandoc/CrossRef/References/Blocks.hs index 7deed9d2..cf668770 100644 --- a/lib/Text/Pandoc/CrossRef/References/Blocks.hs +++ b/lib/Text/Pandoc/CrossRef/References/Blocks.hs @@ -136,7 +136,7 @@ replaceEqn :: Options -> Scope -> Attr -> String -> Maybe String -> WS (String, replaceEqn opts scope (label, _, attrs) eq pfx = do let label' | null label = Left "eq" | otherwise = Right label - idxStr <- replaceAttr opts scope label' (lookup "label" attrs) mempty (fromMaybe "eq" pfx) + idxStr <- replaceAttr opts scope label' (lookup "label" attrs) (B.math eq) (fromMaybe "eq" pfx) let eq' | tableEqns opts = eq | otherwise = eq++"\\qquad("++stringify (refIxInl idxStr)++")" return (eq', stringify (refIxInl idxStr)) @@ -162,10 +162,10 @@ replaceInline opts scope (Image attr@(label,_,attrs) alt img@(_, tit)) f | isLatexFormat f -> ialt _ -> applyTitleTemplate opts idxStr replaceNoRecurse $ Image attr alt' img -replaceInline opts scope x@(Span (label,_,attrs) _content) +replaceInline opts scope x@(Span (label,_,attrs) content) | Just pfx <- getRefPrefix opts label = do - rec' <- replaceAttr opts scope (Right label) (lookup "label" attrs) mempty pfx + rec' <- replaceAttr opts scope (Right label) (lookup "label" attrs) (B.fromList content) pfx replaceRecurse (newScope rec' scope) x replaceInline _ scope _ = noReplaceRecurse scope From 492fe386c0314c9312f4e3e75becde8c6a54b609 Mon Sep 17 00:00:00 2001 From: Nikolay Yakimov Date: Sat, 2 Mar 2019 16:29:41 +0300 Subject: [PATCH 052/134] Add template for list-of items --- lib/Text/Pandoc/CrossRef/References/List.hs | 24 ++++++++++++------- lib/Text/Pandoc/CrossRef/Util/Options.hs | 3 +++ lib/Text/Pandoc/CrossRef/Util/Prefixes.hs | 2 ++ lib/Text/Pandoc/CrossRef/Util/Settings.hs | 8 ++++--- lib/Text/Pandoc/CrossRef/Util/Settings/Gen.hs | 2 ++ lib/Text/Pandoc/CrossRef/Util/VarFunction.hs | 2 +- 6 files changed, 29 insertions(+), 12 deletions(-) diff --git a/lib/Text/Pandoc/CrossRef/References/List.hs b/lib/Text/Pandoc/CrossRef/References/List.hs index 9715d4e6..e248c780 100644 --- a/lib/Text/Pandoc/CrossRef/References/List.hs +++ b/lib/Text/Pandoc/CrossRef/References/List.hs @@ -18,22 +18,27 @@ with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -} +{-# LANGUAGE NamedFieldPuns #-} + module Text.Pandoc.CrossRef.References.List (listOf) where import Text.Pandoc.Definition import Text.Pandoc.Builder import Data.Accessor.Monad.Trans.State -import Control.Arrow import Data.List +import Data.Function import qualified Data.Map as M import Text.Pandoc.CrossRef.References.Types import Text.Pandoc.CrossRef.Util.Util import Text.Pandoc.CrossRef.Util.Options +import Text.Pandoc.CrossRef.Util.Template +import Text.Pandoc.CrossRef.Util.VarFunction listOf :: Options -> [Block] -> WS [Block] -listOf opts (RawBlock (Format "latex") cmd:xs) - | Just pfxBrace <- "\\listof{" `stripPrefix` cmd +listOf opts (RawBlock fmt cmd:xs) + | isLaTeXRawBlockFmt fmt + , Just pfxBrace <- "\\listof{" `stripPrefix` cmd , (pfx, "}") <- span (/='}') pfxBrace = getPfxData pfx >>= fmap toList . makeList opts pfx (fromList xs) listOf Options{outFormat=f} x | isLatexFormat f = return x @@ -58,8 +63,11 @@ makeList opts titlef xs refs <> divWith ("", ["list"], []) (mconcat $ map itemChap refsSorted) <> xs where - refsSorted :: [(String, RefRec)] - refsSorted = sortBy compare' $ M.toList refs - compare' (_,RefRec{refIndex=i}) (_,RefRec{refIndex=j}) = compare i j - itemChap :: (String, RefRec) -> Blocks - itemChap = para . uncurry (\ x x0 -> x <> space <> x0) . (refIxInl &&& refTitle) . snd + refsSorted :: [RefRec] + refsSorted = sortBy (compare `on` refIndex) $ M.elems refs + itemChap :: RefRec -> Blocks + itemChap = para . applyListItemTemplate opts + +applyListItemTemplate :: Options -> RefRec -> Inlines +applyListItemTemplate opts rr@RefRec{refPfx} = + applyTemplate (fix defaultVarFunc rr) $ pfxListItemTemplate opts refPfx diff --git a/lib/Text/Pandoc/CrossRef/Util/Options.hs b/lib/Text/Pandoc/CrossRef/Util/Options.hs index 76fed66b..4a386164 100644 --- a/lib/Text/Pandoc/CrossRef/Util/Options.hs +++ b/lib/Text/Pandoc/CrossRef/Util/Options.hs @@ -52,6 +52,9 @@ prefixList = M.keys . prefixes pfxCaptionTemplate :: Options -> String -> Template pfxCaptionTemplate opts pfx = prefixCaptionTemplate $ getPfx opts pfx +pfxListItemTemplate :: Options -> String -> Template +pfxListItemTemplate opts pfx = prefixListItemTemplate $ getPfx opts pfx + pfxCaptionIndexTemplate :: Options -> String -> Template pfxCaptionIndexTemplate opts pfx = prefixCaptionIndexTemplate $ getPfx opts pfx diff --git a/lib/Text/Pandoc/CrossRef/Util/Prefixes.hs b/lib/Text/Pandoc/CrossRef/Util/Prefixes.hs index d5ba9fff..ebf0e43d 100644 --- a/lib/Text/Pandoc/CrossRef/Util/Prefixes.hs +++ b/lib/Text/Pandoc/CrossRef/Util/Prefixes.hs @@ -51,6 +51,7 @@ getPrefixes varN dtv , prefixReferenceTemplate = makeRefTemplate kv $ getTemplDefault "referenceTemplate" , prefixReferenceIndexTemplate = makeTemplate kv $ getTemplDefault "referenceIndexTemplate" , prefixCaptionIndexTemplate = makeTemplate kv $ getTemplDefault "captionIndexTemplate" + , prefixListItemTemplate = makeTemplate kv $ getTemplDefault "listItemTemplate" , prefixScope = getMetaStringList "scope" kv , prefixNumbering = \lvl -> let prettyVarName = varN <> "." <> k <> "." <> varName @@ -80,6 +81,7 @@ data Prefix = Prefix { , prefixListOfTitle :: !BlockTemplate , prefixReferenceIndexTemplate :: !Template , prefixCaptionIndexTemplate :: !Template + , prefixListItemTemplate :: !Template -- Used for LaTeX metadata; the same value is used in -- default value for prefixCaptionTemplate , prefixTitle :: Inlines diff --git a/lib/Text/Pandoc/CrossRef/Util/Settings.hs b/lib/Text/Pandoc/CrossRef/Util/Settings.hs index aca3d890..f1e1e2bf 100644 --- a/lib/Text/Pandoc/CrossRef/Util/Settings.hs +++ b/lib/Text/Pandoc/CrossRef/Util/Settings.hs @@ -64,7 +64,8 @@ defaultMeta = Settings $ <> codeBlockCaptions False <> autoSectionLabels False -- <> numberSections False - <> titleDelim (str ":") + <> titleDelim (str ":" <> space) + <> listItemNumberDelim (str "." <> space) <> rangeDelim (str "-") <> pairDelim (str "," <> space) <> lastDelim (str "," <> space) @@ -82,12 +83,13 @@ defaultMeta = Settings $ , "section" .= "sec" ] -- these are merely the defaults, can (and will) be overridden in prefix configs - <> captionTemplate (var "title" <> space <> var "i" <> var "titleDelim" <> space <> var "t") + <> captionTemplate (var "title" <> space <> var "i" <> var "titleDelim" <> var "t") <> captionIndexTemplate (var "i") <> referenceTemplate (var "Ref[n][lvl]" <> str "\160" <> var "rs") <> referenceIndexTemplate (var "i" <> var "suf") <> numbering "arabic" - <> listOfTitle (header 1 $ text "List of $$title$$s") + <> listOfTitle (header 1 $ text "List of " <> var "title" <> str "s") + <> listItemTemplate (var "i" <> var "listItemNumberDelim" <> var "t") <> prefixes' [ "eq" .: [ "ref" .= map str ["eq.", "eqns."], diff --git a/lib/Text/Pandoc/CrossRef/Util/Settings/Gen.hs b/lib/Text/Pandoc/CrossRef/Util/Settings/Gen.hs index 96fe7b75..ad716bf5 100644 --- a/lib/Text/Pandoc/CrossRef/Util/Settings/Gen.hs +++ b/lib/Text/Pandoc/CrossRef/Util/Settings/Gen.hs @@ -33,10 +33,12 @@ nameDeriveSetters ''Options fmap concat $ mapM (makeAcc . mkName) [ "crossrefYaml" , "titleDelim" + , "listItemNumberDelim" , "captionTemplate" , "referenceTemplate" , "referenceIndexTemplate" , "captionIndexTemplate" + , "listItemTemplate" , "numbering" , "listOfTitle" ] diff --git a/lib/Text/Pandoc/CrossRef/Util/VarFunction.hs b/lib/Text/Pandoc/CrossRef/Util/VarFunction.hs index 2e370ce0..7bf095a5 100644 --- a/lib/Text/Pandoc/CrossRef/Util/VarFunction.hs +++ b/lib/Text/Pandoc/CrossRef/Util/VarFunction.hs @@ -18,7 +18,7 @@ with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -} -{-# LANGUAGE Rank2Types, MultiWayIf, RecordWildCards #-} +{-# LANGUAGE RecordWildCards #-} module Text.Pandoc.CrossRef.Util.VarFunction where From b7bd42b4858e5d327dfd2de0fc627ec26ab32aa2 Mon Sep 17 00:00:00 2001 From: Nikolay Yakimov Date: Sat, 2 Mar 2019 17:39:37 +0300 Subject: [PATCH 053/134] Use ref-able object attributes as a source of template variables, too --- lib/Text/Pandoc/CrossRef/References/Blocks.hs | 29 ++++++----- lib/Text/Pandoc/CrossRef/References/List.hs | 2 +- lib/Text/Pandoc/CrossRef/References/Refs.hs | 12 ++--- lib/Text/Pandoc/CrossRef/References/Types.hs | 1 + lib/Text/Pandoc/CrossRef/Util/Meta.hs | 13 ++++- lib/Text/Pandoc/CrossRef/Util/Options.hs | 2 +- lib/Text/Pandoc/CrossRef/Util/Template.hs | 29 ++++------- lib/Text/Pandoc/CrossRef/Util/VarFunction.hs | 23 ++++---- pandoc-crossref.cabal | 5 +- test/m2m/ref-attrs/expect.md | 31 +++++++++++ test/m2m/ref-attrs/expect.tex | 52 +++++++++++++++++++ test/m2m/ref-attrs/input.md | 29 +++++++++++ test/test-pandoc-crossref.hs | 36 ++++++------- 13 files changed, 194 insertions(+), 70 deletions(-) create mode 100644 test/m2m/ref-attrs/expect.md create mode 100644 test/m2m/ref-attrs/expect.tex create mode 100644 test/m2m/ref-attrs/input.md diff --git a/lib/Text/Pandoc/CrossRef/References/Blocks.hs b/lib/Text/Pandoc/CrossRef/References/Blocks.hs index cf668770..89f855e5 100644 --- a/lib/Text/Pandoc/CrossRef/References/Blocks.hs +++ b/lib/Text/Pandoc/CrossRef/References/Blocks.hs @@ -41,6 +41,7 @@ import Text.Pandoc.CrossRef.Util.Template import Text.Pandoc.CrossRef.Util.CodeBlockCaptions import Text.Pandoc.CrossRef.Util.VarFunction import Control.Applicative +import Control.Arrow (second) import Data.Default (def) import Prelude @@ -71,8 +72,8 @@ replaceElement opts scope (Sec n ns (label, cls, attrs) text' body) = do ititle = B.fromList text' defaultSecPfx = "sec" rec' <- case pfx' of - Just p -> replaceAttr opts scope (Right label) (lookup "label" attrs) ititle p - Nothing -> replaceAttr opts scope (Left defaultSecPfx) (lookup "label" attrs) ititle defaultSecPfx + Just p -> replaceAttr opts scope (Right label) attrs ititle p + Nothing -> replaceAttr opts scope (Left defaultSecPfx) attrs ititle defaultSecPfx let title' = B.toList $ case outFormat opts of f | isLatexFormat f -> B.rawInline "latex" (mkLaTeXLabel label) <> ititle @@ -86,7 +87,7 @@ replaceBlock opts scope (Div divOps@(label,_,attrs) [Table title align widths he , Just pfx <- getRefPrefix opts label = do let ititle = B.fromList title - idxStr <- replaceAttr opts scope (Right label) (lookup "label" attrs) ititle pfx + idxStr <- replaceAttr opts scope (Right label) attrs ititle pfx let title' = B.toList $ case outFormat opts of f | isLatexFormat f -> B.rawInline "latex" (mkLaTeXLabel label) <> ititle @@ -97,7 +98,7 @@ replaceBlock opts scope (Div (label,"listing":_, []) [Para caption, CodeBlock ([ , Just pfx <- getRefPrefix opts label = do let icaption = B.fromList caption - idxStr <- replaceAttr opts scope (Right label) (lookup "label" attrs) icaption pfx + idxStr <- replaceAttr opts scope (Right label) attrs icaption pfx let caption' = applyTitleTemplate opts idxStr replaceNoRecurse $ case outFormat opts of f --if used with listings package, return code block with caption @@ -128,7 +129,7 @@ replaceBlock opts scope (Para [Span attrs@(label, _, _) [Math DisplayMath eq]]) replaceBlock opts scope x@(Div (label, _, attrs) _content) | Just pfx <- getRefPrefix opts label = do - rec' <- replaceAttr opts scope (Right label) (lookup "label" attrs) mempty pfx + rec' <- replaceAttr opts scope (Right label) attrs mempty pfx replaceRecurse (newScope rec' scope) x replaceBlock _ scope _ = noReplaceRecurse scope @@ -136,7 +137,7 @@ replaceEqn :: Options -> Scope -> Attr -> String -> Maybe String -> WS (String, replaceEqn opts scope (label, _, attrs) eq pfx = do let label' | null label = Left "eq" | otherwise = Right label - idxStr <- replaceAttr opts scope label' (lookup "label" attrs) (B.math eq) (fromMaybe "eq" pfx) + idxStr <- replaceAttr opts scope label' attrs (B.math eq) (fromMaybe "eq" pfx) let eq' | tableEqns opts = eq | otherwise = eq++"\\qquad("++stringify (refIxInl idxStr)++")" return (eq', stringify (refIxInl idxStr)) @@ -157,7 +158,7 @@ replaceInline opts scope (Image attr@(label,_,attrs) alt img@(_, tit)) , "fig:" `isPrefixOf` tit = do let ialt = B.fromList alt - idxStr <- replaceAttr opts scope (Right label) (lookup "label" attrs) ialt pfx + idxStr <- replaceAttr opts scope (Right label) attrs ialt pfx let alt' = B.toList $ case outFormat opts of f | isLatexFormat f -> ialt _ -> applyTitleTemplate opts idxStr @@ -165,19 +166,19 @@ replaceInline opts scope (Image attr@(label,_,attrs) alt img@(_, tit)) replaceInline opts scope x@(Span (label,_,attrs) content) | Just pfx <- getRefPrefix opts label = do - rec' <- replaceAttr opts scope (Right label) (lookup "label" attrs) (B.fromList content) pfx + rec' <- replaceAttr opts scope (Right label) attrs (B.fromList content) pfx replaceRecurse (newScope rec' scope) x replaceInline _ scope _ = noReplaceRecurse scope applyTitleTemplate :: Options -> RefRec -> B.Inlines applyTitleTemplate opts rr@RefRec{refPfx} = - applyTemplate (fix defaultVarFunc rr) $ pfxCaptionTemplate opts refPfx + applyTemplate (pfxCaptionTemplate opts refPfx) (fix defaultVarFunc rr) applyTitleIndexTemplate :: Options -> RefRec -> B.Inlines -> B.Inlines applyTitleIndexTemplate opts rr@RefRec{..} label = - applyTemplate vf $ pfxCaptionIndexTemplate opts refPfx + applyTemplate (pfxCaptionIndexTemplate opts refPfx) vf where - vf "i" = Just label + vf "i" = Just $ MetaInlines $ B.toList label vf x = fix defaultVarFunc rr x divBlocks :: Options -> Block -> Block @@ -214,11 +215,12 @@ spanInlines opts (math@(Math DisplayMath _eq):ils) = Span nullAttr [math]:ils spanInlines _ x = x -replaceAttr :: Options -> Scope -> Either String String -> Maybe String -> B.Inlines -> String -> WS RefRec -replaceAttr o scope label refLabel' title pfx +replaceAttr :: Options -> Scope -> Either String String -> [(String, String)] -> B.Inlines -> String -> WS RefRec +replaceAttr o scope label attrs title pfx = do let ropt = getPfx o pfx itemScope = find ((`elem` prefixScope ropt) . refPfx) scope + refLabel' = lookup "label" attrs cr <- (\CounterRec{..} -> CounterRec{ crIndex = crIndex+1 , crIndexInScope = M.insertWith (+) itemScope 1 crIndexInScope @@ -240,6 +242,7 @@ replaceAttr o scope label refLabel' title pfx , refLevel = lvl , refPfx = pfx , refCaption = applyTitleTemplate o rec' + , refAttrs = M.fromListWith (flip (++)) $ map (second return) attrs } modify referenceData $ M.insert label' rec' return rec' diff --git a/lib/Text/Pandoc/CrossRef/References/List.hs b/lib/Text/Pandoc/CrossRef/References/List.hs index e248c780..92ffab10 100644 --- a/lib/Text/Pandoc/CrossRef/References/List.hs +++ b/lib/Text/Pandoc/CrossRef/References/List.hs @@ -70,4 +70,4 @@ makeList opts titlef xs refs applyListItemTemplate :: Options -> RefRec -> Inlines applyListItemTemplate opts rr@RefRec{refPfx} = - applyTemplate (fix defaultVarFunc rr) $ pfxListItemTemplate opts refPfx + applyTemplate (pfxListItemTemplate opts refPfx) (fix defaultVarFunc rr) diff --git a/lib/Text/Pandoc/CrossRef/References/Refs.hs b/lib/Text/Pandoc/CrossRef/References/Refs.hs index 73c62200..195b4e4b 100644 --- a/lib/Text/Pandoc/CrossRef/References/Refs.hs +++ b/lib/Text/Pandoc/CrossRef/References/Refs.hs @@ -78,8 +78,8 @@ getRefPrefix :: Options -> Bool -> Int -> RefRec -> Inlines -> Inlines getRefPrefix opts capitalize num rr@RefRec{..} cit = applyRefTemplate reftempl vf capitalize where Prefix{prefixReferenceTemplate=reftempl} = fromMaybe undefined $ M.lookup refPfx $ prefixes opts - vf "rs" = Just cit - vf "n" = Just $ str $ show num + vf "rs" = Just $ MetaInlines $ toList cit + vf "n" = Just $ MetaString $ show num vf x = fix defaultVarFunc rr x replaceRefsLatex :: String -> Options -> [RefData] -> WS Inlines @@ -237,15 +237,15 @@ makeIndices o s = format $ concatMap f $ HT.groupBy g $ sort $ nub s error ("Undefined cross-reference: " <> rdiLabel <> ". This should not be possible, please report a bug") -applyIndexTemplate :: Options -> Many Inline -> RefRec -> Inlines +applyIndexTemplate :: Options -> Inlines -> RefRec -> Inlines applyIndexTemplate opts suf rr = let varsSc rr' "ref" = Just $ inlines False rr' varsSc rr' "Ref" = Just $ inlines True rr' varsSc rr' x = defaultVarFunc varsSc rr' x - vars _ "suf" = Just suf + vars _ "suf" = Just $ MetaInlines $ toList suf vars rr' x = defaultVarFunc varsSc rr' x template = prefixReferenceIndexTemplate pfxRec pfxRec = getPfx opts (refPfx rr) - inlines cap ref = + inlines cap ref = MetaInlines $ toList $ getRefPrefix opts cap 0 ref $ applyIndexTemplate opts mempty ref - in applyTemplate (vars rr) template + in applyTemplate template (vars rr) diff --git a/lib/Text/Pandoc/CrossRef/References/Types.hs b/lib/Text/Pandoc/CrossRef/References/Types.hs index e25c3b39..98e2489d 100644 --- a/lib/Text/Pandoc/CrossRef/References/Types.hs +++ b/lib/Text/Pandoc/CrossRef/References/Types.hs @@ -35,6 +35,7 @@ data RefRec = RefRec { refIndex :: !Int -- global ordinal number for prefix , refLabel :: !String -- label, i.e. pfx:label string , refPfx :: !String -- reference prefix, the part in label before : , refCaption :: Inlines -- caption after applying template; must be non-strict + , refAttrs :: !(M.Map String [String]) -- attribute map } deriving (Show, Eq, Ord) type RefMap = M.Map String RefRec diff --git a/lib/Text/Pandoc/CrossRef/Util/Meta.hs b/lib/Text/Pandoc/CrossRef/Util/Meta.hs index 01d89f2a..aaaa36bc 100644 --- a/lib/Text/Pandoc/CrossRef/Util/Meta.hs +++ b/lib/Text/Pandoc/CrossRef/Util/Meta.hs @@ -41,6 +41,7 @@ import Data.Default import Text.Pandoc.Walk import Text.Pandoc.Shared hiding (capitalize, toString) import Data.Maybe +import qualified Data.Map as M getMetaList :: (Default a) => (MetaValue -> a) -> String -> Settings -> Int -> a getMetaList f name (Settings meta) i = maybe def f $ lookupMeta name meta >>= getList i @@ -127,10 +128,18 @@ getList i (MetaList l) = l !!? i | otherwise = Nothing getList _ x = Just x -capitalize :: (Walkable Inline a) => (String -> Maybe a) -> String -> Maybe a +capitalize :: (String -> Maybe MetaValue) -> String -> Maybe MetaValue capitalize f varname = case f (capitalizeFirst varname) of - Nothing -> walk capStrFst <$> f varname + Nothing -> case f varname of + Nothing -> Nothing + Just x -> Just $ cap x Just xs -> Just xs where + cap (MetaString s) = MetaString $ capitalizeFirst s + cap (MetaInlines i) = MetaInlines $ walk capStrFst i + cap (MetaBlocks b) = MetaBlocks $ walk capStrFst b + cap (MetaMap m) = MetaMap $ M.map cap m + cap (MetaList l) = MetaList $ map cap l + cap x = x capStrFst (Str s) = Str $ capitalizeFirst s capStrFst x = x diff --git a/lib/Text/Pandoc/CrossRef/Util/Options.hs b/lib/Text/Pandoc/CrossRef/Util/Options.hs index 4a386164..538637e4 100644 --- a/lib/Text/Pandoc/CrossRef/Util/Options.hs +++ b/lib/Text/Pandoc/CrossRef/Util/Options.hs @@ -83,4 +83,4 @@ getRefLabel opts ils getRefLabel _ _ = Nothing getTitleForListOf :: Options -> String -> Blocks -getTitleForListOf opts = applyBlockTemplate (const Nothing) . prefixListOfTitle . getPfx opts +getTitleForListOf opts = flip applyBlockTemplate (const Nothing) . prefixListOfTitle . getPfx opts diff --git a/lib/Text/Pandoc/CrossRef/Util/Template.hs b/lib/Text/Pandoc/CrossRef/Util/Template.hs index 15f35a55..91a96dbe 100644 --- a/lib/Text/Pandoc/CrossRef/Util/Template.hs +++ b/lib/Text/Pandoc/CrossRef/Util/Template.hs @@ -44,9 +44,9 @@ import Control.Monad ((<=<)) import Data.Data (Data) type VarFunc = String -> Maybe MetaValue -newtype Template = Template (VarFunc -> Inlines) -newtype RefTemplate = RefTemplate (VarFunc -> Bool -> Inlines) -newtype BlockTemplate = BlockTemplate (VarFunc -> Blocks) +newtype Template = Template { applyTemplate :: VarFunc -> Inlines } +newtype RefTemplate = RefTemplate { applyRefTemplate :: VarFunc -> Bool -> Inlines } +newtype BlockTemplate = BlockTemplate { applyBlockTemplate :: VarFunc -> Blocks } data State = StFirstVar | StIndex | StAfterIndex | StPrefix | StSuffix deriving Eq data ParseRes = ParseRes { prVar :: String, prIdx :: [String], prPfx :: String, prSfx :: String } deriving Show @@ -99,18 +99,11 @@ scan = bottomUp . go makeRefTemplate :: Settings -> Inlines -> RefTemplate makeRefTemplate dtv xs' = let Template g = makeTemplate dtv xs' - vf cap (vc:vs) - | isUpper vc && cap = capitalize (`lookupSettings` dtv) var - | otherwise = lookupSettings var dtv - where var = toLower vc : vs - vf _ [] = error "Empty variable name" - in RefTemplate $ \vars cap -> g (\v -> vars v <|> vf cap v) - -applyRefTemplate :: RefTemplate -> (String -> Maybe Inlines) -> Bool -> Inlines -applyRefTemplate (RefTemplate g) vars = g (fmap (MetaInlines . toList) . vars) - -applyTemplate :: (String -> Maybe Inlines) -> Template -> Inlines -applyTemplate vars (Template g) = g $ fmap (MetaInlines . toList) . vars - -applyBlockTemplate :: VarFunc -> BlockTemplate -> Blocks -applyBlockTemplate vars (BlockTemplate g) = g vars + vf vars cap (vc:vs) + | isUpper vc && cap = capitalize lookup' var + | otherwise = lookup' var + where + var = toLower vc : vs + lookup' x = vars x <|> lookupSettings x dtv + vf _ _ [] = error "Empty variable name" + in RefTemplate $ \vars cap -> g (vf vars cap) diff --git a/lib/Text/Pandoc/CrossRef/Util/VarFunction.hs b/lib/Text/Pandoc/CrossRef/Util/VarFunction.hs index 7bf095a5..afac245b 100644 --- a/lib/Text/Pandoc/CrossRef/Util/VarFunction.hs +++ b/lib/Text/Pandoc/CrossRef/Util/VarFunction.hs @@ -22,21 +22,26 @@ with this program; if not, write to the Free Software Foundation, Inc., module Text.Pandoc.CrossRef.Util.VarFunction where +import Text.Pandoc.Definition import qualified Text.Pandoc.Builder as B import Data.List +import qualified Data.Map as M import Text.Pandoc.CrossRef.References.Types as Types -defaultVarFunc :: (RefRec -> String -> Maybe B.Inlines) - -> RefRec -> String -> Maybe B.Inlines +defaultVarFunc :: (RefRec -> String -> Maybe MetaValue) + -> RefRec -> String -> Maybe MetaValue defaultVarFunc self RefRec{..} x = case x of - "idx" -> Just $ B.str $ show refIndex - "i" -> Just refIxInl - "t" -> Just refTitle - "lvl" -> Just $ B.str $ show refLevel - "lbl" -> Just $ B.str refLabel - "pfx" -> Just $ B.str refPfx + "idx" -> Just $ MetaString $ show refIndex + "i" -> Just $ MetaInlines $ B.toList refIxInl + "t" -> Just $ MetaInlines $ B.toList refTitle + "lvl" -> Just $ MetaString $ show refLevel + "lbl" -> Just $ MetaString refLabel + "pfx" -> Just $ MetaString refPfx _ | Just y <- stripPrefix "s." x , Just rs <- refScope -> self rs y - _ -> Nothing + _ -> case M.lookup x refAttrs of + Just [s] -> Just $ MetaString s + Just ss -> Just $ MetaList $ map MetaString ss + _ -> Nothing diff --git a/pandoc-crossref.cabal b/pandoc-crossref.cabal index 20d59841..1c599bc8 100644 --- a/pandoc-crossref.cabal +++ b/pandoc-crossref.cabal @@ -4,7 +4,7 @@ cabal-version: 1.12 -- -- see: https://github.com/sol/hpack -- --- hash: cdd762fd29fa9e48896393d0ca4b3b90a1c029bf28453ec58af6c605090268b1 +-- hash: d30ab549b7a62592a79d5bc6680d6f0311e963e00a2a1c124193ea104c66bb9a name: pandoc-crossref version: 0.4.0.0 @@ -58,6 +58,9 @@ data-files: test/m2m/listing-captions-ids/expect.md test/m2m/listing-captions-ids/expect.tex test/m2m/listing-captions-ids/input.md + test/m2m/ref-attrs/expect.md + test/m2m/ref-attrs/expect.tex + test/m2m/ref-attrs/input.md test/m2m/regresssion-219/expect.md test/m2m/regresssion-219/expect.tex test/m2m/regresssion-219/input.md diff --git a/test/m2m/ref-attrs/expect.md b/test/m2m/ref-attrs/expect.md new file mode 100644 index 00000000..fe4922ea --- /dev/null +++ b/test/m2m/ref-attrs/expect.md @@ -0,0 +1,31 @@ +![Test1 1: Image 1](img.png){#fig:1 ref="img." ref="imgs." +title="Test1"} + +![Test2 2: Image 2](img.png){#fig:2 ref="img." ref="imgs." +title="Test2"} + +![Figure 3: Image 3](img.png){#fig:3} + +This should have custom prefix: img. 1 + +This should have custom prefix: img. 2 + +This should have normal prefix: fig. 3 + +This should have custom prefix: imgs. 1, 2 + +This should have custom prefix: imgs. 1-3 + +This should have normal prefix: figs. 1-3 + +This should have custom prefix (capitalized): Img. 1 + +This should have custom prefix (capitalized): Img. 2 + +This should have normal prefix (capitalized): Fig. 3 + +This should have custom prefix (capitalized): Imgs. 1, 2 + +This should have custom prefix (capitalized): Imgs. 1-3 + +This should have normal prefix (capitalized): Figs. 1-3 diff --git a/test/m2m/ref-attrs/expect.tex b/test/m2m/ref-attrs/expect.tex new file mode 100644 index 00000000..5d0ac3ce --- /dev/null +++ b/test/m2m/ref-attrs/expect.tex @@ -0,0 +1,52 @@ +\begin{figure} +\hypertarget{fig:1}{% +\centering +\includegraphics{img.png} +\caption{Image 1}\label{fig:1} +} +\end{figure} + +\begin{figure} +\hypertarget{fig:2}{% +\centering +\includegraphics{img.png} +\caption{Image 2}\label{fig:2} +} +\end{figure} + +\begin{figure} +\hypertarget{fig:3}{% +\centering +\includegraphics{img.png} +\caption{Image 3}\label{fig:3} +} +\end{figure} + +This should have custom prefix: img.~\ref{fig:1} + +This should have custom prefix: img.~\ref{fig:2} + +This should have normal prefix: fig.~\ref{fig:3} + +This should have custom prefix: imgs.~\ref{fig:1}, \ref{fig:2} + +This should have custom prefix: +imgs.~\ref{fig:1}, \ref{fig:2}, \ref{fig:3} + +This should have normal prefix: +figs.~\ref{fig:3}, \ref{fig:1}, \ref{fig:2} + +This should have custom prefix (capitalized): img.~\ref{fig:1} + +This should have custom prefix (capitalized): img.~\ref{fig:2} + +This should have normal prefix (capitalized): fig.~\ref{fig:3} + +This should have custom prefix (capitalized): +imgs.~\ref{fig:1}, \ref{fig:2} + +This should have custom prefix (capitalized): +imgs.~\ref{fig:1}, \ref{fig:2}, \ref{fig:3} + +This should have normal prefix (capitalized): +figs.~\ref{fig:3}, \ref{fig:1}, \ref{fig:2} diff --git a/test/m2m/ref-attrs/input.md b/test/m2m/ref-attrs/input.md new file mode 100644 index 00000000..383aaa50 --- /dev/null +++ b/test/m2m/ref-attrs/input.md @@ -0,0 +1,29 @@ +![Image 1](img.png){#fig:1 ref="img." ref="imgs." title="Test1"} + +![Image 2](img.png){#fig:2 ref="img." ref="imgs." title="Test2"} + +![Image 3](img.png){#fig:3} + +This should have custom prefix: @fig:1 + +This should have custom prefix: @fig:2 + +This should have normal prefix: @fig:3 + +This should have custom prefix: [@fig:1; @fig:2] + +This should have custom prefix: [@fig:1; @fig:2; @fig:3] + +This should have normal prefix: [@fig:3; @fig:1; @fig:2] + +This should have custom prefix (capitalized): @Fig:1 + +This should have custom prefix (capitalized): @Fig:2 + +This should have normal prefix (capitalized): @Fig:3 + +This should have custom prefix (capitalized): [@Fig:1; @Fig:2] + +This should have custom prefix (capitalized): [@Fig:1; @Fig:2; @Fig:3] + +This should have normal prefix (capitalized): [@Fig:3; @Fig:1; @Fig:2] diff --git a/test/test-pandoc-crossref.hs b/test/test-pandoc-crossref.hs index 29606765..ac0f8100 100644 --- a/test/test-pandoc-crossref.hs +++ b/test/test-pandoc-crossref.hs @@ -18,7 +18,7 @@ with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -} -{-# LANGUAGE FlexibleContexts, CPP #-} +{-# LANGUAGE FlexibleContexts, CPP, OverloadedStrings, TypeSynonymInstances, FlexibleInstances #-} import Test.Hspec import Text.Pandoc hiding (getDataFileName) import Text.Pandoc.Builder @@ -44,6 +44,7 @@ import qualified Text.Pandoc.CrossRef.Util.CodeBlockCaptions as Util.CodeBlockCa import qualified Native import Paths_pandoc_crossref +import Data.String import Prelude main :: IO () @@ -52,7 +53,7 @@ main = hspec $ do it "Labels equations" $ testAll (plain $ equation' "a^2+b^2=c^2" "equation") (plain $ spanWith ("eq:equation", [], []) (equation' "a^2+b^2=c^2\\qquad(1)" []), - (referenceData =: M.fromList $ refRec'' "eq:equation" 1) . + (referenceData =: M.fromList $ refRec' "eq:equation" 1 (math "a^2+b^2=c^2") "1") . (pfxCounter =: M.singleton "eq" $ CounterRec {crIndex = 1, crIndexInScope = M.singleton Nothing 1}) ) it "Labels equations in the middle of text" $ @@ -64,7 +65,7 @@ main = hspec $ do text "This is an equation: " <> spanWith ("eq:equation", [], []) (equation' "a^2+b^2=c^2\\qquad(1)" []) <> text " it should be labeled", - (referenceData =: M.fromList $ refRec'' "eq:equation" 1) . + (referenceData =: M.fromList $ refRec' "eq:equation" 1 (math "a^2+b^2=c^2") "1") . (pfxCounter =: M.singleton "eq" $ CounterRec {crIndex = 1, crIndexInScope = M.singleton Nothing 1}) ) it "Labels equations in the beginning of text" $ @@ -74,7 +75,7 @@ main = hspec $ do (plain $ spanWith ("eq:equation", [], []) (equation' "a^2+b^2=c^2\\qquad(1)" []) <> text " it should be labeled", - (referenceData =: M.fromList $ refRec'' "eq:equation" 1) . + (referenceData =: M.fromList $ refRec' "eq:equation" 1 (math "a^2+b^2=c^2") "1") . (pfxCounter =: M.singleton "eq" $ CounterRec {crIndex = 1, crIndexInScope = M.singleton Nothing 1}) ) it "Labels equations in the end of text" $ @@ -84,7 +85,7 @@ main = hspec $ do (plain $ text "This is an equation: " <> spanWith ("eq:equation", [], []) (equation' "a^2+b^2=c^2\\qquad(1)" []), - (referenceData =: M.fromList $ refRec'' "eq:equation" 1) . + (referenceData =: M.fromList $ refRec' "eq:equation" 1 (math "a^2+b^2=c^2") "1") . (pfxCounter =: M.singleton "eq" $ CounterRec {crIndex = 1, crIndexInScope = M.singleton Nothing 1}) ) @@ -167,7 +168,7 @@ main = hspec $ do it "Labels equations" $ testAll (equation "a^2+b^2=c^2" "equation") (para $ spanWith ("eq:equation", [], []) (equation' "a^2+b^2=c^2\\qquad(1)" []), - (referenceData =: M.fromList $ refRec'' "eq:equation" 1) . + (referenceData =: M.fromList $ refRec' "eq:equation" 1 (math "a^2+b^2=c^2") "1") . (pfxCounter =: M.singleton "eq" $ CounterRec {crIndex = 1, crIndexInScope = M.singleton Nothing 1}) ) it "Labels equations in the middle of text" $ @@ -179,7 +180,7 @@ main = hspec $ do text "This is an equation: " <> spanWith ("eq:equation", [], []) (equation' "a^2+b^2=c^2\\qquad(1)" []) <> text " it should be labeled", - (referenceData =: M.fromList $ refRec'' "eq:equation" 1) . + (referenceData =: M.fromList $ refRec' "eq:equation" 1 (math "a^2+b^2=c^2") "1") . (pfxCounter =: M.singleton "eq" $ CounterRec {crIndex = 1, crIndexInScope = M.singleton Nothing 1}) ) it "Labels equations in the beginning of text" $ @@ -189,7 +190,7 @@ main = hspec $ do (para $ spanWith ("eq:equation", [], []) (equation' "a^2+b^2=c^2\\qquad(1)" []) <> text " it should be labeled", - (referenceData =: M.fromList $ refRec'' "eq:equation" 1) . + (referenceData =: M.fromList $ refRec' "eq:equation" 1 (math "a^2+b^2=c^2") "1") . (pfxCounter =: M.singleton "eq" $ CounterRec {crIndex = 1, crIndexInScope = M.singleton Nothing 1}) ) it "Labels equations in the end of text" $ @@ -199,7 +200,7 @@ main = hspec $ do (para $ text "This is an equation: " <> spanWith ("eq:equation", [], []) (equation' "a^2+b^2=c^2\\qquad(1)" []), - (referenceData =: M.fromList $ refRec'' "eq:equation" 1) . + (referenceData =: M.fromList $ refRec' "eq:equation" 1 (math "a^2+b^2=c^2") "1") . (pfxCounter =: M.singleton "eq" $ CounterRec {crIndex = 1, crIndexInScope = M.singleton Nothing 1}) ) it "Labels tables" $ @@ -295,10 +296,10 @@ main = hspec $ do let template=Util.Template.makeTemplate (defaultMeta <> Settings (Meta (M.singleton "figureTitle" (toMetaValue $ text "Figure")))) (displayMath "figureTitle" <> displayMath "i" <> displayMath "t") - vf "i" = Just $ text "1" - vf "t" = Just $ text "title" + vf "i" = Just $ MetaInlines $ toList $ text "1" + vf "t" = Just $ MetaInlines $ toList $ text "title" vf _ = Nothing - in Util.Template.applyTemplate vf template `shouldBe` + in Util.Template.applyTemplate template vf `shouldBe` (str "Figure" <> str "1" <> str "title") describe "Citation groups shouldn't be separated (#22 regression test)" $ do @@ -379,19 +380,16 @@ citeGen p l = cite (mconcat $ map (cit . (p++) . show) l) $ text $ "[" ++ intercalate "; " (map (("@"++) . (p++) . show) l) ++ "]" refGen :: String -> [Int] -> [Int] -> M.Map String RefRec -refGen p l1 l2 = M.fromList $ mconcat $ zipWith refRec'' (((uncapitalizeFirst p++) . show) `map` l1) l2 +refGen p l1 l2 = M.fromList $ mconcat $ zipWith (\r i -> refRec' r i mempty mempty) (((uncapitalizeFirst p++) . show) `map` l1) l2 refGen' :: String -> [Int] -> [(Int, Int)] -> M.Map String RefRec refGen' p l1 l2 = M.fromList $ mconcat $ zipWith refRec''' (((uncapitalizeFirst p++) . show) `map` l1) l2 -refRec' :: String -> Int -> String -> String -> [(String, RefRec)] -refRec' ref i tit cap = [(ref, RefRec{refIndex=i, refIxInl = str $ show i, refCaption= text cap,refTitle=text tit,refScope=Nothing, refLevel=0, refPfx=takeWhile (/=':') ref, refLabel=ref})] - -refRec'' :: String -> Int -> [(String, RefRec)] -refRec'' ref i = refRec' ref i [] (show i) +refRec' :: String -> Int -> Inlines -> String -> [(String, RefRec)] +refRec' ref i tit cap = [(ref, RefRec{refIndex=i, refIxInl = str $ show i, refCaption= text cap,refTitle=tit,refScope=Nothing, refLevel=0, refPfx=takeWhile (/=':') ref, refLabel=ref, refAttrs = M.empty})] refRec''' :: String -> (Int, Int) -> [(String, RefRec)] -refRec''' ref (c,i) = [(ref, RefRec{refIndex=c+i,refIxInl = str $ show i, refCaption=str $ show i,refTitle=text [],refScope=Nothing, refLevel=0, refPfx=takeWhile (/=':') ref, refLabel=ref})] +refRec''' ref (c,i) = [(ref, RefRec{refIndex=c+i,refIxInl = str $ show i, refCaption=str $ show i,refTitle=text [],refScope=Nothing, refLevel=0, refPfx=takeWhile (/=':') ref, refLabel=ref, refAttrs = M.empty})] testRefs' :: String -> [Int] -> [Int] -> Accessor References (M.Map String RefRec) -> String -> Expectation testRefs' p l1 l2 prop res = testRefs (para $ citeGen p l1) (setVal prop (refGen p l1 l2) def) (para $ text res) From 814726444e5588b2ba424896cd9b863a17d61882 Mon Sep 17 00:00:00 2001 From: Nikolay Yakimov Date: Sat, 2 Mar 2019 18:57:52 +0300 Subject: [PATCH 054/134] More type safety in Refs and fix simple LaTeX capitalization --- lib/Text/Pandoc/CrossRef/References/Refs.hs | 200 +++++++++----------- test/m2m/capitalization/expect.tex | 12 +- test/m2m/ref-attrs/expect.tex | 12 +- test/m2m/scoping/expect.tex | 4 +- 4 files changed, 106 insertions(+), 122 deletions(-) diff --git a/lib/Text/Pandoc/CrossRef/References/Refs.hs b/lib/Text/Pandoc/CrossRef/References/Refs.hs index 195b4e4b..afc15df6 100644 --- a/lib/Text/Pandoc/CrossRef/References/Refs.hs +++ b/lib/Text/Pandoc/CrossRef/References/Refs.hs @@ -18,7 +18,7 @@ with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -} -{-# LANGUAGE RecordWildCards, NamedFieldPuns #-} +{-# LANGUAGE RecordWildCards, NamedFieldPuns, FlexibleInstances #-} module Text.Pandoc.CrossRef.References.Refs (replaceRefs) where @@ -30,6 +30,8 @@ import qualified Data.List.HT as HT import Data.Maybe import Data.Function import qualified Data.Map as M +import qualified Data.List.NonEmpty as NE +import Data.List.NonEmpty (NonEmpty(..)) import Control.Arrow as A import Data.Accessor.Monad.Trans.State @@ -40,29 +42,38 @@ import Text.Pandoc.CrossRef.Util.Options hiding (getRefPrefix) import Text.Pandoc.CrossRef.Util.Prefixes import Text.Pandoc.CrossRef.Util.VarFunction import Control.Applicative +import Data.Either import Debug.Trace import Prelude +groupEither :: [Either a b] -> [Either [a] [b]] +groupEither [] = [] +groupEither (Left x:xs) + = Left (x:lefts ys) : groupEither zs + where (ys,zs) = span isLeft xs +groupEither (Right x:xs) + = Right (x:rights ys) : groupEither zs + where (ys,zs) = span isRight xs + replaceRefs :: Options -> [Inline] -> WS [Inline] replaceRefs opts ils | Cite cits _:xs <- ils = do - refData <- mapM getRefData cits - toList . (<> fromList xs) . intercalate' (text ", ") <$> mapM replaceRefs' (groupBy eqPred refData) + citRefData <- groupEither <$> mapM getRefData cits + toList . (<> fromList xs) . intrclt <$> mapM replaceRefs' citRefData where - eqPred :: RefData -> RefData -> Bool + eqPred :: RefDataComplete -> RefDataComplete -> Bool eqPred = (==) `on` liftM2 (,) rdScope rdPrefix - replaceRefs' refs - | ref@RefDataComplete{} : _ <- refs - = replaceRefs'' (fromJust $ rdPrefix ref) opts refs - | otherwise = return $ cite cits' il' + intrclt = intercalate' (text ", ") + replaceRefs' (Left xs) = restoreCits' xs + replaceRefs' (Right xs) = intrclt <$> mapM replaceRefs'' (NE.groupBy eqPred xs) + restoreCits' refs = return $ cite cits' il' where - cits' = mapMaybe getCit refs + cits' = map getCit refs getCit RefDataIncomplete{rdCitation, rdiLabel} | takeWhile (/=':') rdiLabel `elem` M.keys (prefixes opts) - = trace ("Undefined cross-reference: " ++ rdiLabel) $ Just rdCitation - | otherwise = Just rdCitation - getCit RefDataComplete{} = error "Converting RefDataComplete back to Citation. This should not happen, please report a bug" + = trace ("Undefined cross-reference: " ++ rdiLabel) rdCitation + | otherwise = rdCitation il' = str "[" <> intercalate' (text "; ") (map citationToInlines cits') <> str "]" @@ -70,8 +81,8 @@ replaceRefs opts ils fromList (citationPrefix c) <> text ("@" ++ citationId c) <> fromList (citationSuffix c) replaceRefs'' - | isLatexFormat (outFormat opts) = replaceRefsLatex - | otherwise = replaceRefsOther + | isLatexFormat (outFormat opts) = replaceRefsLatex opts + | otherwise = replaceRefsOther opts replaceRefs _ x = return x getRefPrefix :: Options -> Bool -> Int -> RefRec -> Inlines -> Inlines @@ -82,99 +93,77 @@ getRefPrefix opts capitalize num rr@RefRec{..} cit = vf "n" = Just $ MetaString $ show num vf x = fix defaultVarFunc rr x -replaceRefsLatex :: String -> Options -> [RefData] -> WS Inlines -replaceRefsLatex prefix opts cits +replaceRefsLatex :: Options -> NonEmpty RefDataComplete -> WS Inlines +replaceRefsLatex opts cits | cref opts - = replaceRefsLatex' prefix opts cits + = return . rawInline "tex" $ cref'++"{"++listLabels "" "," "" cits++"}" | otherwise = intercalate' (text ", ") <$> - mapM (replaceRefsLatex' prefix opts) (groupBy citationGroupPred cits) - -replaceRefsLatex' :: String -> Options -> [RefData] -> WS Inlines -replaceRefsLatex' prefix opts cits = - return $ p texcit + mapM (replaceRefsLatex' opts) (NE.groupBy citationGroupPred cits) where - texcit = rawInline "tex" $ - if cref opts then - cref'++"{"++listLabels prefix "" "," "" cits++"}" - else - listLabels prefix "\\ref{" ", " "}" cits - RefDataComplete{..} = head cits - p | cref opts = id - | rdSuppressPrefix - = id - | isNothing rdCitPrefix - = getRefPrefix opts cap (length cits - 1) rdRec - | otherwise = ((fromJust rdCitPrefix <> space) <>) - cap = maybe False isFirstUpper $ getLabelPrefix opts . rdLabel . head $ cits + RefDataComplete{rdSuppressPrefix, rdUpperCase} = NE.head cits cref' | rdSuppressPrefix = "\\labelcref" - | cap = "\\Cref" + | rdUpperCase = "\\Cref" | otherwise = "\\cref" -listLabels :: String -> String -> String -> String -> [RefData] -> String -listLabels _prefix p sep s = - intercalate sep . map ((p ++) . (++ s) . mkLaTeXLabel' . rdLabel) +replaceRefsLatex' :: Options -> NonEmpty RefDataComplete -> WS Inlines +replaceRefsLatex' opts cits + = return . writePrefix opts cits . rawInline "tex" + $ listLabels "\\ref{" ", " "}" cits -getLabelPrefix :: Options -> String -> Maybe String -getLabelPrefix opts lab - | uncapitalizeFirst p `elem` prefixList opts = Just p - | otherwise = Nothing - where p = takeWhile (/=':') lab +listLabels :: String -> String -> String -> NonEmpty RefDataComplete -> String +listLabels p sep s = intercalate sep . NE.toList . NE.map ((p ++) . (++ s) . mkLaTeXLabel' . rdLabel) -replaceRefsOther :: String -> Options -> [RefData] -> WS Inlines -replaceRefsOther prefix opts cits = intercalate' (text ", ") <$> - mapM (replaceRefsOther' prefix opts) (groupBy citationGroupPred cits) +replaceRefsOther :: Options -> NonEmpty RefDataComplete -> WS Inlines +replaceRefsOther opts cits = intercalate' (text ", ") <$> + mapM (replaceRefsOther' opts) (NE.groupBy citationGroupPred cits) -citationGroupPred :: RefData -> RefData -> Bool +citationGroupPred :: RefDataComplete -> RefDataComplete -> Bool citationGroupPred = (==) `on` liftM2 (,) rdCitPrefix rdSuppressPrefix -replaceRefsOther' :: String -> Options -> [RefData] -> WS Inlines -replaceRefsOther' _prefix opts indices = do +replaceRefsOther' :: Options -> NonEmpty RefDataComplete -> WS Inlines +replaceRefsOther' opts indices = do let - RefDataComplete{..} = head indices - cap = rdUpperCase - writePrefix | rdSuppressPrefix - = id - | isNothing rdCitPrefix - = cmap $ getRefPrefix opts cap (length indices - 1) rdRec - | otherwise - = cmap ((fromJust rdCitPrefix <> space) <>) cmap f x | nameInLink opts , [Link attr t (y, z)] <- toList x = linkWith attr y z (f $ fromList t) cmap f x = f x - return $ writePrefix (makeIndices opts indices) - -data RefData = RefDataIncomplete - { rdiLabel :: String - , rdSuffix :: Inlines - , rdCitation :: Citation - } - | RefDataComplete - { rdRec :: RefRec - , rdSuffix :: Inlines - , rdCitPrefix :: Maybe Inlines - , rdUpperCase :: Bool - , rdSuppressPrefix :: Bool - } deriving (Eq, Show) - -rdIdx :: RefData -> Maybe Int -rdIdx RefDataIncomplete{} = Nothing -rdIdx RefDataComplete{rdRec} = Just $ refIndex rdRec - -rdScope :: RefData -> Maybe RefRec -rdScope RefDataIncomplete{} = Nothing + return $ cmap (writePrefix opts indices) (makeIndices opts indices) + +writePrefix :: Options -> NonEmpty RefDataComplete -> Inlines -> Inlines +writePrefix opts (RefDataComplete{..}:|rds) + | rdSuppressPrefix = id + | isNothing rdCitPrefix = getRefPrefix opts rdUpperCase (length rds) rdRec + | otherwise = ((fromJust rdCitPrefix <> space) <>) + +data RefDataIncomplete = RefDataIncomplete + { rdiLabel :: String + , rdiSuffix :: Inlines + , rdCitation :: Citation + } +data RefDataComplete = RefDataComplete + { rdRec :: RefRec + , rdcSuffix :: Inlines + , rdCitPrefix :: Maybe Inlines + , rdUpperCase :: Bool + , rdSuppressPrefix :: Bool + } deriving (Eq, Show) + +type RefData = Either RefDataIncomplete RefDataComplete + +rdIdx :: RefDataComplete -> Int +rdIdx RefDataComplete{rdRec} = refIndex rdRec + +rdScope :: RefDataComplete -> Maybe RefRec rdScope RefDataComplete{rdRec} = refScope rdRec -rdPrefix :: RefData -> Maybe String -rdPrefix RefDataIncomplete{} = Nothing -rdPrefix RefDataComplete{rdRec} = Just $ refPfx rdRec +rdPrefix :: RefDataComplete -> String +rdPrefix RefDataComplete{rdRec} = refPfx rdRec -rdLabel :: RefData -> String -rdLabel RefDataIncomplete{rdiLabel} = rdiLabel +rdLabel :: RefDataComplete -> String rdLabel RefDataComplete{rdRec} = refLabel rdRec -instance Ord RefData where +instance Ord RefDataComplete where (<=) = (<=) `on` rdIdx getRefData :: Citation -> WS RefData @@ -182,14 +171,14 @@ getRefData c@Citation{..} = do ref <- M.lookup llab <$> get referenceData return $ case ref of - Nothing -> RefDataIncomplete + Nothing -> Left $ RefDataIncomplete { rdiLabel = llab - , rdSuffix = suf' + , rdiSuffix = suf' , rdCitation = c } - Just x -> RefDataComplete + Just x -> Right $ RefDataComplete { rdRec = x - , rdSuffix = suf' + , rdcSuffix = suf' , rdCitPrefix = if null citationPrefix then Nothing else Just $ fromList citationPrefix @@ -199,19 +188,18 @@ getRefData c@Citation{..} where llab = uncapitalizeFirst citationId suf' = fromList citationSuffix -data RefItem = RefRange RefData RefData | RefSingle RefData +data RefItem = RefRange RefDataComplete RefDataComplete | RefSingle RefDataComplete -makeIndices :: Options -> [RefData] -> Inlines -makeIndices o s = format $ concatMap f $ HT.groupBy g $ sort $ nub s +makeIndices :: Options -> NonEmpty RefDataComplete -> Inlines +makeIndices o s = format $ concatMap f $ HT.groupBy g $ sort $ nub $ NE.toList s where - g :: RefData -> RefData -> Bool - g a b = all (null . rdSuffix) [a, b] && ( - fromMaybe False ((liftM2 follows `on` rdIdx) b a) && - ((==) `on` rdScope) a b - ) + g :: RefDataComplete -> RefDataComplete -> Bool + g a b = all (null . rdcSuffix) [a, b] + && (follows `on` rdIdx) b a + && ((==) `on` rdScope) a b follows :: Int -> Int -> Bool follows a b = b + 1 == a - f :: [RefData] -> [RefItem] + f :: [RefDataComplete] -> [RefItem] f [] = [] -- drop empty lists f [w] = [RefSingle w] -- single value f [w1,w2] = [RefSingle w1, RefSingle w2] -- two values @@ -220,22 +208,18 @@ makeIndices o s = format $ concatMap f $ HT.groupBy g $ sort $ nub s format [] = mempty format [x] = show'' x format [x, y] = show'' x <> pairDelim o <> show'' y - format xs = intercalate' (refDelim o) init' <> lastDelim o <> last' - where initlast [] = error "emtpy list in initlast" - initlast [y] = ([], y) - initlast (y:ys) = first (y:) $ initlast ys - (init', last') = initlast $ map show'' xs + format (x:xs) = intercalate' (refDelim o) init' <> lastDelim o <> last' + where initlast (y :| []) = ([], y) + initlast (y :| (z:zs)) = first (y:) $ initlast (z:|zs) + (init', last') = initlast $ NE.map show'' (x:|xs) show'' :: RefItem -> Inlines show'' (RefSingle x) = show' x show'' (RefRange x y) = show' x <> rangeDelim o <> show' y - show' :: RefData -> Inlines + show' :: RefDataComplete -> Inlines show' RefDataComplete{..} | linkReferences o = link ('#':refLabel rdRec) "" txt | otherwise = txt - where txt = applyIndexTemplate o rdSuffix rdRec - show' RefDataIncomplete{..} = - error ("Undefined cross-reference: " <> rdiLabel - <> ". This should not be possible, please report a bug") + where txt = applyIndexTemplate o rdcSuffix rdRec applyIndexTemplate :: Options -> Inlines -> RefRec -> Inlines applyIndexTemplate opts suf rr = diff --git a/test/m2m/capitalization/expect.tex b/test/m2m/capitalization/expect.tex index 686895e1..855d9900 100644 --- a/test/m2m/capitalization/expect.tex +++ b/test/m2m/capitalization/expect.tex @@ -23,14 +23,14 @@ \bottomrule \end{longtable} -eq.~\ref{eq:1}, eq.~\ref{eq:1}, fig.~\ref{fig:1}, fig.~\ref{fig:1}, -tbl.~\ref{tbl:1}, tbl.~\ref{tbl:1} +eq.~\ref{eq:1}, Eq.~\ref{eq:1}, fig.~\ref{fig:1}, Fig.~\ref{fig:1}, +tbl.~\ref{tbl:1}, Tbl.~\ref{tbl:1} -eq.~\ref{eq:1}, eq.~\ref{eq:1}, fig.~\ref{fig:1}, fig.~\ref{fig:1}, -tbl.~\ref{tbl:1}, tbl.~\ref{tbl:1} +eq.~\ref{eq:1}, Eq.~\ref{eq:1}, fig.~\ref{fig:1}, Fig.~\ref{fig:1}, +tbl.~\ref{tbl:1}, Tbl.~\ref{tbl:1} eqs.~\ref{eq:1}, \ref{eq:1}, figs.~\ref{fig:1}, \ref{fig:1}, tbls.~\ref{tbl:1}, \ref{tbl:1} -eqs.~\ref{eq:1}, \ref{eq:1}, figs.~\ref{fig:1}, \ref{fig:1}, -tbls.~\ref{tbl:1}, \ref{tbl:1} +Eqs.~\ref{eq:1}, \ref{eq:1}, Figs.~\ref{fig:1}, \ref{fig:1}, +Tbls.~\ref{tbl:1}, \ref{tbl:1} diff --git a/test/m2m/ref-attrs/expect.tex b/test/m2m/ref-attrs/expect.tex index 5d0ac3ce..f94ec9a4 100644 --- a/test/m2m/ref-attrs/expect.tex +++ b/test/m2m/ref-attrs/expect.tex @@ -36,17 +36,17 @@ This should have normal prefix: figs.~\ref{fig:3}, \ref{fig:1}, \ref{fig:2} -This should have custom prefix (capitalized): img.~\ref{fig:1} +This should have custom prefix (capitalized): Img.~\ref{fig:1} -This should have custom prefix (capitalized): img.~\ref{fig:2} +This should have custom prefix (capitalized): Img.~\ref{fig:2} -This should have normal prefix (capitalized): fig.~\ref{fig:3} +This should have normal prefix (capitalized): Fig.~\ref{fig:3} This should have custom prefix (capitalized): -imgs.~\ref{fig:1}, \ref{fig:2} +Imgs.~\ref{fig:1}, \ref{fig:2} This should have custom prefix (capitalized): -imgs.~\ref{fig:1}, \ref{fig:2}, \ref{fig:3} +Imgs.~\ref{fig:1}, \ref{fig:2}, \ref{fig:3} This should have normal prefix (capitalized): -figs.~\ref{fig:3}, \ref{fig:1}, \ref{fig:2} +Figs.~\ref{fig:3}, \ref{fig:1}, \ref{fig:2} diff --git a/test/m2m/scoping/expect.tex b/test/m2m/scoping/expect.tex index d02a982e..6ce7b7b8 100644 --- a/test/m2m/scoping/expect.tex +++ b/test/m2m/scoping/expect.tex @@ -64,7 +64,7 @@ \section{\texorpdfstring{\label{section-3}Section \item cl.~\ref{cl:addgp} \item - cl.~\ref{cl:multmon} + Cl.~\ref{cl:multmon} \item - cl.~\ref{cl:distrib} + Cl.~\ref{cl:distrib} \end{itemize} From d4d27b032663dbce06ca1de69c241471612899ab Mon Sep 17 00:00:00 2001 From: Nikolay Yakimov Date: Sun, 3 Mar 2019 07:47:19 +0300 Subject: [PATCH 055/134] Move towards using monad stack to report errors/warnings Main thing: don't error out on undefined prefixes --- lib/Text/Pandoc/CrossRef.hs | 47 +++--- lib/Text/Pandoc/CrossRef/References/Blocks.hs | 33 ++-- lib/Text/Pandoc/CrossRef/References/List.hs | 15 +- lib/Text/Pandoc/CrossRef/References/Refs.hs | 28 ++-- lib/Text/Pandoc/CrossRef/References/Types.hs | 48 +----- .../Pandoc/CrossRef/References/Types/Monad.hs | 68 +++++++++ .../Pandoc/CrossRef/References/Types/Ref.hs | 70 +++++++++ lib/Text/Pandoc/CrossRef/Util/ModifyMeta.hs | 143 +++++++++--------- lib/Text/Pandoc/CrossRef/Util/Options.hs | 49 +++--- .../Pandoc/CrossRef/Util/Options/Types.hs | 42 +++++ lib/Text/Pandoc/CrossRef/Util/Prefixes.hs | 35 +---- .../Pandoc/CrossRef/Util/Prefixes/Types.hs | 41 +++++ lib/Text/Pandoc/CrossRef/Util/Replace.hs | 70 +++++++++ lib/Text/Pandoc/CrossRef/Util/Settings.hs | 8 +- lib/Text/Pandoc/CrossRef/Util/Template.hs | 6 +- .../Pandoc/CrossRef/Util/Template/Types.hs | 29 ++++ lib/Text/Pandoc/CrossRef/Util/Util.hs | 63 +++----- package.yaml | 1 - pandoc-crossref.cabal | 21 ++- test/m2m/undefined-prefix/expect.md | 2 + test/m2m/undefined-prefix/expect.tex | 2 + test/m2m/undefined-prefix/input.md | 2 + 22 files changed, 523 insertions(+), 300 deletions(-) create mode 100644 lib/Text/Pandoc/CrossRef/References/Types/Monad.hs create mode 100644 lib/Text/Pandoc/CrossRef/References/Types/Ref.hs create mode 100644 lib/Text/Pandoc/CrossRef/Util/Options/Types.hs create mode 100644 lib/Text/Pandoc/CrossRef/Util/Prefixes/Types.hs create mode 100644 lib/Text/Pandoc/CrossRef/Util/Replace.hs create mode 100644 lib/Text/Pandoc/CrossRef/Util/Template/Types.hs create mode 100644 test/m2m/undefined-prefix/expect.md create mode 100644 test/m2m/undefined-prefix/expect.tex create mode 100644 test/m2m/undefined-prefix/input.md diff --git a/lib/Text/Pandoc/CrossRef.hs b/lib/Text/Pandoc/CrossRef.hs index 50da0fac..06379c83 100644 --- a/lib/Text/Pandoc/CrossRef.hs +++ b/lib/Text/Pandoc/CrossRef.hs @@ -81,29 +81,21 @@ module Text.Pandoc.CrossRef ( ) where import Control.Monad.State -import qualified Control.Monad.Reader as R -import Text.Pandoc +import Control.Monad.Except +import Control.Monad.Writer as W +import Control.Monad.Reader as R +import Text.Pandoc as P import Data.Monoid ((<>)) import Text.Pandoc.CrossRef.References import Text.Pandoc.CrossRef.Util.Settings -import Text.Pandoc.CrossRef.Util.Options as O import Text.Pandoc.CrossRef.Util.ModifyMeta import Text.Pandoc.CrossRef.Util.Settings.Gen as SG --- | Enviromnent for 'CrossRefM' -data CrossRefEnv = CrossRefEnv { - creSettings :: Settings -- ^Metadata settings - , creOptions :: Options -- ^Internal pandoc-crossref options - } - --- | Essentially a reader monad for basic pandoc-crossref environment -type CrossRefM a = R.Reader CrossRefEnv a - {- | Walk over blocks, while inserting cross-references, list-of, etc. Works in 'CrossRefM' monad. -} -crossRefBlocks :: [Block] -> CrossRefM [Block] +crossRefBlocks :: [Block] -> CrossRef [Block] crossRefBlocks blocks = do opts <- R.asks creOptions let @@ -111,7 +103,7 @@ crossRefBlocks blocks = do replaceAll opts blocks >>= bottomUpM (replaceRefs opts) >>= bottomUpM (listOf opts) - return $ evalState doWalk def + CrossRef $ flip evalStateT def . unWS $ doWalk {- | Modifies metadata for LaTeX output, adding header-includes instructions to setup custom and builtin environments. @@ -119,16 +111,13 @@ to setup custom and builtin environments. Note, that if output format is not "latex", this function does nothing. Works in 'CrossRefM' monad. -} -crossRefMeta :: CrossRefM Meta -crossRefMeta = do - opts <- R.asks creOptions - dtv <- R.asks creSettings - return $ modifyMeta opts dtv +crossRefMeta :: CrossRef Meta +crossRefMeta = modifyMeta {- | Combines 'crossRefMeta' and 'crossRefBlocks' Works in 'CrossRefM' monad. -} -defaultCrossRefAction :: Pandoc -> CrossRefM Pandoc +defaultCrossRefAction :: Pandoc -> CrossRef Pandoc defaultCrossRefAction (Pandoc _ bs) = do meta' <- crossRefMeta bs' <- crossRefBlocks bs @@ -137,8 +126,9 @@ defaultCrossRefAction (Pandoc _ bs) = do {- | Run an action in 'CrossRefM' monad with argument, and return pure result. This is primary function to work with 'CrossRefM' -} -runCrossRef :: forall a b. Meta -> Maybe Format -> (a -> CrossRefM b) -> a -> b -runCrossRef meta fmt action arg = R.runReader (action arg) env +runCrossRef :: forall a b. Meta -> Maybe Format -> (a -> CrossRef b) -> a -> (Either WSException b, [String]) +runCrossRef meta fmt action arg = + flip runReader env . runWriterT . runExceptT . unCrossRef $ action arg where settings = Settings meta <> defaultMeta env = CrossRefEnv { @@ -150,12 +140,9 @@ runCrossRef meta fmt action arg = R.runReader (action arg) env This function will attempt to read pandoc-crossref settings from settings file specified by crossrefYaml metadata field. -} -runCrossRefIO :: forall a b. Meta -> Maybe Format -> (a -> CrossRefM b) -> a -> IO b +runCrossRefIO :: forall a b. Meta -> Maybe Format -> (a -> CrossRef b) -> a -> IO b runCrossRefIO meta fmt action arg = do - settings <- getSettings fmt meta - let - env = CrossRefEnv { - creSettings = settings - , creOptions = getOptions settings fmt - } - return $ R.runReader (action arg) env + Settings meta' <- readSettings fmt meta + let (res, lg) = runCrossRef meta' fmt action arg + mapM_ putStrLn lg + return $ either (error . pretty) id res diff --git a/lib/Text/Pandoc/CrossRef/References/Blocks.hs b/lib/Text/Pandoc/CrossRef/References/Blocks.hs index 89f855e5..120de11b 100644 --- a/lib/Text/Pandoc/CrossRef/References/Blocks.hs +++ b/lib/Text/Pandoc/CrossRef/References/Blocks.hs @@ -32,7 +32,6 @@ import Data.Maybe import Data.Monoid import qualified Data.Map as M -import Data.Accessor.Monad.Trans.State import Text.Pandoc.CrossRef.References.Types as Types import Text.Pandoc.CrossRef.Util.Util import Text.Pandoc.CrossRef.Util.Options @@ -40,6 +39,7 @@ import Text.Pandoc.CrossRef.Util.Prefixes import Text.Pandoc.CrossRef.Util.Template import Text.Pandoc.CrossRef.Util.CodeBlockCaptions import Text.Pandoc.CrossRef.Util.VarFunction +import Text.Pandoc.CrossRef.Util.Replace import Control.Applicative import Control.Arrow (second) import Data.Default (def) @@ -77,7 +77,7 @@ replaceElement opts scope (Sec n ns (label, cls, attrs) text' body) = do let title' = B.toList $ case outFormat opts of f | isLatexFormat f -> B.rawInline "latex" (mkLaTeXLabel label) <> ititle - _ -> applyTitleTemplate opts rec' + _ -> applyTitleTemplate rec' replaceRecurse (newScope rec' scope) $ Sec n ns (label', cls, attrs) title' body replaceElement _ scope _ = noReplaceRecurse scope @@ -91,7 +91,7 @@ replaceBlock opts scope (Div divOps@(label,_,attrs) [Table title align widths he let title' = B.toList $ case outFormat opts of f | isLatexFormat f -> B.rawInline "latex" (mkLaTeXLabel label) <> ititle - _ -> applyTitleTemplate opts idxStr + _ -> applyTitleTemplate idxStr replaceNoRecurse $ Div divOps [Table title' align widths header cells] replaceBlock opts scope (Div (label,"listing":_, []) [Para caption, CodeBlock ([],classes,attrs) code]) | not $ null label @@ -99,7 +99,7 @@ replaceBlock opts scope (Div (label,"listing":_, []) [Para caption, CodeBlock ([ = do let icaption = B.fromList caption idxStr <- replaceAttr opts scope (Right label) attrs icaption pfx - let caption' = applyTitleTemplate opts idxStr + let caption' = applyTitleTemplate idxStr replaceNoRecurse $ case outFormat opts of f --if used with listings package, return code block with caption | isLatexFormat f, listings opts -> @@ -161,7 +161,7 @@ replaceInline opts scope (Image attr@(label,_,attrs) alt img@(_, tit)) idxStr <- replaceAttr opts scope (Right label) attrs ialt pfx let alt' = B.toList $ case outFormat opts of f | isLatexFormat f -> ialt - _ -> applyTitleTemplate opts idxStr + _ -> applyTitleTemplate idxStr replaceNoRecurse $ Image attr alt' img replaceInline opts scope x@(Span (label,_,attrs) content) | Just pfx <- getRefPrefix opts label @@ -170,13 +170,13 @@ replaceInline opts scope x@(Span (label,_,attrs) content) replaceRecurse (newScope rec' scope) x replaceInline _ scope _ = noReplaceRecurse scope -applyTitleTemplate :: Options -> RefRec -> B.Inlines -applyTitleTemplate opts rr@RefRec{refPfx} = - applyTemplate (pfxCaptionTemplate opts refPfx) (fix defaultVarFunc rr) +applyTitleTemplate :: RefRec -> B.Inlines +applyTitleTemplate rr@RefRec{refPfxRec} = + applyTemplate (prefixCaptionTemplate refPfxRec) (fix defaultVarFunc rr) -applyTitleIndexTemplate :: Options -> RefRec -> B.Inlines -> B.Inlines -applyTitleIndexTemplate opts rr@RefRec{..} label = - applyTemplate (pfxCaptionIndexTemplate opts refPfx) vf +applyTitleIndexTemplate :: RefRec -> B.Inlines -> B.Inlines +applyTitleIndexTemplate rr@RefRec{..} label = + applyTemplate (prefixCaptionIndexTemplate refPfxRec) vf where vf "i" = Just $ MetaInlines $ B.toList label vf x = fix defaultVarFunc rr x @@ -218,8 +218,8 @@ spanInlines _ x = x replaceAttr :: Options -> Scope -> Either String String -> [(String, String)] -> B.Inlines -> String -> WS RefRec replaceAttr o scope label attrs title pfx = do - let ropt = getPfx o pfx - itemScope = find ((`elem` prefixScope ropt) . refPfx) scope + ropt <- liftEither $ getPfx o pfx + let itemScope = find ((`elem` prefixScope ropt) . refPfx) scope refLabel' = lookup "label" attrs cr <- (\CounterRec{..} -> CounterRec{ crIndex = crIndex+1 @@ -232,16 +232,17 @@ replaceAttr o scope label attrs title pfx lvl = length $ filter ((== pfx) . refPfx) scope customLabel = prefixNumbering ropt lvl hasLabel <- M.member label' <$> get referenceData - when hasLabel $ error $ "Duplicate label: " ++ label' + when hasLabel $ throwError $ WSEDuplicateLabel label' let rec' = RefRec { refIndex = i , refTitle = title , refLabel = label' - , refIxInl = applyTitleIndexTemplate o rec' $ B.text $ fromMaybe (customLabel iInSc) refLabel' + , refIxInl = applyTitleIndexTemplate rec' $ B.text $ fromMaybe (customLabel iInSc) refLabel' , refScope = itemScope , refLevel = lvl , refPfx = pfx - , refCaption = applyTitleTemplate o rec' + , refPfxRec = ropt + , refCaption = applyTitleTemplate rec' , refAttrs = M.fromListWith (flip (++)) $ map (second return) attrs } modify referenceData $ M.insert label' rec' diff --git a/lib/Text/Pandoc/CrossRef/References/List.hs b/lib/Text/Pandoc/CrossRef/References/List.hs index 92ffab10..2336cda7 100644 --- a/lib/Text/Pandoc/CrossRef/References/List.hs +++ b/lib/Text/Pandoc/CrossRef/References/List.hs @@ -24,7 +24,6 @@ module Text.Pandoc.CrossRef.References.List (listOf) where import Text.Pandoc.Definition import Text.Pandoc.Builder -import Data.Accessor.Monad.Trans.State import Data.List import Data.Function import qualified Data.Map as M @@ -33,6 +32,7 @@ import Text.Pandoc.CrossRef.References.Types import Text.Pandoc.CrossRef.Util.Util import Text.Pandoc.CrossRef.Util.Options import Text.Pandoc.CrossRef.Util.Template +import Text.Pandoc.CrossRef.Util.Prefixes.Types import Text.Pandoc.CrossRef.Util.VarFunction listOf :: Options -> [Block] -> WS [Block] @@ -58,16 +58,17 @@ getPfxData pfx = M.filterWithKey (\k _ -> (pfx <> ":") `isPrefixOf` k) <$> get r makeList :: Options -> String -> Blocks -> M.Map String RefRec -> WS Blocks makeList opts titlef xs refs - = return $ - getTitleForListOf opts titlef + = do + title <- liftEither $ getTitleForListOf opts titlef + return $ title <> divWith ("", ["list"], []) (mconcat $ map itemChap refsSorted) <> xs where refsSorted :: [RefRec] refsSorted = sortBy (compare `on` refIndex) $ M.elems refs itemChap :: RefRec -> Blocks - itemChap = para . applyListItemTemplate opts + itemChap = para . applyListItemTemplate -applyListItemTemplate :: Options -> RefRec -> Inlines -applyListItemTemplate opts rr@RefRec{refPfx} = - applyTemplate (pfxListItemTemplate opts refPfx) (fix defaultVarFunc rr) +applyListItemTemplate :: RefRec -> Inlines +applyListItemTemplate rr@RefRec{refPfxRec} = + applyTemplate (prefixListItemTemplate refPfxRec) (fix defaultVarFunc rr) diff --git a/lib/Text/Pandoc/CrossRef/References/Refs.hs b/lib/Text/Pandoc/CrossRef/References/Refs.hs index afc15df6..b0f617ee 100644 --- a/lib/Text/Pandoc/CrossRef/References/Refs.hs +++ b/lib/Text/Pandoc/CrossRef/References/Refs.hs @@ -18,7 +18,7 @@ with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -} -{-# LANGUAGE RecordWildCards, NamedFieldPuns, FlexibleInstances #-} +{-# LANGUAGE RecordWildCards, NamedFieldPuns, FlexibleInstances, FlexibleContexts #-} module Text.Pandoc.CrossRef.References.Refs (replaceRefs) where @@ -34,7 +34,6 @@ import qualified Data.List.NonEmpty as NE import Data.List.NonEmpty (NonEmpty(..)) import Control.Arrow as A -import Data.Accessor.Monad.Trans.State import Text.Pandoc.CrossRef.References.Types import Text.Pandoc.CrossRef.Util.Template import Text.Pandoc.CrossRef.Util.Util @@ -43,7 +42,6 @@ import Text.Pandoc.CrossRef.Util.Prefixes import Text.Pandoc.CrossRef.Util.VarFunction import Control.Applicative import Data.Either -import Debug.Trace import Prelude groupEither :: [Either a b] -> [Either [a] [b]] @@ -67,15 +65,17 @@ replaceRefs opts ils intrclt = intercalate' (text ", ") replaceRefs' (Left xs) = restoreCits' xs replaceRefs' (Right xs) = intrclt <$> mapM replaceRefs'' (NE.groupBy eqPred xs) - restoreCits' refs = return $ cite cits' il' + restoreCits' refs = liftM2 cite cits' il' where - cits' = map getCit refs + cits' = mapM getCit refs getCit RefDataIncomplete{rdCitation, rdiLabel} | takeWhile (/=':') rdiLabel `elem` M.keys (prefixes opts) - = trace ("Undefined cross-reference: " ++ rdiLabel) rdCitation - | otherwise = rdCitation - il' = str "[" - <> intercalate' (text "; ") (map citationToInlines cits') + = tell ["Undefined cross-reference: " <> rdiLabel] >> return rdCitation + | otherwise = return rdCitation + il' = do + i <- map citationToInlines <$> cits' + return $ str "[" + <> intercalate' (text "; ") i <> str "]" citationToInlines c = fromList (citationPrefix c) <> text ("@" ++ citationId c) @@ -147,7 +147,7 @@ data RefDataComplete = RefDataComplete , rdCitPrefix :: Maybe Inlines , rdUpperCase :: Bool , rdSuppressPrefix :: Bool - } deriving (Eq, Show) + } type RefData = Either RefDataIncomplete RefDataComplete @@ -163,8 +163,11 @@ rdPrefix RefDataComplete{rdRec} = refPfx rdRec rdLabel :: RefDataComplete -> String rdLabel RefDataComplete{rdRec} = refLabel rdRec +instance Eq RefDataComplete where + (==) = (==) `on` rdRec + instance Ord RefDataComplete where - (<=) = (<=) `on` rdIdx + (<=) = (<=) `on` rdRec getRefData :: Citation -> WS RefData getRefData c@Citation{..} @@ -228,8 +231,7 @@ applyIndexTemplate opts suf rr = varsSc rr' x = defaultVarFunc varsSc rr' x vars _ "suf" = Just $ MetaInlines $ toList suf vars rr' x = defaultVarFunc varsSc rr' x - template = prefixReferenceIndexTemplate pfxRec - pfxRec = getPfx opts (refPfx rr) + template = prefixReferenceIndexTemplate $ refPfxRec rr inlines cap ref = MetaInlines $ toList $ getRefPrefix opts cap 0 ref $ applyIndexTemplate opts mempty ref in applyTemplate template (vars rr) diff --git a/lib/Text/Pandoc/CrossRef/References/Types.hs b/lib/Text/Pandoc/CrossRef/References/Types.hs index 98e2489d..e146f680 100644 --- a/lib/Text/Pandoc/CrossRef/References/Types.hs +++ b/lib/Text/Pandoc/CrossRef/References/Types.hs @@ -18,47 +18,9 @@ with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -} -{-# LANGUAGE TemplateHaskell #-} -module Text.Pandoc.CrossRef.References.Types where +module Text.Pandoc.CrossRef.References.Types ( + module X +) where -import qualified Data.Map as M -import Control.Monad.State -import Data.Default -import Data.Accessor.Template -import Text.Pandoc.Builder - -data RefRec = RefRec { refIndex :: !Int -- global ordinal number for prefix - , refIxInl :: Inlines -- index as inilnes - , refTitle :: !Inlines -- title text - , refScope :: !(Maybe RefRec) -- reference to parent label - , refLevel :: !Int -- number of upper scopes of the same prefix - , refLabel :: !String -- label, i.e. pfx:label string - , refPfx :: !String -- reference prefix, the part in label before : - , refCaption :: Inlines -- caption after applying template; must be non-strict - , refAttrs :: !(M.Map String [String]) -- attribute map - } deriving (Show, Eq, Ord) - -type RefMap = M.Map String RefRec - --- state data type -data References = References { referenceData_ :: !RefMap - , pfxCounter_ :: !(M.Map String CounterRec) - } deriving (Show, Eq) - -data CounterRec = CounterRec { - crIndex :: Int - , crIndexInScope :: M.Map (Maybe RefRec) Int - } deriving (Show, Eq) - ---state monad -type WS a = State References a - -type Scope = [RefRec] - -instance Default References where - def = References M.empty M.empty - -instance Default CounterRec where - def = CounterRec 0 M.empty - -deriveAccessors ''References +import Text.Pandoc.CrossRef.References.Types.Ref as X +import Text.Pandoc.CrossRef.References.Types.Monad as X diff --git a/lib/Text/Pandoc/CrossRef/References/Types/Monad.hs b/lib/Text/Pandoc/CrossRef/References/Types/Monad.hs new file mode 100644 index 00000000..fc1fd4ca --- /dev/null +++ b/lib/Text/Pandoc/CrossRef/References/Types/Monad.hs @@ -0,0 +1,68 @@ +{- +pandoc-crossref is a pandoc filter for numbering figures, +equations, tables and cross-references to them. +Copyright (C) 2019 Nikolay Yakimov + +This program is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License along +with this program; if not, write to the Free Software Foundation, Inc., +51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +-} + +{-# LANGUAGE GeneralizedNewtypeDeriving #-} +module Text.Pandoc.CrossRef.References.Types.Monad ( + module Text.Pandoc.CrossRef.References.Types.Monad + , module X +) where + +import Text.Pandoc.CrossRef.References.Types.Ref +import Text.Pandoc.CrossRef.Util.Options.Types +import Text.Pandoc.CrossRef.Util.Settings.Types +import Control.Monad.State +import Control.Monad.Reader as X +import Control.Monad.Writer as X +import Control.Monad.Except as X +import qualified Control.Monad.Fail as Fail + +data WSException = WSENoSuchPrefix String + | WSEDuplicateLabel String + | WSEFail String + +type PureErr a = Either WSException a + +-- | Enviromnent for 'CrossRefM' +data CrossRefEnv = CrossRefEnv { + creSettings :: Settings -- ^Metadata settings + , creOptions :: Options -- ^Internal pandoc-crossref options + } + +-- | Essentially a reader monad for basic pandoc-crossref environment +type CrossRefM = ExceptT WSException (WriterT [String] (Reader CrossRefEnv)) + +newtype CrossRef a = CrossRef { unCrossRef :: CrossRefM a } + deriving ( Functor, Applicative, Monad + , MonadError WSException, MonadReader CrossRefEnv + , MonadWriter [String] ) +--state monad +newtype WS a = WS { + unWS :: StateT References CrossRefM a + } deriving ( Functor, Applicative, Monad, MonadState References + , MonadError WSException, MonadReader CrossRefEnv + , MonadWriter [String] ) + +instance Fail.MonadFail WS where + fail s = throwError $ WSEFail s + +pretty :: WSException -> String +pretty (WSENoSuchPrefix s) = "No such prefix: " <> s +pretty (WSEDuplicateLabel s) = "Duplicate label: " <> s +pretty (WSEFail s) = "Generic failure: " <> s diff --git a/lib/Text/Pandoc/CrossRef/References/Types/Ref.hs b/lib/Text/Pandoc/CrossRef/References/Types/Ref.hs new file mode 100644 index 00000000..1efe1971 --- /dev/null +++ b/lib/Text/Pandoc/CrossRef/References/Types/Ref.hs @@ -0,0 +1,70 @@ +{- +pandoc-crossref is a pandoc filter for numbering figures, +equations, tables and cross-references to them. +Copyright (C) 2015 Nikolay Yakimov + +This program is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License along +with this program; if not, write to the Free Software Foundation, Inc., +51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +-} + +{-# LANGUAGE TemplateHaskell, GeneralizedNewtypeDeriving #-} +module Text.Pandoc.CrossRef.References.Types.Ref where + +import qualified Data.Map as M +import Control.Monad +import Data.Default +import Data.Function +import Data.Accessor.Template +import Text.Pandoc.Builder +import Text.Pandoc.CrossRef.Util.Prefixes.Types + +data RefRec = RefRec { refIndex :: !Int -- global ordinal number for prefix + , refIxInl :: Inlines -- index as inilnes + , refTitle :: !Inlines -- title text + , refScope :: !(Maybe RefRec) -- reference to parent label + , refLevel :: !Int -- number of upper scopes of the same prefix + , refLabel :: !String -- label, i.e. pfx:label string + , refPfx :: !String -- reference prefix, the part in label before : + , refPfxRec :: !Prefix -- reference prefix, the part in label before : + , refCaption :: Inlines -- caption after applying template; must be non-strict + , refAttrs :: !(M.Map String [String]) -- attribute map + } + +instance Eq RefRec where + (==) = (==) `on` liftM2 (,) refPfx refIndex + +instance Ord RefRec where + (<=) = (<=) `on` liftM2 (,) refPfx refIndex + +type RefMap = M.Map String RefRec + +-- state data type +data References = References { referenceData_ :: !RefMap + , pfxCounter_ :: !(M.Map String CounterRec) + } + +data CounterRec = CounterRec { + crIndex :: Int + , crIndexInScope :: M.Map (Maybe RefRec) Int + } + +type Scope = [RefRec] + +instance Default References where + def = References M.empty M.empty + +instance Default CounterRec where + def = CounterRec 0 M.empty + +deriveAccessors ''References diff --git a/lib/Text/Pandoc/CrossRef/Util/ModifyMeta.hs b/lib/Text/Pandoc/CrossRef/Util/ModifyMeta.hs index 41813b31..0d9523d3 100644 --- a/lib/Text/Pandoc/CrossRef/Util/ModifyMeta.hs +++ b/lib/Text/Pandoc/CrossRef/Util/ModifyMeta.hs @@ -18,6 +18,8 @@ with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -} +{-# LANGUAGE RecordWildCards #-} + module Text.Pandoc.CrossRef.Util.ModifyMeta ( modifyMeta @@ -28,20 +30,17 @@ import Text.Pandoc import Text.Pandoc.Shared (blocksToInlines) import Text.Pandoc.Builder hiding ((<>)) import Text.Pandoc.CrossRef.Util.Options +import Text.Pandoc.CrossRef.References.Types import Text.Pandoc.CrossRef.Util.Prefixes import Text.Pandoc.CrossRef.Util.Settings.Types import Text.Pandoc.CrossRef.Util.Util import qualified Data.Text as T -import Control.Monad.Writer -modifyMeta :: Options -> Settings -> Meta -modifyMeta opts meta - | isLatexFormat (outFormat opts) - = setMeta "header-includes" - (headerInc $ lookupSettings "header-includes" meta) - $ unSettings meta - | otherwise = unSettings meta - where +modifyMeta :: CrossRef Meta +modifyMeta = do + opts@Options{..} <- asks creOptions + settings <- asks creSettings + let headerInc :: Maybe MetaValue -> MetaValue headerInc Nothing = incList headerInc (Just (MetaList x)) = MetaList $ x ++ [incList] @@ -51,68 +50,74 @@ modifyMeta opts meta tell subfig tell floatnames tell listnames - unless (listings opts) $ + unless listings $ tell codelisting tell lolcommand - when (cref opts) $ do + when cref $ do tell cleveref - unless (listings opts) $ + unless listings $ tell cleverefCodelisting tell [ "\\makeatother" ] - where - subfig = [ - usepackage [] "subfig" - , usepackage [] "caption" - , "\\captionsetup[subfloat]{margin=0.5em}" - ] - floatnames = [ - "\\AtBeginDocument{%" - , "\\renewcommand*\\figurename{"++getFloatCaption "fig"++"}" - , "\\renewcommand*\\tablename{"++getFloatCaption "tbl"++"}" - , "}" - ] - listnames = [ - "\\AtBeginDocument{%" - , "\\renewcommand*\\listfigurename{"++getListOfTitle "fig"++"}" - , "\\renewcommand*\\listtablename{"++getListOfTitle "tbl"++"}" - , "}" - ] - codelisting = [ - usepackage [] "float" - , "\\floatstyle{ruled}" - , "\\@ifundefined{c@chapter}{\\newfloat{codelisting}{h}{lop}}{\\newfloat{codelisting}{h}{lop}[chapter]}" - , "\\floatname{codelisting}{"++getFloatCaption "lst"++"}" - ] - lolcommand - | listings opts = [ - "\\newcommand*\\listoflistings\\lstlistoflistings" - , "\\AtBeginDocument{%" - , "\\renewcommand*{\\lstlistlistingname}{"++getListOfTitle "lst"++"}" - , "}" - ] - | otherwise = ["\\newcommand*\\listoflistings{\\listof{codelisting}{"++getListOfTitle "lst"++"}}"] - cleveref = [ usepackage cleverefOpts "cleveref" ] - -- <> crefname "figure" (pfxRef "fig") - -- <> crefname "table" (pfxRef "tbl") - -- <> crefname "equation" (pfxRef "eq") - -- <> crefname "listing" (pfxRef "lst") - -- <> crefname "section" (pfxRef "sec") - -- pfxRef labelPrefix = prefixRef . flip getPfx labelPrefix - cleverefCodelisting = [ - "\\crefname{codelisting}{\\cref@listing@name}{\\cref@listing@name@plural}" - , "\\Crefname{codelisting}{\\Cref@listing@name}{\\Cref@listing@name@plural}" - ] - cleverefOpts | nameInLink opts = [ "nameinlink" ] - | otherwise = [] - -- crefname n f = [ - -- "\\crefname{" ++ n ++ "}" ++ prefix f False - -- , "\\Crefname{" ++ n ++ "}" ++ prefix f True - -- ] - usepackage [] p = "\\@ifpackageloaded{"++p++"}{}{\\usepackage{"++p++"}}" - usepackage xs p = "\\@ifpackageloaded{"++p++"}{}{\\usepackage"++o++"{"++p++"}}" - where o = "[" ++ intercalate "," xs ++ "]" - toLatex = either (error . show) T.unpack . runPure . writeLaTeX def . Pandoc nullMeta . return . Plain - getListOfTitle = toLatex . blocksToInlines . toList . getTitleForListOf opts - getFloatCaption = toLatex . toList . prefixTitle . getPfx opts - -- prefix f uc = "{" ++ toLatex (toList $ f opts uc 0) ++ "}" ++ - -- "{" ++ toLatex (toList $ f opts uc 1) ++ "}" + subfig = [ + usepackage [] "subfig" + , usepackage [] "caption" + , "\\captionsetup[subfloat]{margin=0.5em}" + ] + floatnames = [ + "\\AtBeginDocument{%" + , "\\renewcommand*\\figurename{"++getFloatCaption "fig"++"}" + , "\\renewcommand*\\tablename{"++getFloatCaption "tbl"++"}" + , "}" + ] + listnames = [ + "\\AtBeginDocument{%" + , "\\renewcommand*\\listfigurename{"++getListOfTitle "fig"++"}" + , "\\renewcommand*\\listtablename{"++getListOfTitle "tbl"++"}" + , "}" + ] + codelisting = [ + usepackage [] "float" + , "\\floatstyle{ruled}" + , "\\@ifundefined{c@chapter}{\\newfloat{codelisting}{h}{lop}}{\\newfloat{codelisting}{h}{lop}[chapter]}" + , "\\floatname{codelisting}{"++getFloatCaption "lst"++"}" + ] + lolcommand + | listings = [ + "\\newcommand*\\listoflistings\\lstlistoflistings" + , "\\AtBeginDocument{%" + , "\\renewcommand*{\\lstlistlistingname}{"++getListOfTitle "lst"++"}" + , "}" + ] + | otherwise = ["\\newcommand*\\listoflistings{\\listof{codelisting}{"++getListOfTitle "lst"++"}}"] + cleveref = [ usepackage cleverefOpts "cleveref" ] + -- <> crefname "figure" (pfxRef "fig") + -- <> crefname "table" (pfxRef "tbl") + -- <> crefname "equation" (pfxRef "eq") + -- <> crefname "listing" (pfxRef "lst") + -- <> crefname "section" (pfxRef "sec") + -- pfxRef labelPrefix = prefixRef . flip getPfx labelPrefix + cleverefCodelisting = [ + "\\crefname{codelisting}{\\cref@listing@name}{\\cref@listing@name@plural}" + , "\\Crefname{codelisting}{\\Cref@listing@name}{\\Cref@listing@name@plural}" + ] + cleverefOpts | nameInLink = [ "nameinlink" ] + | otherwise = [] + -- crefname n f = [ + -- "\\crefname{" ++ n ++ "}" ++ prefix f False + -- , "\\Crefname{" ++ n ++ "}" ++ prefix f True + -- ] + usepackage [] p = "\\@ifpackageloaded{"++p++"}{}{\\usepackage{"++p++"}}" + usepackage xs p = "\\@ifpackageloaded{"++p++"}{}{\\usepackage"++o++"{"++p++"}}" + where o = "[" ++ intercalate "," xs ++ "]" + toLatex = either (error . show) T.unpack . runPure . writeLaTeX def . Pandoc nullMeta . return . Plain + -- TODO: Log + getListOfTitle = either (const mempty) (toLatex . blocksToInlines . toList) . getTitleForListOf opts + getFloatCaption = either (const mempty) (toLatex . toList . prefixTitle) . getPfx opts + -- prefix f uc = "{" ++ toLatex (toList $ f opts uc 0) ++ "}" ++ + -- "{" ++ toLatex (toList $ f opts uc 1) ++ "}" + + return $ if isLatexFormat outFormat + then setMeta "header-includes" + (headerInc $ lookupSettings "header-includes" settings) + $ unSettings settings + else unSettings settings diff --git a/lib/Text/Pandoc/CrossRef/Util/Options.hs b/lib/Text/Pandoc/CrossRef/Util/Options.hs index 538637e4..cf979231 100644 --- a/lib/Text/Pandoc/CrossRef/Util/Options.hs +++ b/lib/Text/Pandoc/CrossRef/Util/Options.hs @@ -18,50 +18,37 @@ with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -} -module Text.Pandoc.CrossRef.Util.Options where +module Text.Pandoc.CrossRef.Util.Options ( + module Text.Pandoc.CrossRef.Util.Options + , module Text.Pandoc.CrossRef.Util.Options.Types +) where + import Text.Pandoc.Definition +import Text.Pandoc.CrossRef.Util.Options.Types +import Text.Pandoc.CrossRef.References.Types.Monad import Text.Pandoc.CrossRef.Util.Template import Text.Pandoc.CrossRef.Util.Prefixes import qualified Data.Map as M import Text.Pandoc.Builder -import Data.Maybe import Data.List import Data.List.Extra -import Text.Pandoc.CrossRef.Util.LatexPrefixes - -data Options = Options { cref :: Bool - , listings :: Bool - , codeBlockCaptions :: Bool - , autoSectionLabels :: Bool - , rangeDelim :: Inlines - , pairDelim :: Inlines - , lastDelim :: Inlines - , refDelim :: Inlines - , outFormat :: Maybe Format - , tableEqns :: Bool - , autoEqnLabels :: Bool - , linkReferences :: Bool - , nameInLink :: Bool - , prefixes :: Prefixes - , latexPrefixes :: LatexPrefixes - } prefixList :: Options -> [String] prefixList = M.keys . prefixes -pfxCaptionTemplate :: Options -> String -> Template -pfxCaptionTemplate opts pfx = prefixCaptionTemplate $ getPfx opts pfx +pfxCaptionTemplate :: Options -> String -> PureErr Template +pfxCaptionTemplate opts pfx = prefixCaptionTemplate <$> getPfx opts pfx -pfxListItemTemplate :: Options -> String -> Template -pfxListItemTemplate opts pfx = prefixListItemTemplate $ getPfx opts pfx +pfxListItemTemplate :: Options -> String -> PureErr Template +pfxListItemTemplate opts pfx = prefixListItemTemplate <$> getPfx opts pfx -pfxCaptionIndexTemplate :: Options -> String -> Template -pfxCaptionIndexTemplate opts pfx = prefixCaptionIndexTemplate $ getPfx opts pfx +pfxCaptionIndexTemplate :: Options -> String -> PureErr Template +pfxCaptionIndexTemplate opts pfx = prefixCaptionIndexTemplate <$> getPfx opts pfx -getPfx :: Options -> String -> Prefix -getPfx o pn = fromMaybe defaultPfx $ M.lookup pn $ prefixes o +getPfx :: Options -> String -> PureErr Prefix +getPfx o pn = maybe defaultPfx return $ M.lookup pn $ prefixes o where - defaultPfx = error $ "Undefined prefix: \"" <> pn <> "\"" + defaultPfx = Left $ WSENoSuchPrefix pn getRefPrefix :: Options -> String -> Maybe String getRefPrefix opts label @@ -82,5 +69,5 @@ getRefLabel opts ils = Just lbl getRefLabel _ _ = Nothing -getTitleForListOf :: Options -> String -> Blocks -getTitleForListOf opts = flip applyBlockTemplate (const Nothing) . prefixListOfTitle . getPfx opts +getTitleForListOf :: Options -> String -> PureErr Blocks +getTitleForListOf opts = fmap (flip applyBlockTemplate (const Nothing) . prefixListOfTitle) . getPfx opts diff --git a/lib/Text/Pandoc/CrossRef/Util/Options/Types.hs b/lib/Text/Pandoc/CrossRef/Util/Options/Types.hs new file mode 100644 index 00000000..02b4c088 --- /dev/null +++ b/lib/Text/Pandoc/CrossRef/Util/Options/Types.hs @@ -0,0 +1,42 @@ +{- +pandoc-crossref is a pandoc filter for numbering figures, +equations, tables and cross-references to them. +Copyright (C) 2015 Nikolay Yakimov + +This program is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License along +with this program; if not, write to the Free Software Foundation, Inc., +51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +-} + +module Text.Pandoc.CrossRef.Util.Options.Types where +import Text.Pandoc.Definition +import Text.Pandoc.CrossRef.Util.Prefixes +import Text.Pandoc.Builder +import Text.Pandoc.CrossRef.Util.LatexPrefixes + +data Options = Options { cref :: Bool + , listings :: Bool + , codeBlockCaptions :: Bool + , autoSectionLabels :: Bool + , rangeDelim :: Inlines + , pairDelim :: Inlines + , lastDelim :: Inlines + , refDelim :: Inlines + , outFormat :: Maybe Format + , tableEqns :: Bool + , autoEqnLabels :: Bool + , linkReferences :: Bool + , nameInLink :: Bool + , prefixes :: Prefixes + , latexPrefixes :: LatexPrefixes + } diff --git a/lib/Text/Pandoc/CrossRef/Util/Prefixes.hs b/lib/Text/Pandoc/CrossRef/Util/Prefixes.hs index ebf0e43d..7bf823cf 100644 --- a/lib/Text/Pandoc/CrossRef/Util/Prefixes.hs +++ b/lib/Text/Pandoc/CrossRef/Util/Prefixes.hs @@ -18,29 +18,20 @@ with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -} -{-# LANGUAGE FlexibleInstances, GeneralizedNewtypeDeriving, MultiParamTypeClasses #-} -module Text.Pandoc.CrossRef.Util.Prefixes where +module Text.Pandoc.CrossRef.Util.Prefixes ( + getPrefixes + , module Types +) where import Text.Pandoc.Definition -import Text.Pandoc.Walk (Walkable(..)) import Text.Pandoc.CrossRef.Util.Template +import Text.Pandoc.CrossRef.Util.Prefixes.Types as Types import Text.Pandoc.CrossRef.Util.Settings.Types import Text.Pandoc.CrossRef.Util.Meta import Text.Pandoc.CrossRef.Util.CustomLabels import qualified Data.Map as M -import Text.Pandoc.Builder hiding ((<>)) -import Data.Default import Data.Maybe -newtype Inlines' = Inlines' { fromInlines' :: Inlines } deriving (Eq, Semigroup, Monoid) -instance Default Inlines' where - def = mempty -instance Walkable Inline Inlines' where - walk f (Inlines' x) = Inlines' $ walk f x - walkM f (Inlines' x) = Inlines' <$> walkM f x - query f (Inlines' x) = query f x - - getPrefixes :: String -> Settings -> Prefixes getPrefixes varN dtv | Just (MetaMap m) <- lookupSettings varN dtv = M.mapWithKey m2p m @@ -70,19 +61,3 @@ getPrefixes varN dtv reportError n what = error $ what <> " meta variable " <> n <> " not set for " <> varN <> "." <> k <> ". This should not happen. Please report a bug" m2p k _ = error $ "Invalid value for prefix " <> k - -type Prefixes = M.Map String Prefix - -data Prefix = Prefix { - prefixCaptionTemplate :: !Template - , prefixReferenceTemplate :: !RefTemplate - , prefixScope :: ![String] - , prefixNumbering :: !(Int -> Int -> String) - , prefixListOfTitle :: !BlockTemplate - , prefixReferenceIndexTemplate :: !Template - , prefixCaptionIndexTemplate :: !Template - , prefixListItemTemplate :: !Template - -- Used for LaTeX metadata; the same value is used in - -- default value for prefixCaptionTemplate - , prefixTitle :: Inlines -} diff --git a/lib/Text/Pandoc/CrossRef/Util/Prefixes/Types.hs b/lib/Text/Pandoc/CrossRef/Util/Prefixes/Types.hs new file mode 100644 index 00000000..e5fcfdb5 --- /dev/null +++ b/lib/Text/Pandoc/CrossRef/Util/Prefixes/Types.hs @@ -0,0 +1,41 @@ +{- +pandoc-crossref is a pandoc filter for numbering figures, +equations, tables and cross-references to them. +Copyright (C) 2019 Nikolay Yakimov + +This program is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License along +with this program; if not, write to the Free Software Foundation, Inc., +51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +-} + +module Text.Pandoc.CrossRef.Util.Prefixes.Types where + +import qualified Data.Map as M +import Text.Pandoc.CrossRef.Util.Template.Types +import Text.Pandoc.Builder + +type Prefixes = M.Map String Prefix + +data Prefix = Prefix { + prefixCaptionTemplate :: !Template + , prefixReferenceTemplate :: !RefTemplate + , prefixScope :: ![String] + , prefixNumbering :: !(Int -> Int -> String) + , prefixListOfTitle :: !BlockTemplate + , prefixReferenceIndexTemplate :: !Template + , prefixCaptionIndexTemplate :: !Template + , prefixListItemTemplate :: !Template + -- Used for LaTeX metadata; the same value is used in + -- default value for prefixCaptionTemplate + , prefixTitle :: Inlines +} diff --git a/lib/Text/Pandoc/CrossRef/Util/Replace.hs b/lib/Text/Pandoc/CrossRef/Util/Replace.hs new file mode 100644 index 00000000..4873cae1 --- /dev/null +++ b/lib/Text/Pandoc/CrossRef/Util/Replace.hs @@ -0,0 +1,70 @@ +{- +pandoc-crossref is a pandoc filter for numbering figures, +equations, tables and cross-references to them. +Copyright (C) 2015 Nikolay Yakimov + +This program is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License along +with this program; if not, write to the Free Software Foundation, Inc., +51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +-} + +{-# LANGUAGE FlexibleContexts, Rank2Types #-} +module Text.Pandoc.CrossRef.Util.Replace ( + module Text.Pandoc.CrossRef.Util.Replace + , module Data.Generics +) where + +import Text.Pandoc.CrossRef.References.Types +import Data.Generics hiding (Prefix) + +data ReplacedResult a = ReplacedRecurse Scope a + | NotReplacedRecurse Scope + | ReplacedNoRecurse a + | NotReplacedNoRecurse +type GenRR m = forall a. Data a => (Scope -> a -> m (ReplacedResult a)) +newtype RR m a = RR {unRR :: Scope -> a -> m (ReplacedResult a)} + +runReplace :: (MonadError WSException m, Monad m) => Scope -> GenRR m -> GenericM m +runReplace s f x = do + res <- f s x `catchError` handler + case res of + ReplacedRecurse s' x' -> gmapM (runReplace s' f) x' + ReplacedNoRecurse x' -> return x' + NotReplacedRecurse s' -> gmapM (runReplace s' f) x + NotReplacedNoRecurse -> return x + where + handler (WSENoSuchPrefix _) = return $ NotReplacedRecurse s + handler e = throwError e + +mkRR :: (Monad m, Typeable a, Typeable b) + => (Scope -> b -> m (ReplacedResult b)) + -> (Scope -> a -> m (ReplacedResult a)) +mkRR = extRR (\s _ -> noReplaceRecurse s) + +extRR :: ( Monad m, Typeable a, Typeable b) + => (Scope -> a -> m (ReplacedResult a)) + -> (Scope -> b -> m (ReplacedResult b)) + -> (Scope -> a -> m (ReplacedResult a)) +extRR def' ext = unRR (RR def' `ext0` RR ext) + +replaceRecurse :: Monad m => Scope -> a -> m (ReplacedResult a) +replaceRecurse s = return . ReplacedRecurse s + +replaceNoRecurse :: Monad m => a -> m (ReplacedResult a) +replaceNoRecurse = return . ReplacedNoRecurse + +noReplaceRecurse :: Monad m => Scope -> m (ReplacedResult a) +noReplaceRecurse = return . NotReplacedRecurse + +noReplaceNoRecurse :: Monad m => m (ReplacedResult a) +noReplaceNoRecurse = return NotReplacedNoRecurse diff --git a/lib/Text/Pandoc/CrossRef/Util/Settings.hs b/lib/Text/Pandoc/CrossRef/Util/Settings.hs index f1e1e2bf..8b22da79 100644 --- a/lib/Text/Pandoc/CrossRef/Util/Settings.hs +++ b/lib/Text/Pandoc/CrossRef/Util/Settings.hs @@ -19,7 +19,7 @@ with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -} -module Text.Pandoc.CrossRef.Util.Settings (getSettings, defaultMeta, Settings(..)) where +module Text.Pandoc.CrossRef.Util.Settings (readSettings, defaultMeta, Settings(..)) where import Text.Pandoc import Text.Pandoc.Builder hiding ((<>)) @@ -34,14 +34,14 @@ import System.IO import qualified Data.Text as T import qualified Data.Map as M -getSettings :: Maybe Format -> Meta -> IO Settings -getSettings fmt inMeta = do +readSettings :: Maybe Format -> Meta -> IO Settings +readSettings fmt inMeta = do let meta = Settings inMeta dirConfig <- readConfig (getMetaString "crossrefYaml" (meta <> defaultMeta)) home <- getHomeDirectory globalConfig <- readConfig (home ".pandoc-crossref" "config.yaml") formatConfig <- maybe (return mempty) (readFmtConfig home) fmt - return $ meta <> dirConfig <> formatConfig <> globalConfig <> defaultMeta + return $ meta <> dirConfig <> formatConfig <> globalConfig where readConfig path = handle handler $ do diff --git a/lib/Text/Pandoc/CrossRef/Util/Template.hs b/lib/Text/Pandoc/CrossRef/Util/Template.hs index 91a96dbe..3b5b6317 100644 --- a/lib/Text/Pandoc/CrossRef/Util/Template.hs +++ b/lib/Text/Pandoc/CrossRef/Util/Template.hs @@ -37,17 +37,13 @@ import Text.Pandoc.Builder import Text.Pandoc.Generic import Text.Pandoc.CrossRef.Util.Meta import Text.Pandoc.CrossRef.Util.Settings.Types +import Text.Pandoc.CrossRef.Util.Template.Types import Control.Applicative import Text.Read import Data.Char (isAlphaNum, isUpper, toLower) import Control.Monad ((<=<)) import Data.Data (Data) -type VarFunc = String -> Maybe MetaValue -newtype Template = Template { applyTemplate :: VarFunc -> Inlines } -newtype RefTemplate = RefTemplate { applyRefTemplate :: VarFunc -> Bool -> Inlines } -newtype BlockTemplate = BlockTemplate { applyBlockTemplate :: VarFunc -> Blocks } - data State = StFirstVar | StIndex | StAfterIndex | StPrefix | StSuffix deriving Eq data ParseRes = ParseRes { prVar :: String, prIdx :: [String], prPfx :: String, prSfx :: String } deriving Show diff --git a/lib/Text/Pandoc/CrossRef/Util/Template/Types.hs b/lib/Text/Pandoc/CrossRef/Util/Template/Types.hs new file mode 100644 index 00000000..87830182 --- /dev/null +++ b/lib/Text/Pandoc/CrossRef/Util/Template/Types.hs @@ -0,0 +1,29 @@ +{- +pandoc-crossref is a pandoc filter for numbering figures, +equations, tables and cross-references to them. +Copyright (C) 2019 Nikolay Yakimov + +This program is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License along +with this program; if not, write to the Free Software Foundation, Inc., +51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +-} + +module Text.Pandoc.CrossRef.Util.Template.Types where + +import Text.Pandoc.Definition +import Text.Pandoc.Builder + +type VarFunc = String -> Maybe MetaValue +newtype Template = Template { applyTemplate :: VarFunc -> Inlines } +newtype RefTemplate = RefTemplate { applyRefTemplate :: VarFunc -> Bool -> Inlines } +newtype BlockTemplate = BlockTemplate { applyBlockTemplate :: VarFunc -> Blocks } diff --git a/lib/Text/Pandoc/CrossRef/Util/Util.hs b/lib/Text/Pandoc/CrossRef/Util/Util.hs index 4e792c39..052bdbc4 100644 --- a/lib/Text/Pandoc/CrossRef/Util/Util.hs +++ b/lib/Text/Pandoc/CrossRef/Util/Util.hs @@ -18,23 +18,22 @@ with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -} -{-# LANGUAGE RankNTypes #-} -module Text.Pandoc.CrossRef.Util.Util - ( module Text.Pandoc.CrossRef.Util.Util - , module Data.Generics - ) where +{-# LANGUAGE FlexibleContexts, Rank2Types #-} +module Text.Pandoc.CrossRef.Util.Util where -import Text.Pandoc.CrossRef.References.Types +import Text.Pandoc.CrossRef.References.Types.Ref import Text.Pandoc.Definition import Text.Pandoc.Class import Text.Pandoc.Shared (Element(..)) import Data.Char (toUpper, toLower, isUpper) -import Data.Generics hiding (Prefix) import Text.Pandoc.Writers.LaTeX import Data.Default import Data.Monoid ((<>)) import qualified Data.Text as T +import qualified Data.Accessor.Basic as Accessor +import qualified Control.Monad.State as State + intercalate' :: (Eq a, Monoid a, Foldable f) => a -> f a -> a intercalate' s = foldr (\x acc -> if acc == mempty then x else x <> s <> acc) mempty @@ -58,45 +57,6 @@ isFirstUpper :: String -> Bool isFirstUpper (x:_) = isUpper x isFirstUpper [] = False -data ReplacedResult a = ReplacedRecurse Scope a - | NotReplacedRecurse Scope - | ReplacedNoRecurse a - | NotReplacedNoRecurse -type GenRR m = forall a. Data a => (Scope -> a -> m (ReplacedResult a)) -newtype RR m a = RR {unRR :: Scope -> a -> m (ReplacedResult a)} - -runReplace :: (Monad m) => Scope -> GenRR m -> GenericM m -runReplace s f x = do - res <- f s x - case res of - ReplacedRecurse s' x' -> gmapM (runReplace s' f) x' - ReplacedNoRecurse x' -> return x' - NotReplacedRecurse s' -> gmapM (runReplace s' f) x - NotReplacedNoRecurse -> return x - -mkRR :: (Monad m, Typeable a, Typeable b) - => (Scope -> b -> m (ReplacedResult b)) - -> (Scope -> a -> m (ReplacedResult a)) -mkRR = extRR (\s _ -> noReplaceRecurse s) - -extRR :: ( Monad m, Typeable a, Typeable b) - => (Scope -> a -> m (ReplacedResult a)) - -> (Scope -> b -> m (ReplacedResult b)) - -> (Scope -> a -> m (ReplacedResult a)) -extRR def' ext = unRR (RR def' `ext0` RR ext) - -replaceRecurse :: Monad m => Scope -> a -> m (ReplacedResult a) -replaceRecurse s = return . ReplacedRecurse s - -replaceNoRecurse :: Monad m => a -> m (ReplacedResult a) -replaceNoRecurse = return . ReplacedNoRecurse - -noReplaceRecurse :: Monad m => Scope -> m (ReplacedResult a) -noReplaceRecurse = return . NotReplacedRecurse - -noReplaceNoRecurse :: Monad m => m (ReplacedResult a) -noReplaceNoRecurse = return NotReplacedNoRecurse - mkLaTeXLabel :: String -> String mkLaTeXLabel l | null l = [] @@ -127,3 +87,14 @@ unhierarchicalize [] = [] newScope :: RefRec -> Scope -> Scope newScope = (:) + +-- * accessors in the form of actions in the state monad + +set :: (State.MonadState r s) => Accessor.T r a -> a -> s () +set f x = State.modify (Accessor.set f x) + +get :: (State.MonadState r s) => Accessor.T r a -> s a +get f = State.gets (Accessor.get f) + +modify :: (State.MonadState r s) => Accessor.T r a -> (a -> a) -> s () +modify f g = State.modify (Accessor.modify f g) diff --git a/package.yaml b/package.yaml index 30680b54..716181ca 100644 --- a/package.yaml +++ b/package.yaml @@ -25,7 +25,6 @@ dependencies: - data-default >=0.4 && <0.8 - data-accessor >=0.2.2.6 && <0.3.0.0 - data-accessor-template >=0.2.1.12 && <0.3.0.0 -- data-accessor-transformers >=0.2.1.6 && <0.3.0.0 - template-haskell >=2.7.0.0 && <3.0.0.0 - roman-numerals ==0.5.* - syb >=0.4 && <0.8 diff --git a/pandoc-crossref.cabal b/pandoc-crossref.cabal index 1c599bc8..3d739582 100644 --- a/pandoc-crossref.cabal +++ b/pandoc-crossref.cabal @@ -4,7 +4,7 @@ cabal-version: 1.12 -- -- see: https://github.com/sol/hpack -- --- hash: d30ab549b7a62592a79d5bc6680d6f0311e963e00a2a1c124193ea104c66bb9a +-- hash: a74d9949e6fbdca0da757f8c93d777e91730714d6f061cb9fb525e6b49fc14f6 name: pandoc-crossref version: 0.4.0.0 @@ -79,6 +79,9 @@ data-files: test/m2m/subfigures/expect.md test/m2m/subfigures/expect.tex test/m2m/subfigures/input.md + test/m2m/undefined-prefix/expect.md + test/m2m/undefined-prefix/expect.tex + test/m2m/undefined-prefix/input.md source-repository head type: git @@ -99,18 +102,24 @@ library Text.Pandoc.CrossRef.References.Refs Text.Pandoc.CrossRef.References.Subfigures Text.Pandoc.CrossRef.References.Types + Text.Pandoc.CrossRef.References.Types.Monad + Text.Pandoc.CrossRef.References.Types.Ref Text.Pandoc.CrossRef.Util.CodeBlockCaptions Text.Pandoc.CrossRef.Util.CustomLabels Text.Pandoc.CrossRef.Util.LatexPrefixes Text.Pandoc.CrossRef.Util.Meta Text.Pandoc.CrossRef.Util.ModifyMeta Text.Pandoc.CrossRef.Util.Options + Text.Pandoc.CrossRef.Util.Options.Types Text.Pandoc.CrossRef.Util.Prefixes + Text.Pandoc.CrossRef.Util.Prefixes.Types + Text.Pandoc.CrossRef.Util.Replace Text.Pandoc.CrossRef.Util.Settings Text.Pandoc.CrossRef.Util.Settings.Gen Text.Pandoc.CrossRef.Util.Settings.Template Text.Pandoc.CrossRef.Util.Settings.Types Text.Pandoc.CrossRef.Util.Template + Text.Pandoc.CrossRef.Util.Template.Types Text.Pandoc.CrossRef.Util.Util Text.Pandoc.CrossRef.Util.VarFunction Paths_pandoc_crossref @@ -122,7 +131,6 @@ library , containers >=0.1 && <0.7 , data-accessor >=0.2.2.6 && <0.3.0.0 , data-accessor-template >=0.2.1.12 && <0.3.0.0 - , data-accessor-transformers >=0.2.1.6 && <0.3.0.0 , data-default >=0.4 && <0.8 , directory >=1 && <1.4 , extra >=1.6 && <1.7 @@ -150,7 +158,6 @@ executable pandoc-crossref , containers >=0.1 && <0.7 , data-accessor >=0.2.2.6 && <0.3.0.0 , data-accessor-template >=0.2.1.12 && <0.3.0.0 - , data-accessor-transformers >=0.2.1.6 && <0.3.0.0 , data-default >=0.4 && <0.8 , deepseq >=1.4 && <1.5 , directory >=1 && <1.4 @@ -182,7 +189,6 @@ test-suite test-integrative , containers >=0.1 && <0.7 , data-accessor >=0.2.2.6 && <0.3.0.0 , data-accessor-template >=0.2.1.12 && <0.3.0.0 - , data-accessor-transformers >=0.2.1.6 && <0.3.0.0 , data-default >=0.4 && <0.8 , directory >=1 && <1.4 , extra >=1.6 && <1.7 @@ -213,18 +219,24 @@ test-suite test-pandoc-crossref Text.Pandoc.CrossRef.References.Refs Text.Pandoc.CrossRef.References.Subfigures Text.Pandoc.CrossRef.References.Types + Text.Pandoc.CrossRef.References.Types.Monad + Text.Pandoc.CrossRef.References.Types.Ref Text.Pandoc.CrossRef.Util.CodeBlockCaptions Text.Pandoc.CrossRef.Util.CustomLabels Text.Pandoc.CrossRef.Util.LatexPrefixes Text.Pandoc.CrossRef.Util.Meta Text.Pandoc.CrossRef.Util.ModifyMeta Text.Pandoc.CrossRef.Util.Options + Text.Pandoc.CrossRef.Util.Options.Types Text.Pandoc.CrossRef.Util.Prefixes + Text.Pandoc.CrossRef.Util.Prefixes.Types + Text.Pandoc.CrossRef.Util.Replace Text.Pandoc.CrossRef.Util.Settings Text.Pandoc.CrossRef.Util.Settings.Gen Text.Pandoc.CrossRef.Util.Settings.Template Text.Pandoc.CrossRef.Util.Settings.Types Text.Pandoc.CrossRef.Util.Template + Text.Pandoc.CrossRef.Util.Template.Types Text.Pandoc.CrossRef.Util.Util Text.Pandoc.CrossRef.Util.VarFunction Paths_pandoc_crossref @@ -237,7 +249,6 @@ test-suite test-pandoc-crossref , containers >=0.1 && <0.7 , data-accessor >=0.2.2.6 && <0.3.0.0 , data-accessor-template >=0.2.1.12 && <0.3.0.0 - , data-accessor-transformers >=0.2.1.6 && <0.3.0.0 , data-default >=0.4 && <0.8 , directory >=1 && <1.4 , extra >=1.6 && <1.7 diff --git a/test/m2m/undefined-prefix/expect.md b/test/m2m/undefined-prefix/expect.md new file mode 100644 index 00000000..e2b890f3 --- /dev/null +++ b/test/m2m/undefined-prefix/expect.md @@ -0,0 +1,2 @@ +Crossref shouldn't error out when it sees something that looks like a +reference, but with unknown prefix, like [@nonexistent:ref] diff --git a/test/m2m/undefined-prefix/expect.tex b/test/m2m/undefined-prefix/expect.tex new file mode 100644 index 00000000..0bb59b38 --- /dev/null +++ b/test/m2m/undefined-prefix/expect.tex @@ -0,0 +1,2 @@ +Crossref shouldn't error out when it sees something that looks like a +reference, but with unknown prefix, like {[}@nonexistent:ref{]} diff --git a/test/m2m/undefined-prefix/input.md b/test/m2m/undefined-prefix/input.md new file mode 100644 index 00000000..3e837f65 --- /dev/null +++ b/test/m2m/undefined-prefix/input.md @@ -0,0 +1,2 @@ +Crossref shouldn't error out when it sees something that looks like +a reference, but with unknown prefix, like [@nonexistent:ref] From b9481f78a8630335b48acdc13f75a75a20c23b87 Mon Sep 17 00:00:00 2001 From: Nikolay Yakimov Date: Sun, 3 Mar 2019 07:52:26 +0300 Subject: [PATCH 056/134] Fix test --- lib/Text/Pandoc/CrossRef.hs | 14 ++-- .../Pandoc/CrossRef/References/Types/Monad.hs | 1 + lib/Text/Pandoc/CrossRef/Util/Settings.hs | 3 +- src/pandoc-crossref.hs | 2 +- test/m2m/capitalization/expect.md | 4 +- test/test-integrative.hs | 7 +- test/test-pandoc-crossref.hs | 80 +++++++++++++++---- 7 files changed, 84 insertions(+), 27 deletions(-) diff --git a/lib/Text/Pandoc/CrossRef.hs b/lib/Text/Pandoc/CrossRef.hs index 06379c83..1706ca44 100644 --- a/lib/Text/Pandoc/CrossRef.hs +++ b/lib/Text/Pandoc/CrossRef.hs @@ -76,8 +76,9 @@ module Text.Pandoc.CrossRef ( , runCrossRefIO , module SG , defaultMeta - , CrossRefM + , CrossRef , CrossRefEnv(..) + , WSException(..) ) where import Control.Monad.State @@ -126,9 +127,8 @@ defaultCrossRefAction (Pandoc _ bs) = do {- | Run an action in 'CrossRefM' monad with argument, and return pure result. This is primary function to work with 'CrossRefM' -} -runCrossRef :: forall a b. Meta -> Maybe Format -> (a -> CrossRef b) -> a -> (Either WSException b, [String]) -runCrossRef meta fmt action arg = - flip runReader env . runWriterT . runExceptT . unCrossRef $ action arg +runCrossRef :: forall b. Meta -> Maybe Format -> CrossRef b -> (Either WSException b, [String]) +runCrossRef meta fmt = flip runReader env . runWriterT . runExceptT . unCrossRef where settings = Settings meta <> defaultMeta env = CrossRefEnv { @@ -140,9 +140,9 @@ runCrossRef meta fmt action arg = This function will attempt to read pandoc-crossref settings from settings file specified by crossrefYaml metadata field. -} -runCrossRefIO :: forall a b. Meta -> Maybe Format -> (a -> CrossRef b) -> a -> IO b -runCrossRefIO meta fmt action arg = do +runCrossRefIO :: forall b. Meta -> Maybe Format -> CrossRef b -> IO b +runCrossRefIO meta fmt action = do Settings meta' <- readSettings fmt meta - let (res, lg) = runCrossRef meta' fmt action arg + let (res, lg) = runCrossRef meta' fmt action mapM_ putStrLn lg return $ either (error . pretty) id res diff --git a/lib/Text/Pandoc/CrossRef/References/Types/Monad.hs b/lib/Text/Pandoc/CrossRef/References/Types/Monad.hs index fc1fd4ca..7d2d5800 100644 --- a/lib/Text/Pandoc/CrossRef/References/Types/Monad.hs +++ b/lib/Text/Pandoc/CrossRef/References/Types/Monad.hs @@ -36,6 +36,7 @@ import qualified Control.Monad.Fail as Fail data WSException = WSENoSuchPrefix String | WSEDuplicateLabel String | WSEFail String + deriving Show type PureErr a = Either WSException a diff --git a/lib/Text/Pandoc/CrossRef/Util/Settings.hs b/lib/Text/Pandoc/CrossRef/Util/Settings.hs index 8b22da79..80cf64fd 100644 --- a/lib/Text/Pandoc/CrossRef/Util/Settings.hs +++ b/lib/Text/Pandoc/CrossRef/Util/Settings.hs @@ -110,7 +110,8 @@ defaultMeta = Settings $ ], "sec" .: [ "ref" .= map str ["sec.", "secs."], - "title" .= text "Section" + "title" .= text "Section", + "captionTemplate" .= var "t" ] ] where var = displayMath diff --git a/src/pandoc-crossref.hs b/src/pandoc-crossref.hs index af795409..6682002e 100644 --- a/src/pandoc-crossref.hs +++ b/src/pandoc-crossref.hs @@ -71,7 +71,7 @@ run = do return () go Nothing _ = toJSONFilter f f fmt p@(Pandoc meta _) = - runCrossRefIO meta fmt defaultCrossRefAction p + runCrossRefIO meta fmt $ defaultCrossRefAction p main :: IO () main = join $ execParser opts diff --git a/test/m2m/capitalization/expect.md b/test/m2m/capitalization/expect.md index 3f385014..601423f7 100644 --- a/test/m2m/capitalization/expect.md +++ b/test/m2m/capitalization/expect.md @@ -14,6 +14,6 @@ eq. 1, Eq. 1, fig. 1, Fig. 1, tbl. 1, Tbl. 1 eq. 1, Eq. 1, fig. 1, Fig. 1, tbl. 1, Tbl. 1 -eqs. 1, 1, figs. 1, 1, tbls. 1, 1 +eqs. 1, figs. 1, tbls. 1 -Eqs. 1, 1, Figs. 1, 1, Tbls. 1, 1 +Eqs. 1, Figs. 1, Tbls. 1 diff --git a/test/test-integrative.hs b/test/test-integrative.hs index e2d3fc09..150b5caf 100644 --- a/test/test-integrative.hs +++ b/test/test-integrative.hs @@ -40,13 +40,13 @@ m2m dir let ro = def { readerExtensions = pandocExtensions } wo = def { writerExtensions = pandocExtensions, writerHighlightStyle=Just pygments } p@(Pandoc meta _) <- runIO $ either (error . show) id <$> P.runIO (readMarkdown ro $ T.pack input) - let actual_md = either (fail . show) T.unpack $ runPure $ writeMarkdown wo $ runCrossRef meta (Just $ Format "markdown") defaultCrossRefAction p + let actual_md = either (fail . show) T.unpack $ runPure $ writeMarkdown wo . evalCrossRefRes . runCrossRef meta (Just $ Format "markdown") $ defaultCrossRefAction p it "Markdown" $ do zipWithM_ shouldBe (lines' actual_md) (lines' expect_md) length' (lines' actual_md) `shouldBe` length' (lines' expect_md) #ifdef FLAKY expect_tex <- runIO $ readFile ("test" "m2m" dir "expect.tex") - let actual_tex = either (fail . show) T.unpack $ runPure $ writeLaTeX wo $ runCrossRef meta (Just $ Format "latex") defaultCrossRefAction p + let actual_tex = either (fail . show) T.unpack $ runPure $ writeLaTeX wo . evalCrossRefRes . runCrossRef meta (Just $ Format "latex") $ defaultCrossRefAction p it "LaTeX" $ do zipWithM_ shouldBe (lines' actual_tex) (lines' expect_tex) length' (lines' actual_tex) `shouldBe` length' (lines' expect_tex) @@ -73,3 +73,6 @@ flaky = [ "equations-tables" , "subfigures-grid" ] #endif + +evalCrossRefRes :: Show a => (Either a c, b) -> c +evalCrossRefRes = either (error . show) id . fst diff --git a/test/test-pandoc-crossref.hs b/test/test-pandoc-crossref.hs index ac0f8100..737a5764 100644 --- a/test/test-pandoc-crossref.hs +++ b/test/test-pandoc-crossref.hs @@ -18,19 +18,22 @@ with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -} -{-# LANGUAGE FlexibleContexts, CPP, OverloadedStrings, TypeSynonymInstances, FlexibleInstances #-} +{-# OPTIONS_GHC -fno-warn-orphans #-} +{-# LANGUAGE FlexibleContexts, CPP, OverloadedStrings, TypeSynonymInstances + , FlexibleInstances, StandaloneDeriving #-} import Test.Hspec import Text.Pandoc hiding (getDataFileName) import Text.Pandoc.Builder import Control.Monad.State import Data.List +import Data.Maybe import Control.Arrow import qualified Data.Map as M import qualified Data.Text as T -import qualified Data.Default as Df import Text.Pandoc.CrossRef import Text.Pandoc.CrossRef.Util.Options +import Text.Pandoc.CrossRef.Util.Prefixes import Text.Pandoc.CrossRef.Util.Util import Text.Pandoc.CrossRef.References.Types import Text.Pandoc.CrossRef.Util.Settings.Types @@ -224,7 +227,8 @@ main = hspec $ do it "Labels sections divs" $ testAll (section "Section Header" 1 "section") (section "Section Header" 1 "section", - referenceData ^= M.fromList (refRec' "sec:section" 1 "Section Header" "") + (referenceData ^= M.fromList (refRec' "sec:section" 1 "Section Header" "")) + . (pfxCounter =: M.singleton "sec" $ CounterRec {crIndex = 1, crIndexInScope = M.singleton Nothing 1}) ) describe "References.Refs.replaceRefs" $ do @@ -277,11 +281,11 @@ main = hspec $ do it "Generates list of tables" $ testList (rawBlock "latex" "\\listoftables") (referenceData =: M.fromList $ refRec' "tbl:1" 4 "4" "Table 4: 4" <> refRec' "tbl:2" 5 "5" "Table 5: 5" <> refRec' "tbl:3" 6 "6" "Table 6: 6") - (header 1 (text "List of Tables") <> orderedList ((plain . str . show) `map` [4..6 :: Int])) + (header 1 (text "List of Tables") <> divWith ("",["list"],[]) (foldl1' (<>) $ map (\i -> let n = show i in para $ text (n <> ". " <> n) ) [4..6 :: Int])) it "Generates list of figures" $ testList (rawBlock "latex" "\\listoffigures") (referenceData =: M.fromList $ refRec' "fig:1" 4 "4" "Figure 4: 4" <> refRec' "fig:2" 5 "5" "Figure 5: 5" <> refRec' "fig:3" 6 "6" "Figure 6: 6") - (header 1 (text "List of Figures") <> orderedList ((plain . str . show) `map` [4..6 :: Int])) + (header 1 (text "List of Figures") <> divWith ("",["list"],[]) (foldl1' (<>) $ map (\i -> let n = show i in para $ text (n <> ". " <> n) ) [4..6 :: Int])) describe "Util.CodeBlockCaptions" $ it "Transforms table-style codeBlock captions to codeblock divs" $ do @@ -323,20 +327,22 @@ main = hspec $ do it "demo.md matches demo.native" $ do demomd <- readFile =<< getDataFileName "docs/demo/demo.md" Pandoc m b <- handleError $ runPure $ readMarkdown def {readerExtensions = pandocExtensions} $ T.pack demomd - runCrossRef m Nothing crossRefBlocks b `shouldBe` Native.demo + let (res, _warn) = runCrossRef m Nothing $ crossRefBlocks b + res `shouldBe` Right Native.demo it "demo.md with chapters matches demo-chapters.native" $ do demomd <- readFile =<< getDataFileName "docs/demo/demo.md" Pandoc m b <- handleError $ runPure $ readMarkdown def {readerExtensions = pandocExtensions} $ T.pack demomd let m' = setMeta "chapters" True m - runCrossRef m' Nothing crossRefBlocks b `shouldBe` Native.demochapters + let (res, _warn) = runCrossRef m' Nothing $ crossRefBlocks b + res `shouldBe` Right Native.demochapters #endif describe "LaTeX" $ do let test = test' nullMeta infixr 5 `test` test' m i o = getLatex m i `shouldBe` o - getLatex m i = either (fail . show) T.unpack (runPure $ writeLaTeX def (Pandoc m $ runCrossRef m (Just $ Format "latex") crossRefBlocks (toList i))) + getLatex m i = either (fail . show) T.unpack (runPure $ writeLaTeX def (Pandoc m . evalCrossRefRes . runCrossRef m (Just $ Format "latex") $ crossRefBlocks (toList i))) describe "Labels" $ do @@ -386,10 +392,38 @@ refGen' :: String -> [Int] -> [(Int, Int)] -> M.Map String RefRec refGen' p l1 l2 = M.fromList $ mconcat $ zipWith refRec''' (((uncapitalizeFirst p++) . show) `map` l1) l2 refRec' :: String -> Int -> Inlines -> String -> [(String, RefRec)] -refRec' ref i tit cap = [(ref, RefRec{refIndex=i, refIxInl = str $ show i, refCaption= text cap,refTitle=tit,refScope=Nothing, refLevel=0, refPfx=takeWhile (/=':') ref, refLabel=ref, refAttrs = M.empty})] +refRec' ref i tit cap = + let pfx = takeWhile (/=':') ref + in [(ref + , RefRec + { refIndex=i + , refIxInl = str $ show i + , refCaption= text cap,refTitle=tit,refScope=Nothing + , refLevel=0 + , refPfx=pfx + , refLabel=ref + , refAttrs = M.empty + , refPfxRec = fromJust $ M.lookup pfx defaultPrefixes + } + )] refRec''' :: String -> (Int, Int) -> [(String, RefRec)] -refRec''' ref (c,i) = [(ref, RefRec{refIndex=c+i,refIxInl = str $ show i, refCaption=str $ show i,refTitle=text [],refScope=Nothing, refLevel=0, refPfx=takeWhile (/=':') ref, refLabel=ref, refAttrs = M.empty})] +refRec''' ref (c,i) = + let pfx = takeWhile (/=':') ref + in [(ref + , RefRec + { refIndex=c+i + , refIxInl = str $ show i + , refCaption=str $ show i + , refTitle=text [] + , refScope=Nothing + , refLevel=0 + , refPfx=pfx + , refLabel=ref + , refAttrs = M.empty + , refPfxRec = fromJust $ M.lookup pfx defaultPrefixes + } + )] testRefs' :: String -> [Int] -> [Int] -> Accessor References (M.Map String RefRec) -> String -> Expectation testRefs' p l1 l2 prop res = testRefs (para $ citeGen p l1) (setVal prop (refGen p l1 l2) def) (para $ text res) @@ -401,9 +435,24 @@ testAll :: Many Block -> (Many Block, References -> References) -> Expectation testAll = testState f def where f = References.Blocks.replaceAll defaultOptions -testState :: (Eq s, Eq a1, Show s, Show a1, Df.Default s) => - ([a] -> State s [a1]) -> s -> Many a -> (Many a1, s -> s) -> Expectation -testState f init' arg (r, s) = runState (f $ toList arg) init' `shouldBe` (toList r, s init') +evalCrossRefM :: CrossRefM c -> c +evalCrossRefM = evalCrossRefRes . runCrossRef (unSettings defaultMeta) Nothing . CrossRef + +evalCrossRefRes :: (Either WSException c, b) -> c +evalCrossRefRes = either (error . show) id . fst + +instance Show Prefix where + show _ = "Prefix{}" +deriving instance Show RefRec +deriving instance Show CounterRec +deriving instance Eq CounterRec +deriving instance Show References +deriving instance Eq References +deriving instance Eq WSException + +testState :: (Eq a1, Show a1) => ([a] -> WS [a1]) -> References -> Many a -> (Many a1, References -> References) -> Expectation +testState f init' arg (r, s) = evalCrossRefM $ + (`shouldBe` (toList r, s init')) <$> runStateT (unWS . f $ toList arg) init' testRefs :: Blocks -> References -> Blocks -> Expectation testRefs bs st rbs = testState (bottomUpM (References.Refs.replaceRefs defaultOptions)) st bs (rbs, id) @@ -412,7 +461,7 @@ testCBCaptions :: Blocks -> Blocks -> Expectation testCBCaptions bs res = bottomUp (Util.CodeBlockCaptions.mkCodeBlockCaptions defaultOptions{Text.Pandoc.CrossRef.Util.Options.codeBlockCaptions=True}) (toList bs) `shouldBe` toList res testList :: Blocks -> (References -> References) -> Blocks -> Expectation -testList bs st res = runState (bottomUpM (References.List.listOf defaultOptions) (toList bs)) (st def) `shouldBe` (toList res, st def) +testList bs st res = testState (bottomUpM (References.List.listOf defaultOptions)) (st def) bs (res, st) figure :: String -> String -> String -> String -> Blocks figure = (((para .) .) .) . figure' "fig:" @@ -473,3 +522,6 @@ cit r = [defCit{citationId=r}] infixr 0 =: (=:) :: Accessor r a -> a -> r -> r a =: b = a ^= b + +defaultPrefixes :: Prefixes +defaultPrefixes = getPrefixes "prefixes" defaultMeta From 6dd2c952d3fd2c9237cd8d511ccf81901d10d1c2 Mon Sep 17 00:00:00 2001 From: Nikolay Yakimov Date: Sun, 3 Mar 2019 10:10:07 +0300 Subject: [PATCH 057/134] Fix more tests and some related minor bugs --- lib/Text/Pandoc/CrossRef.hs | 3 +- lib/Text/Pandoc/CrossRef/References/Blocks.hs | 7 +- lib/Text/Pandoc/CrossRef/References/Refs.hs | 5 +- test/m2m/scoping/expect.tex | 21 ++--- test/m2m/section-template/expect.tex | 20 +++-- test/test-pandoc-crossref.hs | 79 ++++++++----------- 6 files changed, 56 insertions(+), 79 deletions(-) diff --git a/lib/Text/Pandoc/CrossRef.hs b/lib/Text/Pandoc/CrossRef.hs index 1706ca44..0a86c698 100644 --- a/lib/Text/Pandoc/CrossRef.hs +++ b/lib/Text/Pandoc/CrossRef.hs @@ -87,6 +87,7 @@ import Control.Monad.Writer as W import Control.Monad.Reader as R import Text.Pandoc as P import Data.Monoid ((<>)) +import System.IO import Text.Pandoc.CrossRef.References import Text.Pandoc.CrossRef.Util.Settings @@ -144,5 +145,5 @@ runCrossRefIO :: forall b. Meta -> Maybe Format -> CrossRef b -> IO b runCrossRefIO meta fmt action = do Settings meta' <- readSettings fmt meta let (res, lg) = runCrossRef meta' fmt action - mapM_ putStrLn lg + mapM_ (hPutStrLn stderr) lg return $ either (error . pretty) id res diff --git a/lib/Text/Pandoc/CrossRef/References/Blocks.hs b/lib/Text/Pandoc/CrossRef/References/Blocks.hs index 120de11b..83c77dee 100644 --- a/lib/Text/Pandoc/CrossRef/References/Blocks.hs +++ b/lib/Text/Pandoc/CrossRef/References/Blocks.hs @@ -72,12 +72,9 @@ replaceElement opts scope (Sec n ns (label, cls, attrs) text' body) = do ititle = B.fromList text' defaultSecPfx = "sec" rec' <- case pfx' of - Just p -> replaceAttr opts scope (Right label) attrs ititle p + Just p -> replaceAttr opts scope (Right label') attrs ititle p Nothing -> replaceAttr opts scope (Left defaultSecPfx) attrs ititle defaultSecPfx - let title' = B.toList $ - case outFormat opts of - f | isLatexFormat f -> B.rawInline "latex" (mkLaTeXLabel label) <> ititle - _ -> applyTitleTemplate rec' + let title' = B.toList $ applyTitleTemplate rec' replaceRecurse (newScope rec' scope) $ Sec n ns (label', cls, attrs) title' body replaceElement _ scope _ = noReplaceRecurse scope diff --git a/lib/Text/Pandoc/CrossRef/References/Refs.hs b/lib/Text/Pandoc/CrossRef/References/Refs.hs index b0f617ee..b7105ba3 100644 --- a/lib/Text/Pandoc/CrossRef/References/Refs.hs +++ b/lib/Text/Pandoc/CrossRef/References/Refs.hs @@ -61,7 +61,7 @@ replaceRefs opts ils toList . (<> fromList xs) . intrclt <$> mapM replaceRefs' citRefData where eqPred :: RefDataComplete -> RefDataComplete -> Bool - eqPred = (==) `on` liftM2 (,) rdScope rdPrefix + eqPred = (==) `on` liftM2 (,) rdLevel rdPrefix intrclt = intercalate' (text ", ") replaceRefs' (Left xs) = restoreCits' xs replaceRefs' (Right xs) = intrclt <$> mapM replaceRefs'' (NE.groupBy eqPred xs) @@ -163,6 +163,9 @@ rdPrefix RefDataComplete{rdRec} = refPfx rdRec rdLabel :: RefDataComplete -> String rdLabel RefDataComplete{rdRec} = refLabel rdRec +rdLevel :: RefDataComplete -> Int +rdLevel RefDataComplete{rdRec} = refLevel rdRec + instance Eq RefDataComplete where (==) = (==) `on` rdRec diff --git a/test/m2m/scoping/expect.tex b/test/m2m/scoping/expect.tex index 6ce7b7b8..9f02959e 100644 --- a/test/m2m/scoping/expect.tex +++ b/test/m2m/scoping/expect.tex @@ -1,10 +1,8 @@ \hypertarget{sec:1}{% -\section{\texorpdfstring{\label{sec:1}Section -1}{Section 1}}\label{sec:1}} +\section{Chapter 1. Section 1}\label{sec:1}} \hypertarget{sec:11}{% -\subsection{\texorpdfstring{\label{sec:11}Section -1.1}{Section 1.1}}\label{sec:11}} +\subsection{Section 1.1. Section 1.1}\label{sec:11}} \leavevmode\hypertarget{dfn:group}{}% A \emph{group} is a pair \((R,*)\) satisfying: @@ -16,20 +14,16 @@ \subsection{\texorpdfstring{\label{sec:11}Section \end{enumerate} \hypertarget{sec:2}{% -\section{\texorpdfstring{\label{sec:2}Section -2}{Section 2}}\label{sec:2}} +\section{Chapter 2. Section 2}\label{sec:2}} \hypertarget{sec:21}{% -\subsection{\texorpdfstring{\label{sec:21}Section -2.1}{Section 2.1}}\label{sec:21}} +\subsection{Section 2.1. Section 2.1}\label{sec:21}} \hypertarget{sec:211}{% -\subsubsection{\texorpdfstring{\label{sec:211}Section -2.1.1}{Section 2.1.1}}\label{sec:211}} +\subsubsection{Paragraph 2.1.1. Section 2.1.1}\label{sec:211}} \hypertarget{sec:212}{% -\subsubsection{\texorpdfstring{\label{sec:212}Section -2.1.2}{Section 2.1.2}}\label{sec:212}} +\subsubsection{Paragraph 2.1.2. Section 2.1.2}\label{sec:212}} \leavevmode\hypertarget{dfn:ring}{}% A \emph{ring} is a triple \((R,+,*)\) satisfying: @@ -45,8 +39,7 @@ \subsubsection{\texorpdfstring{\label{sec:212}Section \end{enumerate} \hypertarget{section-3}{% -\section{\texorpdfstring{\label{section-3}Section -3}{Section 3}}\label{section-3}} +\section{Chapter 3. Section 3}\label{section-3}} \begin{itemize} \item diff --git a/test/m2m/section-template/expect.tex b/test/m2m/section-template/expect.tex index 8df4679e..101c9178 100644 --- a/test/m2m/section-template/expect.tex +++ b/test/m2m/section-template/expect.tex @@ -1,21 +1,19 @@ \hypertarget{first-level-section}{% -\section{\texorpdfstring{\label{first-level-section}First Level -Section}{First Level Section}}\label{first-level-section}} +\section{Chapter 1. First Level Section}\label{first-level-section}} \hypertarget{second-level-section}{% -\subsection{\texorpdfstring{\label{second-level-section}Second Level -Section}{Second Level Section}}\label{second-level-section}} +\subsection{Section 1.1. Second Level +Section}\label{second-level-section}} \hypertarget{thrid-level-section}{% -\subsubsection{\texorpdfstring{\label{thrid-level-section}Thrid Level -Section}{Thrid Level Section}}\label{thrid-level-section}} +\subsubsection{Paragraph 1.1.1. Thrid Level +Section}\label{thrid-level-section}} \hypertarget{fourth-level-section}{% -\paragraph{\texorpdfstring{\label{fourth-level-section}Fourth Level -Section}{Fourth Level Section}}\label{fourth-level-section}} +\paragraph{1.1.1.1. Fourth Level Section}\label{fourth-level-section}} \hypertarget{fifth-level-section}{% -\subparagraph{\texorpdfstring{\label{fifth-level-section}Fifth Level -Section}{Fifth Level Section}}\label{fifth-level-section}} +\subparagraph{1.1.1.1.1. Fifth Level +Section}\label{fifth-level-section}} -\label{sixth-level-section}Sixth Level Section +1.1.1.1.1.1. Sixth Level Section diff --git a/test/test-pandoc-crossref.hs b/test/test-pandoc-crossref.hs index 737a5764..f238de11 100644 --- a/test/test-pandoc-crossref.hs +++ b/test/test-pandoc-crossref.hs @@ -56,7 +56,7 @@ main = hspec $ do it "Labels equations" $ testAll (plain $ equation' "a^2+b^2=c^2" "equation") (plain $ spanWith ("eq:equation", [], []) (equation' "a^2+b^2=c^2\\qquad(1)" []), - (referenceData =: M.fromList $ refRec' "eq:equation" 1 (math "a^2+b^2=c^2") "1") . + (referenceData =: M.fromList [refRec' "eq:equation" 1 (math "a^2+b^2=c^2") "1"]) . (pfxCounter =: M.singleton "eq" $ CounterRec {crIndex = 1, crIndexInScope = M.singleton Nothing 1}) ) it "Labels equations in the middle of text" $ @@ -68,7 +68,7 @@ main = hspec $ do text "This is an equation: " <> spanWith ("eq:equation", [], []) (equation' "a^2+b^2=c^2\\qquad(1)" []) <> text " it should be labeled", - (referenceData =: M.fromList $ refRec' "eq:equation" 1 (math "a^2+b^2=c^2") "1") . + (referenceData =: M.fromList [refRec' "eq:equation" 1 (math "a^2+b^2=c^2") "1"]) . (pfxCounter =: M.singleton "eq" $ CounterRec {crIndex = 1, crIndexInScope = M.singleton Nothing 1}) ) it "Labels equations in the beginning of text" $ @@ -78,7 +78,7 @@ main = hspec $ do (plain $ spanWith ("eq:equation", [], []) (equation' "a^2+b^2=c^2\\qquad(1)" []) <> text " it should be labeled", - (referenceData =: M.fromList $ refRec' "eq:equation" 1 (math "a^2+b^2=c^2") "1") . + (referenceData =: M.fromList [refRec' "eq:equation" 1 (math "a^2+b^2=c^2") "1"]) . (pfxCounter =: M.singleton "eq" $ CounterRec {crIndex = 1, crIndexInScope = M.singleton Nothing 1}) ) it "Labels equations in the end of text" $ @@ -88,7 +88,7 @@ main = hspec $ do (plain $ text "This is an equation: " <> spanWith ("eq:equation", [], []) (equation' "a^2+b^2=c^2\\qquad(1)" []), - (referenceData =: M.fromList $ refRec' "eq:equation" 1 (math "a^2+b^2=c^2") "1") . + (referenceData =: M.fromList [refRec' "eq:equation" 1 (math "a^2+b^2=c^2") "1"]) . (pfxCounter =: M.singleton "eq" $ CounterRec {crIndex = 1, crIndexInScope = M.singleton Nothing 1}) ) @@ -100,7 +100,7 @@ main = hspec $ do it "Labels images" $ testAll (figure "test.jpg" [] "Test figure" "figure") (figure "test.jpg" [] "Figure 1: Test figure" "figure", - (referenceData =: M.fromList $ refRec' "fig:figure" 1 "Test figure" "Figure 1: Test figure") . + (referenceData =: M.fromList [refRec' "fig:figure" 1 "Test figure" "Figure 1: Test figure"]) . (pfxCounter =: M.singleton "fig" $ CounterRec {crIndex = 1, crIndexInScope = M.singleton Nothing 1}) ) -- it "Labels subfigures" $ @@ -171,7 +171,7 @@ main = hspec $ do it "Labels equations" $ testAll (equation "a^2+b^2=c^2" "equation") (para $ spanWith ("eq:equation", [], []) (equation' "a^2+b^2=c^2\\qquad(1)" []), - (referenceData =: M.fromList $ refRec' "eq:equation" 1 (math "a^2+b^2=c^2") "1") . + (referenceData =: M.fromList [refRec' "eq:equation" 1 (math "a^2+b^2=c^2") "1"]) . (pfxCounter =: M.singleton "eq" $ CounterRec {crIndex = 1, crIndexInScope = M.singleton Nothing 1}) ) it "Labels equations in the middle of text" $ @@ -183,7 +183,7 @@ main = hspec $ do text "This is an equation: " <> spanWith ("eq:equation", [], []) (equation' "a^2+b^2=c^2\\qquad(1)" []) <> text " it should be labeled", - (referenceData =: M.fromList $ refRec' "eq:equation" 1 (math "a^2+b^2=c^2") "1") . + (referenceData =: M.fromList [refRec' "eq:equation" 1 (math "a^2+b^2=c^2") "1"]) . (pfxCounter =: M.singleton "eq" $ CounterRec {crIndex = 1, crIndexInScope = M.singleton Nothing 1}) ) it "Labels equations in the beginning of text" $ @@ -193,7 +193,7 @@ main = hspec $ do (para $ spanWith ("eq:equation", [], []) (equation' "a^2+b^2=c^2\\qquad(1)" []) <> text " it should be labeled", - (referenceData =: M.fromList $ refRec' "eq:equation" 1 (math "a^2+b^2=c^2") "1") . + (referenceData =: M.fromList [refRec' "eq:equation" 1 (math "a^2+b^2=c^2") "1"]) . (pfxCounter =: M.singleton "eq" $ CounterRec {crIndex = 1, crIndexInScope = M.singleton Nothing 1}) ) it "Labels equations in the end of text" $ @@ -203,31 +203,31 @@ main = hspec $ do (para $ text "This is an equation: " <> spanWith ("eq:equation", [], []) (equation' "a^2+b^2=c^2\\qquad(1)" []), - (referenceData =: M.fromList $ refRec' "eq:equation" 1 (math "a^2+b^2=c^2") "1") . + (referenceData =: M.fromList [refRec' "eq:equation" 1 (math "a^2+b^2=c^2") "1"]) . (pfxCounter =: M.singleton "eq" $ CounterRec {crIndex = 1, crIndexInScope = M.singleton Nothing 1}) ) it "Labels tables" $ testAll (table' "Test table" "table") (divWith ("tbl:table", [], []) $ table' "Table 1: Test table" [], - (referenceData =: M.fromList $ refRec' "tbl:table" 1 "Test table" "Table 1: Test table") . + (referenceData =: M.fromList [refRec' "tbl:table" 1 "Test table" "Table 1: Test table"]) . (pfxCounter =: M.singleton "tbl" $ CounterRec {crIndex = 1, crIndexInScope = M.singleton Nothing 1}) ) it "Labels code blocks" $ testAll (codeBlock' "Test code block" "codeblock") (codeBlockDiv "Listing 1: Test code block" "codeblock", - (referenceData =: M.fromList $ refRec' "lst:codeblock" 1 "Test code block" "Listing 1: Test code block") . + (referenceData =: M.fromList [refRec' "lst:codeblock" 1 "Test code block" "Listing 1: Test code block"]) . (pfxCounter =: M.singleton "lst" $ CounterRec {crIndex = 1, crIndexInScope = M.singleton Nothing 1}) ) it "Labels code block divs" $ testAll (codeBlockDiv "Test code block" "codeblock") (codeBlockDiv "Listing 1: Test code block" "codeblock", - (referenceData =: M.fromList $ refRec' "lst:codeblock" 1 "Test code block" "Listing 1: Test code block") . + (referenceData =: M.fromList [refRec' "lst:codeblock" 1 "Test code block" "Listing 1: Test code block"]) . (pfxCounter =: M.singleton "lst" $ CounterRec {crIndex = 1, crIndexInScope = M.singleton Nothing 1}) ) it "Labels sections divs" $ testAll (section "Section Header" 1 "section") (section "Section Header" 1 "section", - (referenceData ^= M.fromList (refRec' "sec:section" 1 "Section Header" "")) + (referenceData ^= M.fromList [refRec' "sec:section" 1 "Section Header" ""]) . (pfxCounter =: M.singleton "sec" $ CounterRec {crIndex = 1, crIndexInScope = M.singleton Nothing 1}) ) @@ -253,7 +253,14 @@ main = hspec $ do it "References multiple sections" $ testRefs' "sec:" [1..3] [4..6] referenceData "secs.\160\&4-6" it "Separates references to different chapter items by a comma" $ - testRefs'' "lst:" [1..6] (zip [1,1..] [4..6] ++ zip [2,2..] [7..9]) referenceData "lsts.\160\&1.4-1.6, 2.7-2.9" + let p = "lst:" + cites = citeGen p [1..6] + chap1 = snd $ refRec' "sec:1" 1 "Section 1" "Section 1" + chap2 = snd $ refRec' "sec:2" 2 "Section 2" "Section 2" + refs1 = M.map (\r -> r{refScope = Just chap1}) $ refGen p [1..3] [4..6] + refs2 = M.map (\r -> r{refScope = Just chap2}) $ refGen p [4..6] [7..9] + res = "lsts.\160\&4-6, 7-9" + in testRefs (para cites) (setVal referenceData (refs1 <> refs2) def) (para $ text res) describe "References.Refs.replaceRefs capitalization" $ do it "References one image" $ @@ -280,11 +287,11 @@ main = hspec $ do describe "References.List.listOf" $ do it "Generates list of tables" $ testList (rawBlock "latex" "\\listoftables") - (referenceData =: M.fromList $ refRec' "tbl:1" 4 "4" "Table 4: 4" <> refRec' "tbl:2" 5 "5" "Table 5: 5" <> refRec' "tbl:3" 6 "6" "Table 6: 6") + (referenceData =: M.fromList [let l = "tbl:" <> show i; n = i + 3; sn = str $ show n in refRec' l n sn ("Table " <> sn <> ": " <> sn) | i <- [1..3]]) (header 1 (text "List of Tables") <> divWith ("",["list"],[]) (foldl1' (<>) $ map (\i -> let n = show i in para $ text (n <> ". " <> n) ) [4..6 :: Int])) it "Generates list of figures" $ testList (rawBlock "latex" "\\listoffigures") - (referenceData =: M.fromList $ refRec' "fig:1" 4 "4" "Figure 4: 4" <> refRec' "fig:2" 5 "5" "Figure 5: 5" <> refRec' "fig:3" 6 "6" "Figure 6: 6") + (referenceData =: M.fromList [let l = "fig:" <> show i; n = i + 3; sn = str $ show n in refRec' l n sn ("Figure " <> sn <> ": " <> sn) | i <- [1..3]]) (header 1 (text "List of Figures") <> divWith ("",["list"],[]) (foldl1' (<>) $ map (\i -> let n = show i in para $ text (n <> ". " <> n) ) [4..6 :: Int])) describe "Util.CodeBlockCaptions" $ @@ -386,36 +393,17 @@ citeGen p l = cite (mconcat $ map (cit . (p++) . show) l) $ text $ "[" ++ intercalate "; " (map (("@"++) . (p++) . show) l) ++ "]" refGen :: String -> [Int] -> [Int] -> M.Map String RefRec -refGen p l1 l2 = M.fromList $ mconcat $ zipWith (\r i -> refRec' r i mempty mempty) (((uncapitalizeFirst p++) . show) `map` l1) l2 +refGen p l1 l2 = M.fromList $ zipWith (\r i -> refRec' r i mempty mempty) (((uncapitalizeFirst p++) . show) `map` l1) l2 -refGen' :: String -> [Int] -> [(Int, Int)] -> M.Map String RefRec -refGen' p l1 l2 = M.fromList $ mconcat $ zipWith refRec''' (((uncapitalizeFirst p++) . show) `map` l1) l2 - -refRec' :: String -> Int -> Inlines -> String -> [(String, RefRec)] +refRec' :: String -> Int -> Inlines -> Inlines -> (String, RefRec) refRec' ref i tit cap = let pfx = takeWhile (/=':') ref - in [(ref + in ( ref , RefRec { refIndex=i , refIxInl = str $ show i - , refCaption= text cap,refTitle=tit,refScope=Nothing - , refLevel=0 - , refPfx=pfx - , refLabel=ref - , refAttrs = M.empty - , refPfxRec = fromJust $ M.lookup pfx defaultPrefixes - } - )] - -refRec''' :: String -> (Int, Int) -> [(String, RefRec)] -refRec''' ref (c,i) = - let pfx = takeWhile (/=':') ref - in [(ref - , RefRec - { refIndex=c+i - , refIxInl = str $ show i - , refCaption=str $ show i - , refTitle=text [] + , refCaption= cap + , refTitle=tit , refScope=Nothing , refLevel=0 , refPfx=pfx @@ -423,14 +411,14 @@ refRec''' ref (c,i) = , refAttrs = M.empty , refPfxRec = fromJust $ M.lookup pfx defaultPrefixes } - )] + ) + +testRefs :: Blocks -> References -> Blocks -> Expectation +testRefs bs st rbs = testState (bottomUpM (References.Refs.replaceRefs defaultOptions)) st bs (rbs, id) testRefs' :: String -> [Int] -> [Int] -> Accessor References (M.Map String RefRec) -> String -> Expectation testRefs' p l1 l2 prop res = testRefs (para $ citeGen p l1) (setVal prop (refGen p l1 l2) def) (para $ text res) -testRefs'' :: String -> [Int] -> [(Int, Int)] -> Accessor References (M.Map String RefRec) -> String -> Expectation -testRefs'' p l1 l2 prop res = testRefs (para $ citeGen p l1) (setVal prop (refGen' p l1 l2) def) (para $ text res) - testAll :: Many Block -> (Many Block, References -> References) -> Expectation testAll = testState f def where f = References.Blocks.replaceAll defaultOptions @@ -454,9 +442,6 @@ testState :: (Eq a1, Show a1) => ([a] -> WS [a1]) -> References -> Many a -> (Ma testState f init' arg (r, s) = evalCrossRefM $ (`shouldBe` (toList r, s init')) <$> runStateT (unWS . f $ toList arg) init' -testRefs :: Blocks -> References -> Blocks -> Expectation -testRefs bs st rbs = testState (bottomUpM (References.Refs.replaceRefs defaultOptions)) st bs (rbs, id) - testCBCaptions :: Blocks -> Blocks -> Expectation testCBCaptions bs res = bottomUp (Util.CodeBlockCaptions.mkCodeBlockCaptions defaultOptions{Text.Pandoc.CrossRef.Util.Options.codeBlockCaptions=True}) (toList bs) `shouldBe` toList res From f3e6c246fde8b9f14779bc75d32754018c03b790 Mon Sep 17 00:00:00 2001 From: Nikolay Yakimov Date: Sun, 3 Mar 2019 15:11:44 +0300 Subject: [PATCH 058/134] See full message - Attribute overrides: some reference properties can be overridden by attributes - metadata tweaks: use nbsp between item title and item number in captions. - more generic templates: use typeclass function makeTemplate for all template types - removed LatexPrefixes: wasn't really used; the initial motivation for it didn't pan out --- lib/Text/Pandoc/CrossRef/References/Blocks.hs | 26 +++++--- .../Pandoc/CrossRef/References/Types/Ref.hs | 2 +- .../Pandoc/CrossRef/Util/LatexPrefixes.hs | 26 -------- lib/Text/Pandoc/CrossRef/Util/ModifyMeta.hs | 3 +- .../Pandoc/CrossRef/Util/Options/Types.hs | 2 - lib/Text/Pandoc/CrossRef/Util/Prefixes.hs | 60 +++++++++++-------- .../Pandoc/CrossRef/Util/Prefixes/Types.hs | 14 ++--- lib/Text/Pandoc/CrossRef/Util/Settings.hs | 14 +---- .../Pandoc/CrossRef/Util/Settings/Template.hs | 3 - lib/Text/Pandoc/CrossRef/Util/Template.hs | 46 +++++++------- .../Pandoc/CrossRef/Util/Template/Types.hs | 7 +++ lib/Text/Pandoc/CrossRef/Util/VarFunction.hs | 5 +- pandoc-crossref.cabal | 4 +- test/m2m/capitalization/expect.md | 4 +- test/m2m/list-of/expect.md | 12 ++-- test/m2m/listing-captions-ids/expect.md | 16 ++--- test/m2m/ref-attrs/expect.md | 6 +- test/test-pandoc-crossref.hs | 24 ++++---- 18 files changed, 128 insertions(+), 146 deletions(-) delete mode 100644 lib/Text/Pandoc/CrossRef/Util/LatexPrefixes.hs diff --git a/lib/Text/Pandoc/CrossRef/References/Blocks.hs b/lib/Text/Pandoc/CrossRef/References/Blocks.hs index 83c77dee..b8c7eff0 100644 --- a/lib/Text/Pandoc/CrossRef/References/Blocks.hs +++ b/lib/Text/Pandoc/CrossRef/References/Blocks.hs @@ -18,7 +18,7 @@ with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -} -{-# LANGUAGE Rank2Types, MultiWayIf, RecordWildCards, NamedFieldPuns #-} +{-# LANGUAGE RecordWildCards, NamedFieldPuns, TypeFamilies #-} module Text.Pandoc.CrossRef.References.Blocks ( replaceAll ) where @@ -37,6 +37,7 @@ import Text.Pandoc.CrossRef.Util.Util import Text.Pandoc.CrossRef.Util.Options import Text.Pandoc.CrossRef.Util.Prefixes import Text.Pandoc.CrossRef.Util.Template +import Text.Pandoc.CrossRef.Util.CustomLabels import Text.Pandoc.CrossRef.Util.CodeBlockCaptions import Text.Pandoc.CrossRef.Util.VarFunction import Text.Pandoc.CrossRef.Util.Replace @@ -105,7 +106,7 @@ replaceBlock opts scope (Div (label,"listing":_, []) [Para caption, CodeBlock ([ | isLatexFormat f -> Div nullAttr [ RawBlock (Format "latex") "\\begin{codelisting}" - , Para [ + , Plain [ RawInline (Format "latex") "\\caption" , Span nullAttr caption ] @@ -147,8 +148,8 @@ replaceInline opts scope (Span attrs@(label,_,_) [Math DisplayMath eq]) (eq', _) <- replaceEqn opts scope attrs eq pfx replaceNoRecurse $ case outFormat opts of f | isLatexFormat f -> - let eqn = "\\begin{equation}"++eq++mkLaTeXLabel label++"\\end{equation}" - in RawInline (Format "latex") eqn + RawInline (Format "latex") + $ "\\begin{equation}"++eq++mkLaTeXLabel label++"\\end{equation}" _ -> Span attrs [Math DisplayMath eq'] replaceInline opts scope (Image attr@(label,_,attrs) alt img@(_, tit)) | Just pfx <- getRefPrefix opts label @@ -216,18 +217,25 @@ replaceAttr :: Options -> Scope -> Either String String -> [(String, String)] -> replaceAttr o scope label attrs title pfx = do ropt <- liftEither $ getPfx o pfx - let itemScope = find ((`elem` prefixScope ropt) . refPfx) scope - refLabel' = lookup "label" attrs + let attrMap = M.fromListWith (flip (++)) $ map (second return) attrs + metaAttrMap = M.map attr2meta attrMap + attr2meta [s] = MetaString s + attr2meta ss = MetaList $ map MetaString ss + scopeSpecifier = fromMaybe (prefixScope ropt) $ M.lookup "scope" attrMap + itemScope = find ((`elem` scopeSpecifier) . refPfx) scope cr <- (\CounterRec{..} -> CounterRec{ crIndex = crIndex+1 , crIndexInScope = M.insertWith (+) itemScope 1 crIndexInScope }) . fromMaybe def . M.lookup pfx <$> get pfxCounter modify pfxCounter $ M.insert pfx cr - let label' = either (++ ':':'\0':show i) id label + let refLabel' = lookup "label" attrs + label' = either (++ ':':'\0':show i) id label iInSc = fromJust $ M.lookup itemScope $ crIndexInScope cr i = crIndex cr lvl = length $ filter ((== pfx) . refPfx) scope - customLabel = prefixNumbering ropt lvl + customLabel = maybe (prefixNumbering ropt lvl) + (mkLabel $ label' <> " attribute numbering") + $ M.lookup "numbering" metaAttrMap hasLabel <- M.member label' <$> get referenceData when hasLabel $ throwError $ WSEDuplicateLabel label' let rec' = RefRec { @@ -240,7 +248,7 @@ replaceAttr o scope label attrs title pfx , refPfx = pfx , refPfxRec = ropt , refCaption = applyTitleTemplate rec' - , refAttrs = M.fromListWith (flip (++)) $ map (second return) attrs + , refAttrs = metaAttrMap } modify referenceData $ M.insert label' rec' return rec' diff --git a/lib/Text/Pandoc/CrossRef/References/Types/Ref.hs b/lib/Text/Pandoc/CrossRef/References/Types/Ref.hs index 1efe1971..b449434d 100644 --- a/lib/Text/Pandoc/CrossRef/References/Types/Ref.hs +++ b/lib/Text/Pandoc/CrossRef/References/Types/Ref.hs @@ -38,7 +38,7 @@ data RefRec = RefRec { refIndex :: !Int -- global ordinal number for prefix , refPfx :: !String -- reference prefix, the part in label before : , refPfxRec :: !Prefix -- reference prefix, the part in label before : , refCaption :: Inlines -- caption after applying template; must be non-strict - , refAttrs :: !(M.Map String [String]) -- attribute map + , refAttrs :: !(M.Map String MetaValue) -- attribute map } instance Eq RefRec where diff --git a/lib/Text/Pandoc/CrossRef/Util/LatexPrefixes.hs b/lib/Text/Pandoc/CrossRef/Util/LatexPrefixes.hs deleted file mode 100644 index a9ebc33e..00000000 --- a/lib/Text/Pandoc/CrossRef/Util/LatexPrefixes.hs +++ /dev/null @@ -1,26 +0,0 @@ -module Text.Pandoc.CrossRef.Util.LatexPrefixes where - -import Text.Pandoc.CrossRef.Util.Settings.Types -import Text.Pandoc.CrossRef.Util.Meta -import Text.Pandoc.Definition - -data LatexPrefixes = LatexPrefixes { - latexFigurePrefix :: !String - , latexTablePrefix :: !String - , latexEquationPrefix :: !String - , latexListingPrefix :: !String - , latexSectionPrefix :: !String - } - -getLatexPrefixes :: String -> Settings -> LatexPrefixes -getLatexPrefixes varN dtv - | Just (MetaMap kv') <- lookupSettings varN dtv = - let kv = Settings (Meta kv') - in LatexPrefixes { - latexFigurePrefix = getMetaString "figure" kv - , latexTablePrefix = getMetaString "table" kv - , latexEquationPrefix = getMetaString "equation" kv - , latexListingPrefix = getMetaString "listing" kv - , latexSectionPrefix = getMetaString "section" kv - } - | otherwise = error "Prefixes not defined" diff --git a/lib/Text/Pandoc/CrossRef/Util/ModifyMeta.hs b/lib/Text/Pandoc/CrossRef/Util/ModifyMeta.hs index 0d9523d3..6ed0e4d3 100644 --- a/lib/Text/Pandoc/CrossRef/Util/ModifyMeta.hs +++ b/lib/Text/Pandoc/CrossRef/Util/ModifyMeta.hs @@ -31,7 +31,6 @@ import Text.Pandoc.Shared (blocksToInlines) import Text.Pandoc.Builder hiding ((<>)) import Text.Pandoc.CrossRef.Util.Options import Text.Pandoc.CrossRef.References.Types -import Text.Pandoc.CrossRef.Util.Prefixes import Text.Pandoc.CrossRef.Util.Settings.Types import Text.Pandoc.CrossRef.Util.Util import qualified Data.Text as T @@ -112,7 +111,7 @@ modifyMeta = do toLatex = either (error . show) T.unpack . runPure . writeLaTeX def . Pandoc nullMeta . return . Plain -- TODO: Log getListOfTitle = either (const mempty) (toLatex . blocksToInlines . toList) . getTitleForListOf opts - getFloatCaption = either (const mempty) (toLatex . toList . prefixTitle) . getPfx opts + getFloatCaption = const mempty -- prefix f uc = "{" ++ toLatex (toList $ f opts uc 0) ++ "}" ++ -- "{" ++ toLatex (toList $ f opts uc 1) ++ "}" diff --git a/lib/Text/Pandoc/CrossRef/Util/Options/Types.hs b/lib/Text/Pandoc/CrossRef/Util/Options/Types.hs index 02b4c088..5a678edb 100644 --- a/lib/Text/Pandoc/CrossRef/Util/Options/Types.hs +++ b/lib/Text/Pandoc/CrossRef/Util/Options/Types.hs @@ -22,7 +22,6 @@ module Text.Pandoc.CrossRef.Util.Options.Types where import Text.Pandoc.Definition import Text.Pandoc.CrossRef.Util.Prefixes import Text.Pandoc.Builder -import Text.Pandoc.CrossRef.Util.LatexPrefixes data Options = Options { cref :: Bool , listings :: Bool @@ -38,5 +37,4 @@ data Options = Options { cref :: Bool , linkReferences :: Bool , nameInLink :: Bool , prefixes :: Prefixes - , latexPrefixes :: LatexPrefixes } diff --git a/lib/Text/Pandoc/CrossRef/Util/Prefixes.hs b/lib/Text/Pandoc/CrossRef/Util/Prefixes.hs index 7bf823cf..397b5efe 100644 --- a/lib/Text/Pandoc/CrossRef/Util/Prefixes.hs +++ b/lib/Text/Pandoc/CrossRef/Util/Prefixes.hs @@ -34,30 +34,38 @@ import Data.Maybe getPrefixes :: String -> Settings -> Prefixes getPrefixes varN dtv - | Just (MetaMap m) <- lookupSettings varN dtv = M.mapWithKey m2p m + | Just (MetaMap m) <- lookupSettings varN dtv = + let + m2p k (MetaMap kv') = Prefix { + prefixCaptionTemplate = mkT $ getTemplInline "captionTemplate" + , prefixReferenceTemplate = mkT $ getTemplInline "referenceTemplate" + , prefixReferenceIndexTemplate = mkT $ getTemplInline "referenceIndexTemplate" + , prefixCaptionIndexTemplate = mkT $ getTemplInline "captionIndexTemplate" + , prefixListItemTemplate = mkT $ getTemplInline "listItemTemplate" + , prefixListOfTitle = mkT $ getTemplBlock "listOfTitle" + , prefixScope = getMetaStringList "scope" kv + , prefixNumbering = \lvl -> + let prettyVarName = varN <> "." <> k <> "." <> varName + varName = "numbering" + in mkLabel prettyVarName + (fromMaybe (reportError prettyVarName "Numbering") + $ lookupSettings varName kv >>= getList lvl) + } + where kv = Settings (Meta kv') <> from <> dtv + from | Just fromRef <- M.lookup "from" kv' + , Just (MetaMap kv'') <- M.lookup (toString "from" fromRef) m + = Settings (Meta kv'') + | otherwise = mempty + mkT :: MakeTemplate a => ElemT a -> a + mkT = makeTemplate kv + getTemplInline = getTemplDefault getMetaInlines + getTemplBlock = getTemplDefault getMetaBlock + getTemplDefault f n = + if isJust $ lookupSettings n kv + then f n kv + else reportError n "Template" + reportError n what = error $ what <> " meta variable " <> n <> " not set for " + <> varN <> "." <> k <> ". This should not happen. Please report a bug" + m2p k _ = error $ "Invalid value for prefix " <> k + in M.mapWithKey m2p m | otherwise = error "Prefixes not defined" - where - m2p k (MetaMap kv') = Prefix { - prefixCaptionTemplate = makeTemplate kv $ getTemplDefault "captionTemplate" - , prefixReferenceTemplate = makeRefTemplate kv $ getTemplDefault "referenceTemplate" - , prefixReferenceIndexTemplate = makeTemplate kv $ getTemplDefault "referenceIndexTemplate" - , prefixCaptionIndexTemplate = makeTemplate kv $ getTemplDefault "captionIndexTemplate" - , prefixListItemTemplate = makeTemplate kv $ getTemplDefault "listItemTemplate" - , prefixScope = getMetaStringList "scope" kv - , prefixNumbering = \lvl -> - let prettyVarName = varN <> "." <> k <> "." <> varName - varName = "numbering" - in mkLabel prettyVarName - (fromMaybe (reportError prettyVarName "Numbering") - $ lookupSettings varName kv >>= getList lvl) - , prefixListOfTitle = makeBlockTemplate kv $ getMetaBlock "listOfTitle" kv - , prefixTitle = getMetaInlines "title" kv - } - where kv = Settings (Meta kv') <> dtv - getTemplDefault n = - if isJust $ lookupSettings n kv - then getMetaInlines n kv - else reportError n "Template" - reportError n what = error $ what <> " meta variable " <> n <> " not set for " - <> varN <> "." <> k <> ". This should not happen. Please report a bug" - m2p k _ = error $ "Invalid value for prefix " <> k diff --git a/lib/Text/Pandoc/CrossRef/Util/Prefixes/Types.hs b/lib/Text/Pandoc/CrossRef/Util/Prefixes/Types.hs index e5fcfdb5..e44e3fb2 100644 --- a/lib/Text/Pandoc/CrossRef/Util/Prefixes/Types.hs +++ b/lib/Text/Pandoc/CrossRef/Util/Prefixes/Types.hs @@ -18,24 +18,22 @@ with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -} +{-# LANGUAGE Rank2Types, TypeFamilies #-} + module Text.Pandoc.CrossRef.Util.Prefixes.Types where import qualified Data.Map as M import Text.Pandoc.CrossRef.Util.Template.Types -import Text.Pandoc.Builder type Prefixes = M.Map String Prefix data Prefix = Prefix { prefixCaptionTemplate :: !Template - , prefixReferenceTemplate :: !RefTemplate - , prefixScope :: ![String] - , prefixNumbering :: !(Int -> Int -> String) - , prefixListOfTitle :: !BlockTemplate , prefixReferenceIndexTemplate :: !Template , prefixCaptionIndexTemplate :: !Template , prefixListItemTemplate :: !Template - -- Used for LaTeX metadata; the same value is used in - -- default value for prefixCaptionTemplate - , prefixTitle :: Inlines + , prefixReferenceTemplate :: !RefTemplate + , prefixListOfTitle :: !BlockTemplate + , prefixScope :: ![String] + , prefixNumbering :: !(Int -> Int -> String) } diff --git a/lib/Text/Pandoc/CrossRef/Util/Settings.hs b/lib/Text/Pandoc/CrossRef/Util/Settings.hs index 80cf64fd..1935ed0d 100644 --- a/lib/Text/Pandoc/CrossRef/Util/Settings.hs +++ b/lib/Text/Pandoc/CrossRef/Util/Settings.hs @@ -75,17 +75,10 @@ defaultMeta = Settings $ <> autoEqnLabels False <> linkReferences False <> nameInLink False - <> latexPrefixes' [ - "figure" .= "fig" - , "table" .= "tbl" - , "equation" .= "eq" - , "listing" .= "lst" - , "section" .= "sec" - ] -- these are merely the defaults, can (and will) be overridden in prefix configs - <> captionTemplate (var "title" <> space <> var "i" <> var "titleDelim" <> var "t") + <> captionTemplate (var "title%\160" <> var "i" <> var "titleDelim" <> var "t") <> captionIndexTemplate (var "i") - <> referenceTemplate (var "Ref[n][lvl]" <> str "\160" <> var "rs") + <> referenceTemplate (var "Ref[n][lvl]%\160" <> var "rs") <> referenceIndexTemplate (var "i" <> var "suf") <> numbering "arabic" <> listOfTitle (header 1 $ text "List of " <> var "title" <> str "s") @@ -119,9 +112,6 @@ defaultMeta = Settings $ prefixes' :: [(String, MetaValue)] -> Meta prefixes' = prefixes . MetaMap . M.fromList -latexPrefixes' :: [(String, MetaValue)] -> Meta -latexPrefixes' = latexPrefixes . MetaMap . M.fromList - infixr 0 .: (.:) :: String -> [(String, MetaValue)] -> (String, MetaValue) key .: val = (key, MetaMap $ M.fromList val) diff --git a/lib/Text/Pandoc/CrossRef/Util/Settings/Template.hs b/lib/Text/Pandoc/CrossRef/Util/Settings/Template.hs index 15e14d8e..98e1bdda 100644 --- a/lib/Text/Pandoc/CrossRef/Util/Settings/Template.hs +++ b/lib/Text/Pandoc/CrossRef/Util/Settings/Template.hs @@ -30,7 +30,6 @@ import Language.Haskell.TH.Syntax hiding (Inline) import Data.List import Text.Pandoc.CrossRef.Util.Template import Text.Pandoc.CrossRef.Util.Prefixes -import Text.Pandoc.CrossRef.Util.LatexPrefixes namedFields :: Con -> [VarStrictType] namedFields (RecC _ fs) = fs @@ -80,7 +79,6 @@ makeCon' t accName = do tmplT <- [t|$(conT t) -> Template|] clT <- [t|$(conT t) -> String -> Int -> Maybe String|] pfxT <- [t|$(conT t) -> Prefixes|] - lpsT <- [t|$(conT t) -> LatexPrefixes|] let varName | Name (OccName n) _ <- accName = liftString n let dtv = return $ VarE $ mkName "dtv" body <- @@ -94,6 +92,5 @@ makeCon' t accName = do | t' == clT -> [|customLabel $(dtv)|] | t' == fmtT -> return $ VarE $ mkName "fmt" | t' == pfxT -> [|getPrefixes $(varName) $(dtv)|] - | t' == lpsT -> [|getLatexPrefixes $(varName) $(dtv)|] | otherwise -> fail $ show t' return [(accName, body)] diff --git a/lib/Text/Pandoc/CrossRef/Util/Template.hs b/lib/Text/Pandoc/CrossRef/Util/Template.hs index 3b5b6317..fabfe8c7 100644 --- a/lib/Text/Pandoc/CrossRef/Util/Template.hs +++ b/lib/Text/Pandoc/CrossRef/Util/Template.hs @@ -18,15 +18,14 @@ with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -} -{-# LANGUAGE RecordWildCards #-} +{-# OPTIONS_GHC -fno-warn-orphans #-} +{-# LANGUAGE RecordWildCards, TypeFamilies #-} module Text.Pandoc.CrossRef.Util.Template ( Template , RefTemplate , BlockTemplate - , makeTemplate - , makeBlockTemplate - , makeRefTemplate + , MakeTemplate(..) , applyTemplate , applyRefTemplate , applyBlockTemplate @@ -68,13 +67,30 @@ parse StAfterIndex (c:_) = error $ "Unexpected character " <> [c] <> " after par parse StPrefix cs = let (pfx, rest) = span (`notElem` "%#") cs in (parse StPrefix rest){prPfx = pfx} parse StSuffix cs = let (sfx, rest) = span (`notElem` "%#") cs in (parse StSuffix rest){prSfx = sfx} -makeTemplate :: Settings -> Inlines -> Template -makeTemplate dtv xs' = Template $ \vf -> fromList $ scan (\var -> vf var <|> lookupSettings var dtv) $ toList xs' +instance MakeTemplate Template where + type ElemT Template = Inlines + makeTemplate dtv xs' = Template (genTemplate dtv xs') -makeBlockTemplate :: Settings -> Blocks -> BlockTemplate -makeBlockTemplate dtv xs' = BlockTemplate $ \vf -> fromList $ scan (\var -> vf var <|> lookupSettings var dtv) $ toList xs' +instance MakeTemplate BlockTemplate where + type ElemT BlockTemplate = Blocks + makeTemplate dtv xs' = BlockTemplate (genTemplate dtv xs') -scan :: (Data a) => (String -> Maybe MetaValue) -> [a] -> [a] +instance MakeTemplate RefTemplate where + type ElemT RefTemplate = Inlines + makeTemplate dtv xs' = RefTemplate $ \vars cap -> g (vf vars cap) + where Template g = makeTemplate dtv xs' + vf vars cap (vc:vs) + | isUpper vc && cap = capitalize lookup' var + | otherwise = lookup' var + where + var = toLower vc : vs + lookup' x = vars x <|> lookupSettings x dtv + vf _ _ [] = error "Empty variable name" + +genTemplate :: (Data a) => Settings -> Many a -> VarFunc -> Many a +genTemplate dtv xs' vf = fromList $ scan (\var -> vf var <|> lookupSettings var dtv) $ toList xs' + +scan :: (Data a) => VarFunc -> [a] -> [a] scan = bottomUp . go where go vf (Math DisplayMath var:xs) @@ -91,15 +107,3 @@ scan = bottomUp . go in toList $ replaceVar arr <> fromList xs go _ (x:xs) = toList $ singleton x <> fromList xs go _ [] = [] - -makeRefTemplate :: Settings -> Inlines -> RefTemplate -makeRefTemplate dtv xs' = - let Template g = makeTemplate dtv xs' - vf vars cap (vc:vs) - | isUpper vc && cap = capitalize lookup' var - | otherwise = lookup' var - where - var = toLower vc : vs - lookup' x = vars x <|> lookupSettings x dtv - vf _ _ [] = error "Empty variable name" - in RefTemplate $ \vars cap -> g (vf vars cap) diff --git a/lib/Text/Pandoc/CrossRef/Util/Template/Types.hs b/lib/Text/Pandoc/CrossRef/Util/Template/Types.hs index 87830182..3fad90c2 100644 --- a/lib/Text/Pandoc/CrossRef/Util/Template/Types.hs +++ b/lib/Text/Pandoc/CrossRef/Util/Template/Types.hs @@ -18,12 +18,19 @@ with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -} +{-# LANGUAGE TypeFamilies #-} + module Text.Pandoc.CrossRef.Util.Template.Types where import Text.Pandoc.Definition import Text.Pandoc.Builder +import Text.Pandoc.CrossRef.Util.Settings.Types type VarFunc = String -> Maybe MetaValue newtype Template = Template { applyTemplate :: VarFunc -> Inlines } newtype RefTemplate = RefTemplate { applyRefTemplate :: VarFunc -> Bool -> Inlines } newtype BlockTemplate = BlockTemplate { applyBlockTemplate :: VarFunc -> Blocks } + +class MakeTemplate a where + type ElemT a + makeTemplate :: Settings -> ElemT a -> a diff --git a/lib/Text/Pandoc/CrossRef/Util/VarFunction.hs b/lib/Text/Pandoc/CrossRef/Util/VarFunction.hs index afac245b..1616ba64 100644 --- a/lib/Text/Pandoc/CrossRef/Util/VarFunction.hs +++ b/lib/Text/Pandoc/CrossRef/Util/VarFunction.hs @@ -41,7 +41,4 @@ defaultVarFunc self RefRec{..} x = case x of _ | Just y <- stripPrefix "s." x , Just rs <- refScope -> self rs y - _ -> case M.lookup x refAttrs of - Just [s] -> Just $ MetaString s - Just ss -> Just $ MetaList $ map MetaString ss - _ -> Nothing + _ -> M.lookup x refAttrs diff --git a/pandoc-crossref.cabal b/pandoc-crossref.cabal index 3d739582..92b514a4 100644 --- a/pandoc-crossref.cabal +++ b/pandoc-crossref.cabal @@ -4,7 +4,7 @@ cabal-version: 1.12 -- -- see: https://github.com/sol/hpack -- --- hash: a74d9949e6fbdca0da757f8c93d777e91730714d6f061cb9fb525e6b49fc14f6 +-- hash: a2145f6739c0ed44aff150fb432e29dab9abf1086b31606d5abb876004ac2b54 name: pandoc-crossref version: 0.4.0.0 @@ -106,7 +106,6 @@ library Text.Pandoc.CrossRef.References.Types.Ref Text.Pandoc.CrossRef.Util.CodeBlockCaptions Text.Pandoc.CrossRef.Util.CustomLabels - Text.Pandoc.CrossRef.Util.LatexPrefixes Text.Pandoc.CrossRef.Util.Meta Text.Pandoc.CrossRef.Util.ModifyMeta Text.Pandoc.CrossRef.Util.Options @@ -223,7 +222,6 @@ test-suite test-pandoc-crossref Text.Pandoc.CrossRef.References.Types.Ref Text.Pandoc.CrossRef.Util.CodeBlockCaptions Text.Pandoc.CrossRef.Util.CustomLabels - Text.Pandoc.CrossRef.Util.LatexPrefixes Text.Pandoc.CrossRef.Util.Meta Text.Pandoc.CrossRef.Util.ModifyMeta Text.Pandoc.CrossRef.Util.Options diff --git a/test/m2m/capitalization/expect.md b/test/m2m/capitalization/expect.md index 601423f7..b223145e 100644 --- a/test/m2m/capitalization/expect.md +++ b/test/m2m/capitalization/expect.md @@ -1,13 +1,13 @@ [$$eqn\qquad(1)$$]{#eq:1} -![Figure 1: Image](img.png){#fig:1} +![Figure 1: Image](img.png){#fig:1} ::: {#tbl:1} a b --- --- c d - : Table 1: Table + : Table 1: Table ::: eq. 1, Eq. 1, fig. 1, Fig. 1, tbl. 1, Tbl. 1 diff --git a/test/m2m/list-of/expect.md b/test/m2m/list-of/expect.md index a04d791b..925fb249 100644 --- a/test/m2m/list-of/expect.md +++ b/test/m2m/list-of/expect.md @@ -1,18 +1,18 @@ [$$eqn1\qquad(1)$$]{#eq:1} [$$eqn2\qquad(2)$$]{#eq:2} [$$eqn3\qquad(3)$$]{#eq:3} -![Figure 1: Image 1](img.png){#fig:1} +![Figure 1: Image 1](img.png){#fig:1} -![Figure 2: Image 2](img.png){#fig:2} +![Figure 2: Image 2](img.png){#fig:2} -![Figure 3: Image 3](img.png){#fig:3} +![Figure 3: Image 3](img.png){#fig:3} ::: {#tbl:1} a b --- --- c d - : Table 1: Table 1 + : Table 1: Table 1 ::: ::: {#tbl:2} @@ -20,7 +20,7 @@ --- --- c d - : Table 2: Table 2 + : Table 2: Table 2 ::: ::: {#tbl:3} @@ -28,7 +28,7 @@ --- --- c d - : Table 3: Table 3 + : Table 3: Table 3 ::: List of Figures diff --git a/test/m2m/listing-captions-ids/expect.md b/test/m2m/listing-captions-ids/expect.md index fd498753..31d8b48f 100644 --- a/test/m2m/listing-captions-ids/expect.md +++ b/test/m2m/listing-captions-ids/expect.md @@ -1,7 +1,7 @@ After code block ::: {#lst:code1 .listing .haskell} -Listing 1: Listing caption 1 +Listing 1: Listing caption 1 ``` {.haskell} main :: IO () @@ -10,7 +10,7 @@ main = putStrLn "Hello World!" ::: ::: {#lst:code2 .listing .haskell} -Listing 2: Listing caption 2 +Listing 2: Listing caption 2 ``` {.haskell} main :: IO () @@ -19,7 +19,7 @@ main = putStrLn "Hello World!" ::: ::: {#lst:code3 .listing .haskell} -Listing 3: Listing caption 3 +Listing 3: Listing caption 3 ``` {.haskell} main :: IO () @@ -28,7 +28,7 @@ main = putStrLn "Hello World!" ::: ::: {#lst:code4 .listing .haskell} -Listing 4: Listing caption 4 +Listing 4: Listing caption 4 ``` {.haskell} main :: IO () @@ -53,7 +53,7 @@ main = putStrLn "Hello World!" Before code block ::: {#lst:code11 .listing .haskell} -Listing 5: Listing caption 11 +Listing 5: Listing caption 11 ``` {.haskell} main :: IO () @@ -62,7 +62,7 @@ main = putStrLn "Hello World!" ::: ::: {#lst:code12 .listing .haskell} -Listing 6: Listing caption 12 +Listing 6: Listing caption 12 ``` {.haskell} main :: IO () @@ -71,7 +71,7 @@ main = putStrLn "Hello World!" ::: ::: {#lst:code13 .listing .haskell} -Listing 7: Listing caption 13 +Listing 7: Listing caption 13 ``` {.haskell} main :: IO () @@ -80,7 +80,7 @@ main = putStrLn "Hello World!" ::: ::: {#lst:code14 .listing .haskell} -Listing 8: Listing caption 14 +Listing 8: Listing caption 14 ``` {.haskell} main :: IO () diff --git a/test/m2m/ref-attrs/expect.md b/test/m2m/ref-attrs/expect.md index fe4922ea..d94e3dd7 100644 --- a/test/m2m/ref-attrs/expect.md +++ b/test/m2m/ref-attrs/expect.md @@ -1,10 +1,10 @@ -![Test1 1: Image 1](img.png){#fig:1 ref="img." ref="imgs." +![Test1 1: Image 1](img.png){#fig:1 ref="img." ref="imgs." title="Test1"} -![Test2 2: Image 2](img.png){#fig:2 ref="img." ref="imgs." +![Test2 2: Image 2](img.png){#fig:2 ref="img." ref="imgs." title="Test2"} -![Figure 3: Image 3](img.png){#fig:3} +![Figure 3: Image 3](img.png){#fig:3} This should have custom prefix: img. 1 diff --git a/test/test-pandoc-crossref.hs b/test/test-pandoc-crossref.hs index f238de11..73326f01 100644 --- a/test/test-pandoc-crossref.hs +++ b/test/test-pandoc-crossref.hs @@ -22,7 +22,7 @@ with this program; if not, write to the Free Software Foundation, Inc., {-# LANGUAGE FlexibleContexts, CPP, OverloadedStrings, TypeSynonymInstances , FlexibleInstances, StandaloneDeriving #-} import Test.Hspec -import Text.Pandoc hiding (getDataFileName) +import Text.Pandoc hiding (getDataFileName, Template) import Text.Pandoc.Builder import Control.Monad.State import Data.List @@ -36,6 +36,7 @@ import Text.Pandoc.CrossRef.Util.Options import Text.Pandoc.CrossRef.Util.Prefixes import Text.Pandoc.CrossRef.Util.Util import Text.Pandoc.CrossRef.References.Types +import Text.Pandoc.CrossRef.Util.Template.Types import Text.Pandoc.CrossRef.Util.Settings.Types import Data.Accessor hiding ((=:)) import qualified Text.Pandoc.CrossRef.References.Blocks as References.Blocks @@ -99,7 +100,7 @@ main = hspec $ do describe "References.Blocks.replaceBlocks" $ do it "Labels images" $ testAll (figure "test.jpg" [] "Test figure" "figure") - (figure "test.jpg" [] "Figure 1: Test figure" "figure", + (figure "test.jpg" [] "Figure\160\&1: Test figure" "figure", (referenceData =: M.fromList [refRec' "fig:figure" 1 "Test figure" "Figure 1: Test figure"]) . (pfxCounter =: M.singleton "fig" $ CounterRec {crIndex = 1, crIndexInScope = M.singleton Nothing 1}) ) @@ -208,20 +209,20 @@ main = hspec $ do ) it "Labels tables" $ testAll (table' "Test table" "table") - (divWith ("tbl:table", [], []) $ table' "Table 1: Test table" [], + (divWith ("tbl:table", [], []) $ table' "Table\160\&1: Test table" [], (referenceData =: M.fromList [refRec' "tbl:table" 1 "Test table" "Table 1: Test table"]) . (pfxCounter =: M.singleton "tbl" $ CounterRec {crIndex = 1, crIndexInScope = M.singleton Nothing 1}) ) it "Labels code blocks" $ testAll (codeBlock' "Test code block" "codeblock") - (codeBlockDiv "Listing 1: Test code block" "codeblock", - (referenceData =: M.fromList [refRec' "lst:codeblock" 1 "Test code block" "Listing 1: Test code block"]) . + (codeBlockDiv "Listing\160\&1: Test code block" "codeblock", + (referenceData =: M.fromList [refRec' "lst:codeblock" 1 "Test code block" "Listing\160\&1: Test code block"]) . (pfxCounter =: M.singleton "lst" $ CounterRec {crIndex = 1, crIndexInScope = M.singleton Nothing 1}) ) it "Labels code block divs" $ testAll (codeBlockDiv "Test code block" "codeblock") - (codeBlockDiv "Listing 1: Test code block" "codeblock", - (referenceData =: M.fromList [refRec' "lst:codeblock" 1 "Test code block" "Listing 1: Test code block"]) . + (codeBlockDiv "Listing\160\&1: Test code block" "codeblock", + (referenceData =: M.fromList [refRec' "lst:codeblock" 1 "Test code block" "Listing\160\&1: Test code block"]) . (pfxCounter =: M.singleton "lst" $ CounterRec {crIndex = 1, crIndexInScope = M.singleton Nothing 1}) ) it "Labels sections divs" $ @@ -288,11 +289,11 @@ main = hspec $ do it "Generates list of tables" $ testList (rawBlock "latex" "\\listoftables") (referenceData =: M.fromList [let l = "tbl:" <> show i; n = i + 3; sn = str $ show n in refRec' l n sn ("Table " <> sn <> ": " <> sn) | i <- [1..3]]) - (header 1 (text "List of Tables") <> divWith ("",["list"],[]) (foldl1' (<>) $ map (\i -> let n = show i in para $ text (n <> ". " <> n) ) [4..6 :: Int])) + (header 1 (text "List of Tables") <> divWith ("",["list"],[]) (mconcat $ map (\i -> let n = show i in para $ text (n <> ". " <> n) ) [4..6 :: Int])) it "Generates list of figures" $ testList (rawBlock "latex" "\\listoffigures") (referenceData =: M.fromList [let l = "fig:" <> show i; n = i + 3; sn = str $ show n in refRec' l n sn ("Figure " <> sn <> ": " <> sn) | i <- [1..3]]) - (header 1 (text "List of Figures") <> divWith ("",["list"],[]) (foldl1' (<>) $ map (\i -> let n = show i in para $ text (n <> ". " <> n) ) [4..6 :: Int])) + (header 1 (text "List of Figures") <> divWith ("",["list"],[]) (mconcat $ map (\i -> let n = show i in para $ text (n <> ". " <> n) ) [4..6 :: Int])) describe "Util.CodeBlockCaptions" $ it "Transforms table-style codeBlock captions to codeblock divs" $ do @@ -398,6 +399,7 @@ refGen p l1 l2 = M.fromList $ zipWith (\r i -> refRec' r i mempty mempty) (((unc refRec' :: String -> Int -> Inlines -> Inlines -> (String, RefRec) refRec' ref i tit cap = let pfx = takeWhile (/=':') ref + pfxRec = fromJust $ M.lookup pfx defaultPrefixes in ( ref , RefRec { refIndex=i @@ -409,7 +411,7 @@ refRec' ref i tit cap = , refPfx=pfx , refLabel=ref , refAttrs = M.empty - , refPfxRec = fromJust $ M.lookup pfx defaultPrefixes + , refPfxRec = pfxRec } ) @@ -431,6 +433,8 @@ evalCrossRefRes = either (error . show) id . fst instance Show Prefix where show _ = "Prefix{}" +instance Show Template where + show _ = "Template{}" deriving instance Show RefRec deriving instance Show CounterRec deriving instance Eq CounterRec From 3f1348e0bf70d113af202d851d21cf61bff5fc6d Mon Sep 17 00:00:00 2001 From: Nikolay Yakimov Date: Sun, 3 Mar 2019 20:01:38 +0300 Subject: [PATCH 059/134] Groundwork for subfigures - autoEqnLabels now specifies prefix for auto labels - added autoFigLabels - last para in reference-able div is treated as caption if it starts with `: ` - prefixes of different nesting level can be fully customized using new prefix definition `sub` property - removed awkward dependency on nesting level from prefix properties (still possible via templates) - new prefix settings `subcaption` and `subcaptionGrid` --- lib/Text/Pandoc/CrossRef/References/Blocks.hs | 68 +++-- lib/Text/Pandoc/CrossRef/References/Refs.hs | 24 +- .../Pandoc/CrossRef/References/Subfigures.hs | 238 +++++++----------- lib/Text/Pandoc/CrossRef/Util/Meta.hs | 14 +- .../Pandoc/CrossRef/Util/Options/Types.hs | 3 +- lib/Text/Pandoc/CrossRef/Util/Prefixes.hs | 7 +- .../Pandoc/CrossRef/Util/Prefixes/Types.hs | 5 +- lib/Text/Pandoc/CrossRef/Util/Settings.hs | 3 +- .../Pandoc/CrossRef/Util/Settings/Template.hs | 4 + test/m2m/equations-auto/input.md | 2 +- test/m2m/equations-tables-auto/input.md | 2 +- test/m2m/scoping/input.md | 18 +- 12 files changed, 187 insertions(+), 201 deletions(-) diff --git a/lib/Text/Pandoc/CrossRef/References/Blocks.hs b/lib/Text/Pandoc/CrossRef/References/Blocks.hs index b8c7eff0..5848cfd0 100644 --- a/lib/Text/Pandoc/CrossRef/References/Blocks.hs +++ b/lib/Text/Pandoc/CrossRef/References/Blocks.hs @@ -33,6 +33,7 @@ import Data.Monoid import qualified Data.Map as M import Text.Pandoc.CrossRef.References.Types as Types +import Text.Pandoc.CrossRef.References.Subfigures import Text.Pandoc.CrossRef.Util.Util import Text.Pandoc.CrossRef.Util.Options import Text.Pandoc.CrossRef.Util.Prefixes @@ -52,8 +53,9 @@ replaceAll opts = . runReplace [] (mkRR (replaceElement opts) `extRR` replaceBlock opts `extRR` replaceInline opts) . hierarchicalize . runSplitMath + . everywhere (mkT $ makeSubfigures opts) . everywhere (mkT (divBlocks opts) `extT` spanInlines opts) - . everywhere (mkT (mkCodeBlockCaptions opts)) + . everywhere (mkT $ mkCodeBlockCaptions opts) where runSplitMath | tableEqns opts , not $ isLatexFormat (outFormat opts) @@ -117,46 +119,59 @@ replaceBlock opts scope (Div (label,"listing":_, []) [Para caption, CodeBlock ([ mkCaption opts "Caption" caption' , CodeBlock ([], classes, attrs) code ] -replaceBlock opts scope (Para [Span attrs@(label, _, _) [Math DisplayMath eq]]) +replaceBlock opts scope (Para [Span ats@(label, _, attrs) [Math DisplayMath eq]]) | not $ isLatexFormat (outFormat opts) , tableEqns opts - , pfx <- getRefPrefix opts label + , Just pfx <- getRefPrefix opts label <|> autoEqnLabels opts + , Just lbl <- autoLabel pfx label = do - (eq', idx) <- replaceEqn opts scope attrs eq pfx - replaceNoRecurse $ Div attrs [Table [] [AlignCenter, AlignRight] [0.9, 0.09] [] [[[Plain [Math DisplayMath eq']], [Plain [Math DisplayMath $ "(" ++ idx ++ ")"]]]]] -replaceBlock opts scope x@(Div (label, _, attrs) _content) + (eq', idx) <- replaceEqn opts scope lbl attrs eq pfx + replaceNoRecurse $ Div ats [Table [] [AlignCenter, AlignRight] [0.9, 0.09] [] [[[Plain [Math DisplayMath eq']], [Plain [Math DisplayMath $ "(" ++ idx ++ ")"]]]]] +replaceBlock opts scope x@(Div ats@(label, _, attrs) content) | Just pfx <- getRefPrefix opts label = do - rec' <- replaceAttr opts scope (Right label) attrs mempty pfx - replaceRecurse (newScope rec' scope) x + let caption + | not (null content) + , Para (Str ":":Space:c) <- last content + = Just $ B.fromList c + | otherwise = Nothing + rec' <- replaceAttr opts scope (Right label) attrs (fromMaybe mempty caption) pfx + replaceRecurse (newScope rec' scope) $ case caption of + Nothing -> x + Just _ -> Div ats $ init content <> [Para $ B.toList (applyTitleTemplate rec')] replaceBlock _ scope _ = noReplaceRecurse scope -replaceEqn :: Options -> Scope -> Attr -> String -> Maybe String -> WS (String, String) -replaceEqn opts scope (label, _, attrs) eq pfx = do - let label' | null label = Left "eq" - | otherwise = Right label - idxStr <- replaceAttr opts scope label' attrs (B.math eq) (fromMaybe "eq" pfx) +replaceEqn :: Options -> Scope -> Either String String -> [(String, String)] -> String -> String -> WS (String, String) +replaceEqn opts scope label attrs eq pfx = do + idxStr <- replaceAttr opts scope label attrs (B.math eq) pfx let eq' | tableEqns opts = eq | otherwise = eq++"\\qquad("++stringify (refIxInl idxStr)++")" return (eq', stringify (refIxInl idxStr)) +autoLabel :: String -> String -> Maybe (Either String String) +autoLabel pfx label + | null label = Just $ Left pfx + | (pfx <> ":") `isPrefixOf` label = Just $ Right label + | otherwise = Nothing + replaceInline :: Options -> Scope -> Inline -> WS (ReplacedResult Inline) -replaceInline opts scope (Span attrs@(label,_,_) [Math DisplayMath eq]) - | pfx <- getRefPrefix opts label - , isJust pfx || null label && autoEqnLabels opts +replaceInline opts scope (Span ats@(label,_,attrs) [Math DisplayMath eq]) + | Just pfx <- getRefPrefix opts label <|> autoEqnLabels opts + , Just lbl <- autoLabel pfx label = do - (eq', _) <- replaceEqn opts scope attrs eq pfx + (eq', _) <- replaceEqn opts scope lbl attrs eq pfx replaceNoRecurse $ case outFormat opts of f | isLatexFormat f -> RawInline (Format "latex") $ "\\begin{equation}"++eq++mkLaTeXLabel label++"\\end{equation}" - _ -> Span attrs [Math DisplayMath eq'] + _ -> Span ats [Math DisplayMath eq'] replaceInline opts scope (Image attr@(label,_,attrs) alt img@(_, tit)) - | Just pfx <- getRefPrefix opts label + | Just pfx <- getRefPrefix opts label <|> autoFigLabels opts + , Just lbl <- autoLabel pfx label , "fig:" `isPrefixOf` tit = do let ialt = B.fromList alt - idxStr <- replaceAttr opts scope (Right label) attrs ialt pfx + idxStr <- replaceAttr opts scope lbl attrs ialt pfx let alt' = B.toList $ case outFormat opts of f | isLatexFormat f -> ialt _ -> applyTitleTemplate idxStr @@ -209,20 +224,26 @@ spanInlines opts (math@(Math DisplayMath _eq):ils) | c:ils' <- dropWhile isSpace ils , Just label <- getRefLabel opts [c] = Span (label,[],[]) [math]:ils' - | autoEqnLabels opts + | isJust $ autoEqnLabels opts = Span nullAttr [math]:ils spanInlines _ x = x replaceAttr :: Options -> Scope -> Either String String -> [(String, String)] -> B.Inlines -> String -> WS RefRec replaceAttr o scope label attrs title pfx = do - ropt <- liftEither $ getPfx o pfx + roptMain <- liftEither $ getPfx o pfx let attrMap = M.fromListWith (flip (++)) $ map (second return) attrs metaAttrMap = M.map attr2meta attrMap attr2meta [s] = MetaString s attr2meta ss = MetaList $ map MetaString ss scopeSpecifier = fromMaybe (prefixScope ropt) $ M.lookup "scope" attrMap itemScope = find ((`elem` scopeSpecifier) . refPfx) scope + lvl = length $ filter ((== pfx) . refPfx) scope + ropt = recurseSub lvl roptMain + recurseSub 0 r = r + recurseSub l r + | Just i <- prefixSub r = recurseSub (l-1) i + | otherwise = r cr <- (\CounterRec{..} -> CounterRec{ crIndex = crIndex+1 , crIndexInScope = M.insertWith (+) itemScope 1 crIndexInScope @@ -232,8 +253,7 @@ replaceAttr o scope label attrs title pfx label' = either (++ ':':'\0':show i) id label iInSc = fromJust $ M.lookup itemScope $ crIndexInScope cr i = crIndex cr - lvl = length $ filter ((== pfx) . refPfx) scope - customLabel = maybe (prefixNumbering ropt lvl) + customLabel = maybe (prefixNumbering ropt) (mkLabel $ label' <> " attribute numbering") $ M.lookup "numbering" metaAttrMap hasLabel <- M.member label' <$> get referenceData diff --git a/lib/Text/Pandoc/CrossRef/References/Refs.hs b/lib/Text/Pandoc/CrossRef/References/Refs.hs index b7105ba3..ae7bba35 100644 --- a/lib/Text/Pandoc/CrossRef/References/Refs.hs +++ b/lib/Text/Pandoc/CrossRef/References/Refs.hs @@ -85,10 +85,10 @@ replaceRefs opts ils | otherwise = replaceRefsOther opts replaceRefs _ x = return x -getRefPrefix :: Options -> Bool -> Int -> RefRec -> Inlines -> Inlines -getRefPrefix opts capitalize num rr@RefRec{..} cit = +getRefPrefix :: Bool -> Int -> RefRec -> Inlines -> Inlines +getRefPrefix capitalize num rr@RefRec{..} cit = applyRefTemplate reftempl vf capitalize - where Prefix{prefixReferenceTemplate=reftempl} = fromMaybe undefined $ M.lookup refPfx $ prefixes opts + where Prefix{prefixReferenceTemplate=reftempl} = refPfxRec vf "rs" = Just $ MetaInlines $ toList cit vf "n" = Just $ MetaString $ show num vf x = fix defaultVarFunc rr x @@ -99,16 +99,16 @@ replaceRefsLatex opts cits = return . rawInline "tex" $ cref'++"{"++listLabels "" "," "" cits++"}" | otherwise = intercalate' (text ", ") <$> - mapM (replaceRefsLatex' opts) (NE.groupBy citationGroupPred cits) + mapM replaceRefsLatex' (NE.groupBy citationGroupPred cits) where RefDataComplete{rdSuppressPrefix, rdUpperCase} = NE.head cits cref' | rdSuppressPrefix = "\\labelcref" | rdUpperCase = "\\Cref" | otherwise = "\\cref" -replaceRefsLatex' :: Options -> NonEmpty RefDataComplete -> WS Inlines -replaceRefsLatex' opts cits - = return . writePrefix opts cits . rawInline "tex" +replaceRefsLatex' :: NonEmpty RefDataComplete -> WS Inlines +replaceRefsLatex' cits + = return . writePrefix cits . rawInline "tex" $ listLabels "\\ref{" ", " "}" cits listLabels :: String -> String -> String -> NonEmpty RefDataComplete -> String @@ -128,12 +128,12 @@ replaceRefsOther' opts indices = do | nameInLink opts , [Link attr t (y, z)] <- toList x = linkWith attr y z (f $ fromList t) cmap f x = f x - return $ cmap (writePrefix opts indices) (makeIndices opts indices) + return $ cmap (writePrefix indices) (makeIndices opts indices) -writePrefix :: Options -> NonEmpty RefDataComplete -> Inlines -> Inlines -writePrefix opts (RefDataComplete{..}:|rds) +writePrefix :: NonEmpty RefDataComplete -> Inlines -> Inlines +writePrefix (RefDataComplete{..}:|rds) | rdSuppressPrefix = id - | isNothing rdCitPrefix = getRefPrefix opts rdUpperCase (length rds) rdRec + | isNothing rdCitPrefix = getRefPrefix rdUpperCase (length rds) rdRec | otherwise = ((fromJust rdCitPrefix <> space) <>) data RefDataIncomplete = RefDataIncomplete @@ -236,5 +236,5 @@ applyIndexTemplate opts suf rr = vars rr' x = defaultVarFunc varsSc rr' x template = prefixReferenceIndexTemplate $ refPfxRec rr inlines cap ref = MetaInlines $ toList $ - getRefPrefix opts cap 0 ref $ applyIndexTemplate opts mempty ref + getRefPrefix cap 0 ref $ applyIndexTemplate opts mempty ref in applyTemplate template (vars rr) diff --git a/lib/Text/Pandoc/CrossRef/References/Subfigures.hs b/lib/Text/Pandoc/CrossRef/References/Subfigures.hs index e50779b7..20b47bd1 100644 --- a/lib/Text/Pandoc/CrossRef/References/Subfigures.hs +++ b/lib/Text/Pandoc/CrossRef/References/Subfigures.hs @@ -1,143 +1,99 @@ - module Text.Pandoc.CrossRef.References.Subfigures where --- import Text.Pandoc.Definition --- import qualified Text.Pandoc.Builder as B --- import Text.Pandoc.Shared (stringify, hierarchicalize, Element(..)) --- import Control.Monad.State hiding (get, modify) --- import Data.List --- import Data.Maybe --- import Data.Monoid --- import qualified Data.Map as M --- --- import Data.Accessor.Monad.Trans.State --- import Text.Pandoc.CrossRef.References.Types --- import Text.Pandoc.CrossRef.Util.Util --- import Text.Pandoc.CrossRef.Util.Options --- import Text.Pandoc.CrossRef.Util.Prefixes --- import Text.Pandoc.CrossRef.Util.Template --- import Text.Pandoc.CrossRef.Util.CodeBlockCaptions --- import Control.Applicative --- import Data.Default (def) --- import Prelude --- --- replaceBlock opts scope (Div (label,cls,attrs) images) --- | Just pfx <- getRefPrefix opts label --- , Para caption <- last images --- = do --- idxStr <- replaceAttr opts scope (Right label) (lookup "label" attrs) (B.fromList caption) pfx --- let (cont, st) = runState (runReplace scope (mkRR $ replaceSubfigs opts') $ init images) def --- collectedCaptions = B.toList $ --- intercalate' (ccsDelim opts) --- $ map (collectCaps . snd) --- $ sortOn (refIndex . snd) --- $ filter (not . null . refTitle . snd) --- $ M.toList --- $ referenceData_ st --- collectCaps v = --- applyTemplate --- (chapPrefix (chapDelim opts) (refIndex v)) --- (refTitle v) --- (ccsTemplate opts) --- vars = M.fromDistinctAscList --- [ ("ccs", B.fromList collectedCaptions) --- , ("i", idxStr) --- , ("t", B.fromList caption) --- ] --- capt = applyTemplate' vars $ pfxCaptionTemplate opts pfx --- opts' = opts { --- prefixes = case M.lookup ("sub" <> pfx) $ prefixes opts of --- Just sp -> M.insert pfx sp $ prefixes opts --- Nothing -> prefixes opts --- } --- lastRef <- fromJust . M.lookup label <$> get referenceData --- modify referenceData $ \old -> --- M.union --- old --- (M.map (\v -> v{refIndex = refIndex lastRef, refSubfigure = Just $ refIndex v}) --- $ referenceData_ st) --- case outFormat opts of --- f | isLatexFormat f, pfx == "fig" -> --- replaceNoRecurse $ Div nullAttr $ --- [ RawBlock (Format "latex") "\\begin{figure}\n\\centering" ] --- ++ cont ++ --- [ Para [RawInline (Format "latex") "\\caption" --- , Span nullAttr caption] --- , RawBlock (Format "latex") $ mkLaTeXLabel label --- , RawBlock (Format "latex") "\\end{figure}"] --- _ -> replaceNoRecurse $ Div (label, "subfigures":cls, attrs) $ toTable cont capt --- where --- toTable :: [Block] -> B.Inlines -> [Block] --- toTable blks capt --- | subfigGrid opts = [Table [] align widths [] $ map blkToRow blks, mkCaption opts "Image Caption" capt] --- | otherwise = blks ++ [mkCaption opts "Image Caption" capt] --- where --- align | Para ils:_ <- blks = replicate (length $ mapMaybe getWidth ils) AlignCenter --- | otherwise = error "Misformatted subfigures block" --- widths | Para ils:_ <- blks --- = fixZeros $ mapMaybe getWidth ils --- | otherwise = error "Misformatted subfigures block" --- getWidth (Image (_id, _class, as) _ _) --- = Just $ maybe 0 percToDouble $ lookup "width" as --- getWidth _ = Nothing --- fixZeros :: [Double] -> [Double] --- fixZeros ws --- = let nz = length $ filter (== 0) ws --- rzw = (0.99 - sum ws) / fromIntegral nz --- in if nz>0 --- then map (\x -> if x == 0 then rzw else x) ws --- else ws --- percToDouble :: String -> Double --- percToDouble percs --- | '%' <- last percs --- , perc <- read $ init percs --- = perc/100.0 --- | otherwise = error "Only percent allowed in subfigure width!" --- blkToRow :: Block -> [[Block]] --- blkToRow (Para inls) = mapMaybe inlToCell inls --- blkToRow x = [[x]] --- inlToCell :: Inline -> Maybe [Block] --- inlToCell (Image (id', cs, as) txt tgt) = Just [Para [Image (id', cs, setW as) txt tgt]] --- inlToCell _ = Nothing --- setW as = ("width", "100%"):filter ((/="width") . fst) as --- --- replaceSubfigs :: Options -> Scope -> [Inline] -> WS (ReplacedResult [Inline]) --- replaceSubfigs opts scope = (replaceNoRecurse scope . concat =<<) . mapM (replaceSubfig opts) --- --- replaceSubfig :: Options -> Inline -> WS [Inline] --- replaceSubfig opts x@(Image (label,cls,attrs) alt (src, tit)) --- = do --- let label' | "fig:" `isPrefixOf` label = Right label --- | null label = Left "fig" --- | otherwise = Right $ "fig:" ++ label --- let ialt = B.fromList alt --- idxStr <- replaceAttr opts scope label' (lookup "label" attrs) ialt "fig" --- case outFormat opts of --- f | isLatexFormat f -> --- return $ latexSubFigure x label --- _ -> --- let alt' = B.toList $ applyTemplate idxStr ialt $ pfxCaptionTemplate opts "fig" --- tit' | "nocaption" `elem` cls = fromMaybe tit $ stripPrefix "fig:" tit --- | "fig:" `isPrefixOf` tit = tit --- | otherwise = "fig:" ++ tit --- in return [Image (label, cls, attrs) alt' (src, tit')] --- replaceSubfig _ x = return [x] --- latexSubFigure :: Inline -> String -> [Inline] --- latexSubFigure (Image (_, cls, attrs) alt (src, title)) label = --- let --- title' = fromMaybe title $ stripPrefix "fig:" title --- texlabel | null label = [] --- | otherwise = [RawInline (Format "latex") $ mkLaTeXLabel label] --- texalt | "nocaption" `elem` cls = [] --- | otherwise = concat --- [ [ RawInline (Format "latex") "["] --- , alt --- , [ RawInline (Format "latex") "]"] --- ] --- img = Image (label, cls, attrs) alt (src, title') --- in concat [ --- [ RawInline (Format "latex") "\\subfloat" ] --- , texalt --- , [Span nullAttr $ img:texlabel] --- ] --- latexSubFigure x _ = [x] +import Text.Pandoc.Definition +import Text.Pandoc.Walk +import Data.List +import Data.Maybe +import Data.Monoid + +import Text.Pandoc.CrossRef.Util.Util +import Text.Pandoc.CrossRef.Util.Options +import Text.Pandoc.CrossRef.Util.Prefixes +import Prelude + +makeSubfigures :: Options -> Block -> Block +makeSubfigures opts (Div (label,cls,attrs) contents) + | Just pfx <- getRefPrefix opts label + , Right pfxRec <- getPfx opts pfx + , prefixSubcaptions pfxRec + = Div (label, "subcaption":cls, attrs) + $ if prefixSubcaptionsGrid pfxRec + then toTable (init cont) ++ [last cont] + else cont + where cont = walk figImageParas contents -- modified contents + figImageParas (Para cs) + | all isImageOrSpace cs + = Para $ map addFigureAttr cs + figImageParas (Plain cs) + | all isImageOrSpace cs + = Plain $ map addFigureAttr cs + figImageParas x = x + isImageOrSpace Image{} = True + isImageOrSpace x = isSpace x + addFigureAttr (Image attr alt (src, tit)) + | not $ "fig:" `isPrefixOf` tit + = Image attr alt (src, "fig:" <> tit) + addFigureAttr x = x +makeSubfigures _ x = x + +toTable :: [Block] -> [Block] +toTable blks = [Table [] align widths [] $ map blkToRow blks] + where + align | Para ils:_ <- blks = replicate (length $ mapMaybe getWidth ils) AlignCenter + | otherwise = error "Misformatted subfigures block" + widths | Para ils:_ <- blks + = fixZeros $ mapMaybe getWidth ils + | otherwise = error "Misformatted subfigures block" + getWidth (Image (_id, _class, as) _ _) + = Just $ maybe 0 percToDouble $ lookup "width" as + getWidth _ = Nothing + fixZeros :: [Double] -> [Double] + fixZeros ws + = let nz = length $ filter (== 0) ws + rzw = (0.99 - sum ws) / fromIntegral nz + in if nz>0 + then map (\x -> if x == 0 then rzw else x) ws + else ws + percToDouble :: String -> Double + percToDouble percs + | '%' <- last percs + , perc <- read $ init percs + = perc/100.0 + | otherwise = error "Only percent allowed in subfigure width!" + blkToRow :: Block -> [[Block]] + blkToRow (Para inls) = mapMaybe inlToCell inls + blkToRow x = [[x]] + inlToCell :: Inline -> Maybe [Block] + inlToCell (Image (id', cs, as) txt tgt) = Just [Para [Image (id', cs, setW as) txt tgt]] + inlToCell _ = Nothing + setW as = ("width", "100%"):filter ((/="width") . fst) as + +latexSubFigure :: Inline -> String -> [Inline] +latexSubFigure (Image (_, cls, attrs) alt (src, title)) label = + let + title' = fromMaybe title $ stripPrefix "fig:" title + texlabel | null label = [] + | otherwise = [RawInline (Format "latex") $ mkLaTeXLabel label] + texalt | "nocaption" `elem` cls = [] + | otherwise = concat + [ [ RawInline (Format "latex") "["] + , alt + , [ RawInline (Format "latex") "]"] + ] + img = Image (label, cls, attrs) alt (src, title') + in concat [ + [ RawInline (Format "latex") "\\subfloat" ] + , texalt + , [Span nullAttr $ img:texlabel] + ] +latexSubFigure x _ = [x] + +latexEnv :: String -> [Block] -> [Inline] -> String -> Block +latexEnv env contents caption label = + Div (label, [], []) $ + [ RawBlock (Format "latex") $ "\\begin{"<>env<>"}\n\\centering" ] + ++ contents ++ + [ Para [RawInline (Format "latex") "\\caption" + , Span nullAttr caption] + , RawBlock (Format "latex") $ mkLaTeXLabel label + , RawBlock (Format "latex") $ "\\end{"<>env<>"}"] diff --git a/lib/Text/Pandoc/CrossRef/Util/Meta.hs b/lib/Text/Pandoc/CrossRef/Util/Meta.hs index aaaa36bc..33d64f7d 100644 --- a/lib/Text/Pandoc/CrossRef/Util/Meta.hs +++ b/lib/Text/Pandoc/CrossRef/Util/Meta.hs @@ -65,7 +65,7 @@ getMetaString :: String -> Settings -> String getMetaString = getScalar toString getMetaStringMaybe :: String -> Settings -> Maybe String -getMetaStringMaybe = getScalar toMaybeString +getMetaStringMaybe = getScalar (const toMaybeString) getScalar :: Def b => (String -> MetaValue -> b) -> String -> Settings -> b getScalar conv name (Settings meta) = maybe def' (conv name) $ lookupMeta name meta @@ -112,13 +112,13 @@ toBlocks _ (MetaString s) = plain $ text s toBlocks n x = unexpectedError "blocks" n x toString :: String -> MetaValue -> String -toString n x = fromMaybe (unexpectedError "string" n x) $ toMaybeString n x +toString n x = fromMaybe (unexpectedError "string" n x) $ toMaybeString x -toMaybeString :: String -> MetaValue -> Maybe String -toMaybeString _ (MetaString s) = Just s -toMaybeString _ (MetaBlocks b) = Just $ stringify b -toMaybeString _ (MetaInlines i) = Just $ stringify i -toMaybeString _ _ = Nothing +toMaybeString :: MetaValue -> Maybe String +toMaybeString (MetaString s) = Just s +toMaybeString (MetaBlocks b) = Just $ stringify b +toMaybeString (MetaInlines i) = Just $ stringify i +toMaybeString _ = Nothing getList :: Int -> MetaValue -> Maybe MetaValue getList i (MetaList l) = l !!? i diff --git a/lib/Text/Pandoc/CrossRef/Util/Options/Types.hs b/lib/Text/Pandoc/CrossRef/Util/Options/Types.hs index 5a678edb..a1e91da5 100644 --- a/lib/Text/Pandoc/CrossRef/Util/Options/Types.hs +++ b/lib/Text/Pandoc/CrossRef/Util/Options/Types.hs @@ -33,7 +33,8 @@ data Options = Options { cref :: Bool , refDelim :: Inlines , outFormat :: Maybe Format , tableEqns :: Bool - , autoEqnLabels :: Bool + , autoEqnLabels :: Maybe String + , autoFigLabels :: Maybe String , linkReferences :: Bool , nameInLink :: Bool , prefixes :: Prefixes diff --git a/lib/Text/Pandoc/CrossRef/Util/Prefixes.hs b/lib/Text/Pandoc/CrossRef/Util/Prefixes.hs index 397b5efe..1c52eca8 100644 --- a/lib/Text/Pandoc/CrossRef/Util/Prefixes.hs +++ b/lib/Text/Pandoc/CrossRef/Util/Prefixes.hs @@ -44,12 +44,15 @@ getPrefixes varN dtv , prefixListItemTemplate = mkT $ getTemplInline "listItemTemplate" , prefixListOfTitle = mkT $ getTemplBlock "listOfTitle" , prefixScope = getMetaStringList "scope" kv - , prefixNumbering = \lvl -> + , prefixNumbering = let prettyVarName = varN <> "." <> k <> "." <> varName varName = "numbering" in mkLabel prettyVarName (fromMaybe (reportError prettyVarName "Numbering") - $ lookupSettings varName kv >>= getList lvl) + $ lookupSettings varName kv) + , prefixSubcaptions = getMetaBool "subcaptions" kv + , prefixSubcaptionsGrid = getMetaBool "subcaptionsGrid" kv + , prefixSub = m2p k . (`merge` MetaMap kv') <$> lookupSettings "sub" (Settings (Meta kv') <> from) } where kv = Settings (Meta kv') <> from <> dtv from | Just fromRef <- M.lookup "from" kv' diff --git a/lib/Text/Pandoc/CrossRef/Util/Prefixes/Types.hs b/lib/Text/Pandoc/CrossRef/Util/Prefixes/Types.hs index e44e3fb2..45d8bd1f 100644 --- a/lib/Text/Pandoc/CrossRef/Util/Prefixes/Types.hs +++ b/lib/Text/Pandoc/CrossRef/Util/Prefixes/Types.hs @@ -35,5 +35,8 @@ data Prefix = Prefix { , prefixReferenceTemplate :: !RefTemplate , prefixListOfTitle :: !BlockTemplate , prefixScope :: ![String] - , prefixNumbering :: !(Int -> Int -> String) + , prefixNumbering :: !(Int -> String) + , prefixSubcaptions :: !Bool + , prefixSubcaptionsGrid :: !Bool + , prefixSub :: !(Maybe Prefix) } diff --git a/lib/Text/Pandoc/CrossRef/Util/Settings.hs b/lib/Text/Pandoc/CrossRef/Util/Settings.hs index 1935ed0d..6eb34bc0 100644 --- a/lib/Text/Pandoc/CrossRef/Util/Settings.hs +++ b/lib/Text/Pandoc/CrossRef/Util/Settings.hs @@ -72,13 +72,12 @@ defaultMeta = Settings $ <> refDelim (str "," <> space) <> crossrefYaml "pandoc-crossref.yaml" <> tableEqns False - <> autoEqnLabels False <> linkReferences False <> nameInLink False -- these are merely the defaults, can (and will) be overridden in prefix configs <> captionTemplate (var "title%\160" <> var "i" <> var "titleDelim" <> var "t") <> captionIndexTemplate (var "i") - <> referenceTemplate (var "Ref[n][lvl]%\160" <> var "rs") + <> referenceTemplate (var "Ref[n]%\160" <> var "rs") <> referenceIndexTemplate (var "i" <> var "suf") <> numbering "arabic" <> listOfTitle (header 1 $ text "List of " <> var "title" <> str "s") diff --git a/lib/Text/Pandoc/CrossRef/Util/Settings/Template.hs b/lib/Text/Pandoc/CrossRef/Util/Settings/Template.hs index 98e1bdda..611fc639 100644 --- a/lib/Text/Pandoc/CrossRef/Util/Settings/Template.hs +++ b/lib/Text/Pandoc/CrossRef/Util/Settings/Template.hs @@ -79,6 +79,8 @@ makeCon' t accName = do tmplT <- [t|$(conT t) -> Template|] clT <- [t|$(conT t) -> String -> Int -> Maybe String|] pfxT <- [t|$(conT t) -> Prefixes|] + strT <- [t|$(conT t) -> String|] + mstT <- [t|$(conT t) -> Maybe String|] let varName | Name (OccName n) _ <- accName = liftString n let dtv = return $ VarE $ mkName "dtv" body <- @@ -92,5 +94,7 @@ makeCon' t accName = do | t' == clT -> [|customLabel $(dtv)|] | t' == fmtT -> return $ VarE $ mkName "fmt" | t' == pfxT -> [|getPrefixes $(varName) $(dtv)|] + | t' == strT -> [|getMetaString $(varName) $(dtv)|] + | t' == mstT -> [|getMetaStringMaybe $(varName) $(dtv)|] | otherwise -> fail $ show t' return [(accName, body)] diff --git a/test/m2m/equations-auto/input.md b/test/m2m/equations-auto/input.md index dc9cd6e9..302c77ce 100644 --- a/test/m2m/equations-auto/input.md +++ b/test/m2m/equations-auto/input.md @@ -1,5 +1,5 @@ --- -autoEqnLabels: true +autoEqnLabels: eq ... This is a test file with some referenced equations, line $$ this $$ diff --git a/test/m2m/equations-tables-auto/input.md b/test/m2m/equations-tables-auto/input.md index 311526d7..f5b9e048 100644 --- a/test/m2m/equations-tables-auto/input.md +++ b/test/m2m/equations-tables-auto/input.md @@ -1,6 +1,6 @@ --- tableEqns: true -autoEqnLabels: true +autoEqnLabels: eq ... This is a test file with some referenced equations, line $$ this $$ diff --git a/test/m2m/scoping/input.md b/test/m2m/scoping/input.md index d296edcb..38e4d1fd 100644 --- a/test/m2m/scoping/input.md +++ b/test/m2m/scoping/input.md @@ -10,19 +10,19 @@ prefixes: scope: "dfn" referenceIndexTemplate: "$$i$$$$s.ref# (%)$$" sec: - captionTemplate: '$$titleName[lvl]% $$$$i$$$$titleDelim$$ $$t$$' + captionTemplate: '$$title% $$$$i$$$$titleDelim$$ $$t$$' captionIndexTemplate: '$$s.i%.$$$$i$$' referenceIndexTemplate: '$$i$$$$s.ref# (%)$$' scope: sec - titleName: - - Chapter - - Section - - Paragraph - ref: - - ["chp.", "sec.", "par."] - - ["chps.", "secs.", "pars."] - title: Section titleDelim: '.' + title: Chapter + ref: ["chp.", "chps."] + sub: + title: Section + ref: ["sec.", "secs."] + sub: + title: Paragraph + ref: ["par.", "pars."] chapters: false ... From 39ead544007cf04e98e712dfaf497ff63b99ce96 Mon Sep 17 00:00:00 2001 From: Nikolay Yakimov Date: Sun, 3 Mar 2019 21:51:02 +0300 Subject: [PATCH 060/134] Subfugures: collect captions This is somewhat limited, since it only shows captions collected above the place where it's inserted. Only collects items which are immediate children of the current scope. Currently a placeholder for collected captions is empty span `[]{}`. Might be changed in the future. --- lib/Text/Pandoc/CrossRef/References/Blocks.hs | 11 +++- .../Pandoc/CrossRef/References/Types/Ref.hs | 2 +- lib/Text/Pandoc/CrossRef/Util/Prefixes.hs | 2 + .../Pandoc/CrossRef/Util/Prefixes/Types.hs | 3 ++ lib/Text/Pandoc/CrossRef/Util/Settings.hs | 7 ++- lib/Text/Pandoc/CrossRef/Util/Settings/Gen.hs | 3 ++ pandoc-crossref.cabal | 5 +- test/m2m/subfigures-ccsDelim/expect.md | 12 ++--- test/m2m/subfigures-ccsDelim/input.md | 17 ++++-- test/m2m/subfigures-grid/expect.md | 12 ++--- test/m2m/subfigures-grid/input.md | 17 ++++-- .../m2m/subfigures-template-collect/expect.md | 41 ++++++++++++++ .../subfigures-template-collect/expect.tex | 53 ++++++++++++++++++ test/m2m/subfigures-template-collect/input.md | 54 +++++++++++++++++++ test/m2m/subfigures/expect.md | 12 ++--- test/m2m/subfigures/input.md | 17 +++++- 16 files changed, 234 insertions(+), 34 deletions(-) create mode 100644 test/m2m/subfigures-template-collect/expect.md create mode 100644 test/m2m/subfigures-template-collect/expect.tex create mode 100644 test/m2m/subfigures-template-collect/input.md diff --git a/lib/Text/Pandoc/CrossRef/References/Blocks.hs b/lib/Text/Pandoc/CrossRef/References/Blocks.hs index 5848cfd0..323b15ef 100644 --- a/lib/Text/Pandoc/CrossRef/References/Blocks.hs +++ b/lib/Text/Pandoc/CrossRef/References/Blocks.hs @@ -176,11 +176,18 @@ replaceInline opts scope (Image attr@(label,_,attrs) alt img@(_, tit)) f | isLatexFormat f -> ialt _ -> applyTitleTemplate idxStr replaceNoRecurse $ Image attr alt' img -replaceInline opts scope x@(Span (label,_,attrs) content) +replaceInline opts scope (Span (label,_,attrs) content) | Just pfx <- getRefPrefix opts label = do rec' <- replaceAttr opts scope (Right label) attrs (B.fromList content) pfx - replaceRecurse (newScope rec' scope) x + noReplaceRecurse (newScope rec' scope) +replaceInline _opts (scope@RefRec{refPfxRec=Prefix{..}}:_) (Span ("",_,_) []) = do + rd <- get referenceData + let ccd = filter ((== Just scope) . refScope) . M.elems $ rd + replaceNoRecurse . Span nullAttr . B.toList . mconcat + . intersperse prefixCollectedCaptionDelim + . map (applyTemplate prefixCollectedCaptionTemplate . fix defaultVarFunc) + $ sort ccd replaceInline _ scope _ = noReplaceRecurse scope applyTitleTemplate :: RefRec -> B.Inlines diff --git a/lib/Text/Pandoc/CrossRef/References/Types/Ref.hs b/lib/Text/Pandoc/CrossRef/References/Types/Ref.hs index b449434d..e02dc683 100644 --- a/lib/Text/Pandoc/CrossRef/References/Types/Ref.hs +++ b/lib/Text/Pandoc/CrossRef/References/Types/Ref.hs @@ -32,7 +32,7 @@ import Text.Pandoc.CrossRef.Util.Prefixes.Types data RefRec = RefRec { refIndex :: !Int -- global ordinal number for prefix , refIxInl :: Inlines -- index as inilnes , refTitle :: !Inlines -- title text - , refScope :: !(Maybe RefRec) -- reference to parent label + , refScope :: !(Maybe RefRec) -- reference to parent scope label (as specified in scopes array) , refLevel :: !Int -- number of upper scopes of the same prefix , refLabel :: !String -- label, i.e. pfx:label string , refPfx :: !String -- reference prefix, the part in label before : diff --git a/lib/Text/Pandoc/CrossRef/Util/Prefixes.hs b/lib/Text/Pandoc/CrossRef/Util/Prefixes.hs index 1c52eca8..42ca2e99 100644 --- a/lib/Text/Pandoc/CrossRef/Util/Prefixes.hs +++ b/lib/Text/Pandoc/CrossRef/Util/Prefixes.hs @@ -42,7 +42,9 @@ getPrefixes varN dtv , prefixReferenceIndexTemplate = mkT $ getTemplInline "referenceIndexTemplate" , prefixCaptionIndexTemplate = mkT $ getTemplInline "captionIndexTemplate" , prefixListItemTemplate = mkT $ getTemplInline "listItemTemplate" + , prefixCollectedCaptionTemplate = mkT $ getTemplInline "collectedCaptionTemplate" , prefixListOfTitle = mkT $ getTemplBlock "listOfTitle" + , prefixCollectedCaptionDelim = getMetaInlines "collectedCaptionDelim" kv , prefixScope = getMetaStringList "scope" kv , prefixNumbering = let prettyVarName = varN <> "." <> k <> "." <> varName diff --git a/lib/Text/Pandoc/CrossRef/Util/Prefixes/Types.hs b/lib/Text/Pandoc/CrossRef/Util/Prefixes/Types.hs index 45d8bd1f..a78fa19e 100644 --- a/lib/Text/Pandoc/CrossRef/Util/Prefixes/Types.hs +++ b/lib/Text/Pandoc/CrossRef/Util/Prefixes/Types.hs @@ -24,6 +24,7 @@ module Text.Pandoc.CrossRef.Util.Prefixes.Types where import qualified Data.Map as M import Text.Pandoc.CrossRef.Util.Template.Types +import Text.Pandoc.Builder type Prefixes = M.Map String Prefix @@ -32,8 +33,10 @@ data Prefix = Prefix { , prefixReferenceIndexTemplate :: !Template , prefixCaptionIndexTemplate :: !Template , prefixListItemTemplate :: !Template + , prefixCollectedCaptionTemplate :: !Template , prefixReferenceTemplate :: !RefTemplate , prefixListOfTitle :: !BlockTemplate + , prefixCollectedCaptionDelim :: !Inlines , prefixScope :: ![String] , prefixNumbering :: !(Int -> String) , prefixSubcaptions :: !Bool diff --git a/lib/Text/Pandoc/CrossRef/Util/Settings.hs b/lib/Text/Pandoc/CrossRef/Util/Settings.hs index 6eb34bc0..2a8d09d8 100644 --- a/lib/Text/Pandoc/CrossRef/Util/Settings.hs +++ b/lib/Text/Pandoc/CrossRef/Util/Settings.hs @@ -74,14 +74,17 @@ defaultMeta = Settings $ <> tableEqns False <> linkReferences False <> nameInLink False + <> collectedCaptionDelim (str "," <> space) + <> collectedCaptionItemDelim (space <> str "–" <> space) -- these are merely the defaults, can (and will) be overridden in prefix configs <> captionTemplate (var "title%\160" <> var "i" <> var "titleDelim" <> var "t") <> captionIndexTemplate (var "i") <> referenceTemplate (var "Ref[n]%\160" <> var "rs") + <> listItemTemplate (var "i" <> var "listItemNumberDelim" <> var "t") + <> collectedCaptionTemplate (var "i" <> var "collectedCaptionItemDelim" <> var "t") <> referenceIndexTemplate (var "i" <> var "suf") - <> numbering "arabic" <> listOfTitle (header 1 $ text "List of " <> var "title" <> str "s") - <> listItemTemplate (var "i" <> var "listItemNumberDelim" <> var "t") + <> numbering "arabic" <> prefixes' [ "eq" .: [ "ref" .= map str ["eq.", "eqns."], diff --git a/lib/Text/Pandoc/CrossRef/Util/Settings/Gen.hs b/lib/Text/Pandoc/CrossRef/Util/Settings/Gen.hs index ad716bf5..38bfe6c5 100644 --- a/lib/Text/Pandoc/CrossRef/Util/Settings/Gen.hs +++ b/lib/Text/Pandoc/CrossRef/Util/Settings/Gen.hs @@ -41,6 +41,9 @@ fmap concat $ mapM (makeAcc . mkName) , "listItemTemplate" , "numbering" , "listOfTitle" + , "collectedCaptionDelim" + , "collectedCaptionItemDelim" + , "collectedCaptionTemplate" ] getOptions :: Settings -> Maybe Format -> Options diff --git a/pandoc-crossref.cabal b/pandoc-crossref.cabal index 92b514a4..b8b1f317 100644 --- a/pandoc-crossref.cabal +++ b/pandoc-crossref.cabal @@ -4,7 +4,7 @@ cabal-version: 1.12 -- -- see: https://github.com/sol/hpack -- --- hash: a2145f6739c0ed44aff150fb432e29dab9abf1086b31606d5abb876004ac2b54 +-- hash: 58a889350b438385af3c27afd80affc9efabf78bef71cfb716d4456a5650b098 name: pandoc-crossref version: 0.4.0.0 @@ -76,6 +76,9 @@ data-files: test/m2m/subfigures-grid/expect.md test/m2m/subfigures-grid/expect.tex test/m2m/subfigures-grid/input.md + test/m2m/subfigures-template-collect/expect.md + test/m2m/subfigures-template-collect/expect.tex + test/m2m/subfigures-template-collect/input.md test/m2m/subfigures/expect.md test/m2m/subfigures/expect.tex test/m2m/subfigures/input.md diff --git a/test/m2m/subfigures-ccsDelim/expect.md b/test/m2m/subfigures-ccsDelim/expect.md index f30cef33..7f55459f 100644 --- a/test/m2m/subfigures-ccsDelim/expect.md +++ b/test/m2m/subfigures-ccsDelim/expect.md @@ -1,6 +1,6 @@ You can define subfigures: -::: {#fig:subfigures .subfigures} +::: {#fig:subfigures .subcaption} ![a](fig1.png "fig:"){#fig:subfig1} ![b](fig2.png "fig:"){#fig:subfig2} ![c](fig3.png "fig:") @@ -10,11 +10,11 @@ You can define subfigures: ![g](fig7.png "fig:"){#fig:subfig7} ![h](fig8.png "fig:") ![i](fig9.png "fig:"){#fig:subfig9} -Figure 1: Caption. a --- 1; b --- 2; c --- 3; d --- 4; e --- 5; f --- -6; g --- 7; h --- 8; i --- 9 +Figure 1: Caption. a -- 1; b -- 2; c -- 3; d -- 4; e -- 5; f -- 6; g -- +7; h -- 8; i -- 9 ::: -::: {#fig:subfigures2 .subfigures} +::: {#fig:subfigures2 .subcaption} ![a](fig1.png){#fig:subfig21} ![b](fig2.png){#fig:subfig22} @@ -33,8 +33,8 @@ Figure 1: Caption. a --- 1; b --- 2; c --- 3; d --- 4; e --- 5; f --- ![i](fig9.png){#fig:subfig29} -Figure 2: Caption. a --- 1; b --- 2; c --- 3; d --- 4; e --- 5; f --- -6; g --- 7; h --- 8; i --- 9 +Figure 2: Caption. a -- 1; b -- 2; c -- 3; d -- 4; e -- 5; f -- 6; g -- +7; h -- 8; i -- 9 ::: Figures themselves can be referenced fig. 2, as well as individual diff --git a/test/m2m/subfigures-ccsDelim/input.md b/test/m2m/subfigures-ccsDelim/input.md index c57c276f..2fb0a9a3 100644 --- a/test/m2m/subfigures-ccsDelim/input.md +++ b/test/m2m/subfigures-ccsDelim/input.md @@ -1,6 +1,15 @@ --- -ccsDelim: "; " -... +autoFigLabels: fig +prefixes: + fig: + subcaptions: true + collectedCaptionDelim: "; " + sub: + numbering: alpha a + referenceIndexTemplate: $$s.i$$ ($$i$$) + captionTemplate: $$i$$ + scope: "fig" +--- You can define subfigures: @@ -17,7 +26,7 @@ You can define subfigures: ![8](fig8.png) ![9](fig9.png){#fig:subfig9} - Caption + : Caption. []{}
@@ -39,7 +48,7 @@ You can define subfigures: ![9](fig9.png){#fig:subfig29} - Caption + \: Caption. []{}
Figures themselves can be referenced @fig:subfigures2, as well as individual subfigures: [@fig:subfig1; @fig:subfig2; @fig:subfig29] diff --git a/test/m2m/subfigures-grid/expect.md b/test/m2m/subfigures-grid/expect.md index 2af6e76e..0b1b780d 100644 --- a/test/m2m/subfigures-grid/expect.md +++ b/test/m2m/subfigures-grid/expect.md @@ -1,6 +1,6 @@ You can define subfigures: -::: {#fig:subfigures .subfigures} +::: {#fig:subfigures .subcaption} +:------------------:+:------------------:+:------------------:+ | ![a](fig1.png){#fi | ![b](fig2.png){#fi | ![c](fig3.png){wid | | g:subfig1 | g:subfig2 | th="100%"} | @@ -15,11 +15,11 @@ You can define subfigures: | width="100%"} | | width="100%"} | +--------------------+--------------------+--------------------+ -Figure 1: Caption. a --- 1, b --- 2, c --- 3, d --- 4, e --- 5, f --- 6, -g --- 7, h --- 8, i --- 9 +Figure 1: Caption. a -- 1, b -- 2, c -- 3, d -- 4, e -- 5, f -- 6, g -- +7, h -- 8, i -- 9 ::: -::: {#fig:subfigures2 .subfigures} +::: {#fig:subfigures2 .subcaption} +:--------------------------------------------------------------------:+ | ![a](fig1.png){#fig:subfig21 width="100%"} | +----------------------------------------------------------------------+ @@ -40,8 +40,8 @@ g --- 7, h --- 8, i --- 9 | ![i](fig9.png){#fig:subfig29 width="100%"} | +----------------------------------------------------------------------+ -Figure 2: Caption. a --- 1, b --- 2, c --- 3, d --- 4, e --- 5, f --- 6, -g --- 7, h --- 8, i --- 9 +Figure 2: Caption. a -- 1, b -- 2, c -- 3, d -- 4, e -- 5, f -- 6, g -- +7, h -- 8, i -- 9 ::: Figures themselves can be referenced fig. 2, as well as individual diff --git a/test/m2m/subfigures-grid/input.md b/test/m2m/subfigures-grid/input.md index 09bc9939..21bf5ce1 100644 --- a/test/m2m/subfigures-grid/input.md +++ b/test/m2m/subfigures-grid/input.md @@ -1,6 +1,15 @@ --- -subfigGrid: true -... +autoFigLabels: fig +prefixes: + fig: + subcaptions: true + subcaptionsGrid: true + sub: + numbering: alpha a + referenceIndexTemplate: $$s.i$$ ($$i$$) + captionTemplate: $$i$$ + scope: "fig" +--- You can define subfigures: @@ -17,7 +26,7 @@ You can define subfigures: ![8](fig8.png){width=30%} ![9](fig9.png){#fig:subfig9 width=30%} - Caption + : Caption. []{}
@@ -39,7 +48,7 @@ You can define subfigures: ![9](fig9.png){#fig:subfig29} - Caption + \: Caption. []{}
Figures themselves can be referenced @fig:subfigures2, as well as individual subfigures: [@fig:subfig1; @fig:subfig2; @fig:subfig29] diff --git a/test/m2m/subfigures-template-collect/expect.md b/test/m2m/subfigures-template-collect/expect.md new file mode 100644 index 00000000..3ba67c6e --- /dev/null +++ b/test/m2m/subfigures-template-collect/expect.md @@ -0,0 +1,41 @@ +You can define subfigures: + +::: {#fig:subfigures .subcaption} +![a](fig1.png "fig:"){#fig:subfig1} ![b](fig2.png "fig:"){#fig:subfig2} +![c](fig3.png "fig:") + +![d](fig4.png "fig:"){#fig:subfig4} ![e](fig5.png "fig:") +![f](fig6.png "fig:"){#fig:subfig6} + +![g](fig7.png "fig:"){#fig:subfig7} ![h](fig8.png "fig:") +![i](fig9.png "fig:"){#fig:subfig9} + +Figure 1: Caption. a -- 1, b -- 2, c -- 3, d -- 4, e -- 5, f -- 6, g -- +7, h -- 8, i -- 9 +::: + +::: {#fig:subfigures2 .subcaption} +![a](fig1.png){#fig:subfig21} + +![b](fig2.png){#fig:subfig22} + +![c](fig3.png) + +![d](fig4.png){#fig:subfig24} + +![e](fig5.png) + +![f](fig6.png){#fig:subfig26} + +![g](fig7.png){#fig:subfig27} + +![h](fig8.png) + +![i](fig9.png){#fig:subfig29} + +Figure 2: Caption. a -- 1, b -- 2, c -- 3, d -- 4, e -- 5, f -- 6, g -- +7, h -- 8, i -- 9 +::: + +Figures themselves can be referenced fig. 2, as well as individual +subfigures: figs. 1 (a), 1 (b), 2 (i) diff --git a/test/m2m/subfigures-template-collect/expect.tex b/test/m2m/subfigures-template-collect/expect.tex new file mode 100644 index 00000000..97fcf563 --- /dev/null +++ b/test/m2m/subfigures-template-collect/expect.tex @@ -0,0 +1,53 @@ +You can define subfigures: + +\begin{figure} +\centering + +\subfloat[1]{\includegraphics{fig1.png}\label{fig:subfig1}} +\subfloat[2]{\includegraphics{fig2.png}\label{fig:subfig2}} +\subfloat[3]{\includegraphics{fig3.png}} + +\subfloat[4]{\includegraphics{fig4.png}\label{fig:subfig4}} +\subfloat[5]{\includegraphics{fig5.png}} +\subfloat[6]{\includegraphics{fig6.png}\label{fig:subfig6}} + +\subfloat[7]{\includegraphics{fig7.png}\label{fig:subfig7}} +\subfloat[8]{\includegraphics{fig8.png}} +\subfloat[9]{\includegraphics{fig9.png}\label{fig:subfig9}} + +\caption{Caption} + +\label{fig:subfigures} + +\end{figure} + +\begin{figure} +\centering + +\subfloat[1]{\includegraphics{fig1.png}\label{fig:subfig21}} + +\subfloat[2]{\includegraphics{fig2.png}\label{fig:subfig22}} + +\subfloat[3]{\includegraphics{fig3.png}} + +\subfloat[4]{\includegraphics{fig4.png}\label{fig:subfig24}} + +\subfloat[5]{\includegraphics{fig5.png}} + +\subfloat[6]{\includegraphics{fig6.png}\label{fig:subfig26}} + +\subfloat[7]{\includegraphics{fig7.png}\label{fig:subfig27}} + +\subfloat[8]{\includegraphics{fig8.png}} + +\subfloat[9]{\includegraphics{fig9.png}\label{fig:subfig29}} + +\caption{Caption} + +\label{fig:subfigures2} + +\end{figure} + +Figures themselves can be referenced fig.~\ref{fig:subfigures2}, as well +as individual subfigures: +figs.~\ref{fig:subfig1}, \ref{fig:subfig2}, \ref{fig:subfig29} diff --git a/test/m2m/subfigures-template-collect/input.md b/test/m2m/subfigures-template-collect/input.md new file mode 100644 index 00000000..28cbbc9f --- /dev/null +++ b/test/m2m/subfigures-template-collect/input.md @@ -0,0 +1,54 @@ +--- +autoFigLabels: fig +prefixes: + fig: + subcaptions: true + captionTemplate: '$$title% $$$$i$$$$titleDelim$$$$t$$. []{}' + sub: + numbering: alpha a + referenceIndexTemplate: $$s.i$$ ($$i$$) + captionTemplate: $$i$$ + scope: "fig" +--- + +You can define subfigures: + +
+ ![1](fig1.png){#fig:subfig1} + ![2](fig2.png){#fig:subfig2} + ![3](fig3.png) + + ![4](fig4.png){#fig:subfig4} + ![5](fig5.png) + ![6](fig6.png){#fig:subfig6} + + ![7](fig7.png){#fig:subfig7} + ![8](fig8.png) + ![9](fig9.png){#fig:subfig9} + + : Caption +
+ +
+ ![1](fig1.png){#fig:subfig21} + + ![2](fig2.png){#fig:subfig22} + + ![3](fig3.png) + + ![4](fig4.png){#fig:subfig24} + + ![5](fig5.png) + + ![6](fig6.png){#fig:subfig26} + + ![7](fig7.png){#fig:subfig27} + + ![8](fig8.png) + + ![9](fig9.png){#fig:subfig29} + + \: Caption +
+ +Figures themselves can be referenced @fig:subfigures2, as well as individual subfigures: [@fig:subfig1; @fig:subfig2; @fig:subfig29] diff --git a/test/m2m/subfigures/expect.md b/test/m2m/subfigures/expect.md index 70b86f41..3ba67c6e 100644 --- a/test/m2m/subfigures/expect.md +++ b/test/m2m/subfigures/expect.md @@ -1,6 +1,6 @@ You can define subfigures: -::: {#fig:subfigures .subfigures} +::: {#fig:subfigures .subcaption} ![a](fig1.png "fig:"){#fig:subfig1} ![b](fig2.png "fig:"){#fig:subfig2} ![c](fig3.png "fig:") @@ -10,11 +10,11 @@ You can define subfigures: ![g](fig7.png "fig:"){#fig:subfig7} ![h](fig8.png "fig:") ![i](fig9.png "fig:"){#fig:subfig9} -Figure 1: Caption. a --- 1, b --- 2, c --- 3, d --- 4, e --- 5, f --- 6, -g --- 7, h --- 8, i --- 9 +Figure 1: Caption. a -- 1, b -- 2, c -- 3, d -- 4, e -- 5, f -- 6, g -- +7, h -- 8, i -- 9 ::: -::: {#fig:subfigures2 .subfigures} +::: {#fig:subfigures2 .subcaption} ![a](fig1.png){#fig:subfig21} ![b](fig2.png){#fig:subfig22} @@ -33,8 +33,8 @@ g --- 7, h --- 8, i --- 9 ![i](fig9.png){#fig:subfig29} -Figure 2: Caption. a --- 1, b --- 2, c --- 3, d --- 4, e --- 5, f --- 6, -g --- 7, h --- 8, i --- 9 +Figure 2: Caption. a -- 1, b -- 2, c -- 3, d -- 4, e -- 5, f -- 6, g -- +7, h -- 8, i -- 9 ::: Figures themselves can be referenced fig. 2, as well as individual diff --git a/test/m2m/subfigures/input.md b/test/m2m/subfigures/input.md index 5b59461d..7e35fb3f 100644 --- a/test/m2m/subfigures/input.md +++ b/test/m2m/subfigures/input.md @@ -1,3 +1,16 @@ +--- +autoFigLabels: fig +prefixes: + fig: + subcaptions: true + # subcaptionsGrid: true + sub: + numbering: alpha a + referenceIndexTemplate: $$s.i$$ ($$i$$) + captionTemplate: $$i$$ + scope: "fig" +--- + You can define subfigures:
@@ -13,7 +26,7 @@ You can define subfigures: ![8](fig8.png) ![9](fig9.png){#fig:subfig9} - Caption + : Caption. []{}
@@ -35,7 +48,7 @@ You can define subfigures: ![9](fig9.png){#fig:subfig29} - Caption + \: Caption. []{}
Figures themselves can be referenced @fig:subfigures2, as well as individual subfigures: [@fig:subfig1; @fig:subfig2; @fig:subfig29] From 03f31c8655731fe663efc815d3ba6bc661a42162 Mon Sep 17 00:00:00 2001 From: Nikolay Yakimov Date: Sun, 3 Mar 2019 23:19:05 +0300 Subject: [PATCH 061/134] Update demo.md to work with subfigures --- docs/demo/demo.md | 9 ++++++++- lib/Text/Pandoc/CrossRef/References/Blocks.hs | 16 +++++++++++----- 2 files changed, 19 insertions(+), 6 deletions(-) diff --git a/docs/demo/demo.md b/docs/demo/demo.md index 55d8f1de..a340f7c1 100644 --- a/docs/demo/demo.md +++ b/docs/demo/demo.md @@ -1,11 +1,18 @@ --- codeBlockCaptions: True +autoFigLabels: fig prefixes: fig: title: | Figure # listOfTitle: | ## List of Figures + subcaptions: true + sub: + numbering: alpha a + referenceIndexTemplate: $$s.i$$ ($$i$$) + captionTemplate: $$i$$ + scope: "fig" tbl: listOfTitle: | ## List of Tables @@ -48,7 +55,7 @@ Subfigures are supported, see [@fig:subfigures; @fig:subfigureB] ![Subfigure b](img1.jpg){#fig:subfigureB} -Subfigures caption +\: Subfigures caption. []{} # Chapter 2. Equations {#sec:sec2} diff --git a/lib/Text/Pandoc/CrossRef/References/Blocks.hs b/lib/Text/Pandoc/CrossRef/References/Blocks.hs index 323b15ef..b979d53f 100644 --- a/lib/Text/Pandoc/CrossRef/References/Blocks.hs +++ b/lib/Text/Pandoc/CrossRef/References/Blocks.hs @@ -181,13 +181,19 @@ replaceInline opts scope (Span (label,_,attrs) content) = do rec' <- replaceAttr opts scope (Right label) attrs (B.fromList content) pfx noReplaceRecurse (newScope rec' scope) -replaceInline _opts (scope@RefRec{refPfxRec=Prefix{..}}:_) (Span ("",_,_) []) = do +replaceInline _opts (scope@RefRec{refPfxRec=Prefix{..}}:_) (Span ("",_,attrs) []) = do rd <- get referenceData let ccd = filter ((== Just scope) . refScope) . M.elems $ rd - replaceNoRecurse . Span nullAttr . B.toList . mconcat - . intersperse prefixCollectedCaptionDelim - . map (applyTemplate prefixCollectedCaptionTemplate . fix defaultVarFunc) - $ sort ccd + prefix = maybe mempty B.str $ lookup "prefix" attrs + suffix = maybe mempty B.str $ lookup "suffix" attrs + delim = maybe prefixCollectedCaptionDelim B.str $ lookup "delim" attrs + varFunc rr x = fix defaultVarFunc rr x <|> (MetaString <$> lookup x attrs) + replaceNoRecurse . Span nullAttr . B.toList $ + prefix <> ( + mconcat + . intersperse delim + . map (applyTemplate prefixCollectedCaptionTemplate . varFunc) + $ sort ccd) <> suffix replaceInline _ scope _ = noReplaceRecurse scope applyTitleTemplate :: RefRec -> B.Inlines From 7ffd91b920e33fd8e9b1913c9025b35da943b173 Mon Sep 17 00:00:00 2001 From: Nikolay Yakimov Date: Sun, 3 Mar 2019 23:56:57 +0300 Subject: [PATCH 062/134] Add GPL headers to new files --- .../Pandoc/CrossRef/References/Subfigures.hs | 20 +++++++++++++++++++ .../Pandoc/CrossRef/Util/Settings/Types.hs | 20 +++++++++++++++++++ 2 files changed, 40 insertions(+) diff --git a/lib/Text/Pandoc/CrossRef/References/Subfigures.hs b/lib/Text/Pandoc/CrossRef/References/Subfigures.hs index 20b47bd1..4c59ecee 100644 --- a/lib/Text/Pandoc/CrossRef/References/Subfigures.hs +++ b/lib/Text/Pandoc/CrossRef/References/Subfigures.hs @@ -1,3 +1,23 @@ +{- +pandoc-crossref is a pandoc filter for numbering figures, +equations, tables and cross-references to them. +Copyright (C) 2019 Nikolay Yakimov + +This program is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License along +with this program; if not, write to the Free Software Foundation, Inc., +51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +-} + module Text.Pandoc.CrossRef.References.Subfigures where import Text.Pandoc.Definition diff --git a/lib/Text/Pandoc/CrossRef/Util/Settings/Types.hs b/lib/Text/Pandoc/CrossRef/Util/Settings/Types.hs index 28d664ca..2967de3b 100644 --- a/lib/Text/Pandoc/CrossRef/Util/Settings/Types.hs +++ b/lib/Text/Pandoc/CrossRef/Util/Settings/Types.hs @@ -1,3 +1,23 @@ +{- +pandoc-crossref is a pandoc filter for numbering figures, +equations, tables and cross-references to them. +Copyright (C) 2015 Nikolay Yakimov + +This program is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License along +with this program; if not, write to the Free Software Foundation, Inc., +51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +-} + module Text.Pandoc.CrossRef.Util.Settings.Types where import Text.Pandoc.Definition From 7f5f7be5e7d2d815f371af8e461a1ef8fe801960 Mon Sep 17 00:00:00 2001 From: Nikolay Yakimov Date: Fri, 8 Mar 2019 04:07:34 +0300 Subject: [PATCH 063/134] Use applicative parser --- lib/Text/Pandoc/CrossRef/Util/Template.hs | 32 +++++++++-------------- 1 file changed, 13 insertions(+), 19 deletions(-) diff --git a/lib/Text/Pandoc/CrossRef/Util/Template.hs b/lib/Text/Pandoc/CrossRef/Util/Template.hs index fabfe8c7..e3e25b68 100644 --- a/lib/Text/Pandoc/CrossRef/Util/Template.hs +++ b/lib/Text/Pandoc/CrossRef/Util/Template.hs @@ -37,13 +37,13 @@ import Text.Pandoc.Generic import Text.Pandoc.CrossRef.Util.Meta import Text.Pandoc.CrossRef.Util.Settings.Types import Text.Pandoc.CrossRef.Util.Template.Types -import Control.Applicative -import Text.Read +import Control.Applicative hiding (many, optional) +import Text.Read hiding ((<++), (+++)) import Data.Char (isAlphaNum, isUpper, toLower) import Control.Monad ((<=<)) import Data.Data (Data) +import Text.ParserCombinators.ReadP -data State = StFirstVar | StIndex | StAfterIndex | StPrefix | StSuffix deriving Eq data ParseRes = ParseRes { prVar :: String, prIdx :: [String], prPfx :: String, prSfx :: String } deriving Show isVariableSym :: Char -> Bool @@ -51,21 +51,15 @@ isVariableSym '.' = True isVariableSym '_' = True isVariableSym c = isAlphaNum c -parse :: State -> String -> ParseRes -parse _ [] = ParseRes [] [] [] [] -parse StFirstVar cs@(c:_) | isVariableSym c = let (var, rest) = span isVariableSym cs in (parse StFirstVar rest){prVar = var} -parse s ('[':cs) - | s == StAfterIndex || s == StFirstVar - = let (idx, rest) = span isVariableSym cs in (\r -> r{prIdx = idx : prIdx r})(parse StIndex rest) -parse StIndex (']':cs) = parse StAfterIndex cs -parse StIndex _ = error "Unterminated [ in indexed variable" -parse StAfterIndex ('[':cs) = parse StIndex cs -parse _ ('%':cs) = parse StSuffix cs -parse _ ('#':cs) = parse StPrefix cs -parse StFirstVar s = error $ "Invalid variable name in " <> s -parse StAfterIndex (c:_) = error $ "Unexpected character " <> [c] <> " after parsing indexed variable" -parse StPrefix cs = let (pfx, rest) = span (`notElem` "%#") cs in (parse StPrefix rest){prPfx = pfx} -parse StSuffix cs = let (sfx, rest) = span (`notElem` "%#") cs in (parse StSuffix rest){prSfx = sfx} +parse :: ReadP ParseRes +parse = uncurry <$> (ParseRes <$> varName <*> many varIdx) <*> option ("", "") ps <* eof + where + varName = munch1 isVariableSym + varIdx = between (char '[') (char ']') varName + prefix = char '#' *> many (satisfy (/='%')) + suffix = char '%' *> many (satisfy (/='#')) + ps = (flip (,) <$> suffix <*> option "" prefix) + +++ ((,) <$> prefix <*> option "" suffix) instance MakeTemplate Template where type ElemT Template = Inlines @@ -94,7 +88,7 @@ scan :: (Data a) => VarFunc -> [a] -> [a] scan = bottomUp . go where go vf (Math DisplayMath var:xs) - | ParseRes{..} <- parse StFirstVar var + | ParseRes{..} <- fst . head $ readP_to_S parse var = let replaceVar = maybe mempty (modifier . toInlines ("variable " ++ var)) modifier = (<> text prSfx) . (text prPfx <>) in case prIdx of From 44c1b1accd25f55ebfcc296295412efe48b9a8bc Mon Sep 17 00:00:00 2001 From: Nikolay Yakimov Date: Fri, 8 Mar 2019 04:46:02 +0300 Subject: [PATCH 064/134] Tests update for Pandoc 2.7 --- test/m2m/scoping/expect.md | 2 ++ test/m2m/scoping/expect.tex | 7 +++++++ test/m2m/scoping/input.md | 2 ++ 3 files changed, 11 insertions(+) diff --git a/test/m2m/scoping/expect.md b/test/m2m/scoping/expect.md index 9ff19471..ee8d576d 100644 --- a/test/m2m/scoping/expect.md +++ b/test/m2m/scoping/expect.md @@ -36,6 +36,8 @@ Chapter 3. Section 3 {#section-3} - dfn. 1 (sec. 1.1 (chp. 1)) - cl. 1 (dfn. 1 (sec. 1.1 (chp. 1))) +------------------------------------------------------------------------ + - chp. 2 - dfn. 1 (par. 2.1.2 (sec. 2.1 (chp. 2))) - cl. 1 (dfn. 1 (par. 2.1.2 (sec. 2.1 (chp. 2)))) diff --git a/test/m2m/scoping/expect.tex b/test/m2m/scoping/expect.tex index 9f02959e..8319db4b 100644 --- a/test/m2m/scoping/expect.tex +++ b/test/m2m/scoping/expect.tex @@ -42,6 +42,7 @@ \subsubsection{Paragraph 2.1.2. Section 2.1.2}\label{sec:212}} \section{Chapter 3. Section 3}\label{section-3}} \begin{itemize} +\tightlist \item chp.~\ref{sec:1} \item @@ -50,6 +51,12 @@ \section{Chapter 3. Section 3}\label{section-3}} dfn.~\ref{dfn:group} \item cl.~\ref{cl:grpmul} +\end{itemize} + +\begin{center}\rule{0.5\linewidth}{\linethickness}\end{center} + +\begin{itemize} +\tightlist \item chp.~\ref{sec:2} \item diff --git a/test/m2m/scoping/input.md b/test/m2m/scoping/input.md index 38e4d1fd..95baff1c 100644 --- a/test/m2m/scoping/input.md +++ b/test/m2m/scoping/input.md @@ -59,6 +59,8 @@ A _ring_ is a triple $(R,+,*)$ satisfying: - @dfn:group - @cl:grpmul +--- + - @sec:2 - @dfn:ring - @cl:addgp From 3fcf310b1419d6617a3426e9292edf60cae053c1 Mon Sep 17 00:00:00 2001 From: Nikolay Yakimov Date: Fri, 8 Mar 2019 04:46:36 +0300 Subject: [PATCH 065/134] Template variables: options and objects by index --- lib/Text/Pandoc/CrossRef/Util/Meta.hs | 5 ++++ lib/Text/Pandoc/CrossRef/Util/Template.hs | 35 ++++++++++++++++------- 2 files changed, 29 insertions(+), 11 deletions(-) diff --git a/lib/Text/Pandoc/CrossRef/Util/Meta.hs b/lib/Text/Pandoc/CrossRef/Util/Meta.hs index 33d64f7d..17558d6c 100644 --- a/lib/Text/Pandoc/CrossRef/Util/Meta.hs +++ b/lib/Text/Pandoc/CrossRef/Util/Meta.hs @@ -28,6 +28,7 @@ module Text.Pandoc.CrossRef.Util.Meta ( , getMetaStringMaybe , getMetaStringList , getList + , getObj , toString , toInlines , capitalize @@ -128,6 +129,10 @@ getList i (MetaList l) = l !!? i | otherwise = Nothing getList _ x = Just x +getObj :: String -> MetaValue -> Maybe MetaValue +getObj i (MetaMap m) = M.lookup i m +getObj _ _ = Nothing + capitalize :: (String -> Maybe MetaValue) -> String -> Maybe MetaValue capitalize f varname = case f (capitalizeFirst varname) of Nothing -> case f varname of diff --git a/lib/Text/Pandoc/CrossRef/Util/Template.hs b/lib/Text/Pandoc/CrossRef/Util/Template.hs index e3e25b68..3fa37cbc 100644 --- a/lib/Text/Pandoc/CrossRef/Util/Template.hs +++ b/lib/Text/Pandoc/CrossRef/Util/Template.hs @@ -44,7 +44,13 @@ import Control.Monad ((<=<)) import Data.Data (Data) import Text.ParserCombinators.ReadP -data ParseRes = ParseRes { prVar :: String, prIdx :: [String], prPfx :: String, prSfx :: String } deriving Show +data PRVar = PRVar { prvName :: String + , prvIdx :: [[PRVar]] + } deriving Show +data ParseRes = ParseRes { prVar :: [PRVar] + , prPfx :: String + , prSfx :: String + } deriving Show isVariableSym :: Char -> Bool isVariableSym '.' = True @@ -52,10 +58,11 @@ isVariableSym '_' = True isVariableSym c = isAlphaNum c parse :: ReadP ParseRes -parse = uncurry <$> (ParseRes <$> varName <*> many varIdx) <*> option ("", "") ps <* eof +parse = uncurry <$> (ParseRes <$> var) <*> option ("", "") ps <* eof where + var = sepBy1 (PRVar <$> varName <*> many varIdx) (char '?') varName = munch1 isVariableSym - varIdx = between (char '[') (char ']') varName + varIdx = between (char '[') (char ']') var prefix = char '#' *> many (satisfy (/='%')) suffix = char '%' *> many (satisfy (/='#')) ps = (flip (,) <$> suffix <*> option "" prefix) @@ -91,13 +98,19 @@ scan = bottomUp . go | ParseRes{..} <- fst . head $ readP_to_S parse var = let replaceVar = maybe mempty (modifier . toInlines ("variable " ++ var)) modifier = (<> text prSfx) . (text prPfx <>) - in case prIdx of - [] -> toList $ replaceVar (vf prVar) <> fromList xs - idxVars -> - let - idxs :: Maybe [Int] - idxs = mapM (readMaybe . toString ("index variables " ++ show idxVars) <=< vf) idxVars - arr = foldr (\i a -> getList i =<< a) (vf prVar) . reverse =<< idxs - in toList $ replaceVar arr <> fromList xs + tryVar PRVar{..} = + case prvIdx of + [] -> vf prvName + idxVars -> + let + idxs :: Maybe [String] + idxs = mapM (Just . toString ("index variables " ++ show idxVars) <=< tryVars) idxVars + arr = foldr (\i a -> getObjOrList i =<< a) (vf prvName) . reverse =<< idxs + getObjOrList :: String -> MetaValue -> Maybe MetaValue + getObjOrList i x = getObj i x <|> (readMaybe i >>= flip getList x) + in arr + tryVars = foldr ((<|>) . tryVar) Nothing + + in toList $ replaceVar (tryVars prVar) <> fromList xs go _ (x:xs) = toList $ singleton x <> fromList xs go _ [] = [] From 495efaa7faed2e580c5c93df681fd90263300d5c Mon Sep 17 00:00:00 2001 From: Nikolay Yakimov Date: Fri, 8 Mar 2019 04:51:53 +0300 Subject: [PATCH 066/134] Test for template var option --- test/m2m/template-options/expect.md | 37 ++++++++++++++++++++++++++++ test/m2m/template-options/expect.tex | 36 +++++++++++++++++++++++++++ test/m2m/template-options/input.md | 15 +++++++++++ 3 files changed, 88 insertions(+) create mode 100644 test/m2m/template-options/expect.md create mode 100644 test/m2m/template-options/expect.tex create mode 100644 test/m2m/template-options/input.md diff --git a/test/m2m/template-options/expect.md b/test/m2m/template-options/expect.md new file mode 100644 index 00000000..22896922 --- /dev/null +++ b/test/m2m/template-options/expect.md @@ -0,0 +1,37 @@ +Section 1 {#sec:1} +========= + +Section 1.1 {#sec:11} +----------- + +Section 2 {#sec:2 shortCaption="Sec. 2" shortCaption2="Won't actually show"} +========= + +Section 2.1 {#sec:21} +----------- + +### Section 2.1.1 {#sec:211} + +### Section 2.1.2 {#sec:212 shortCaption2="Sec. 2.1.2"} + +Section 3 +========= + +List of Sections +================ + +::: {.list} +1\. Section 1 + +2\. Section 1.1 + +3\. Sec. 2 + +4\. Section 2.1 + +5\. Section 2.1.1 + +6\. Sec. 2.1.2 + +7\. Section 3 +::: diff --git a/test/m2m/template-options/expect.tex b/test/m2m/template-options/expect.tex new file mode 100644 index 00000000..c076719d --- /dev/null +++ b/test/m2m/template-options/expect.tex @@ -0,0 +1,36 @@ +\hypertarget{sec:1}{% +\section{Section 1}\label{sec:1}} + +\hypertarget{sec:11}{% +\subsection{Section 1.1}\label{sec:11}} + +\hypertarget{sec:2}{% +\section{Section 2}\label{sec:2}} + +\hypertarget{sec:21}{% +\subsection{Section 2.1}\label{sec:21}} + +\hypertarget{sec:211}{% +\subsubsection{Section 2.1.1}\label{sec:211}} + +\hypertarget{sec:212}{% +\subsubsection{Section 2.1.2}\label{sec:212}} + +\hypertarget{section-3}{% +\section{Section 3}\label{section-3}} + +\section{List of Sections} + +1. Section 1 + +2. Section 1.1 + +3. Sec. 2 + +4. Section 2.1 + +5. Section 2.1.1 + +6. Sec. 2.1.2 + +7. Section 3 diff --git a/test/m2m/template-options/input.md b/test/m2m/template-options/input.md new file mode 100644 index 00000000..2882a2cc --- /dev/null +++ b/test/m2m/template-options/input.md @@ -0,0 +1,15 @@ +--- +prefixes: + sec: + listItemTemplate: '$$i$$$$listItemNumberDelim$$$$shortCaption?shortCaption2?t$$' +... + +# Section 1 {#sec:1} +## Section 1.1 {#sec:11} +# Section 2 {#sec:2 shortCaption="Sec. 2" shortCaption2="Won't actually show"} +## Section 2.1 {#sec:21} +### Section 2.1.1 {#sec:211} +### Section 2.1.2 {#sec:212 shortCaption2="Sec. 2.1.2"} +# Section 3 + +\listof{sec} From cb3ed49a79e2618902af6d6a16893a5d4e767a09 Mon Sep 17 00:00:00 2001 From: Nikolay Yakimov Date: Fri, 8 Mar 2019 04:54:49 +0300 Subject: [PATCH 067/134] Test for referencing objects in template --- test/m2m/template-objects/expect.md | 37 ++++++++++++++++++++++++++++ test/m2m/template-objects/expect.tex | 36 +++++++++++++++++++++++++++ test/m2m/template-objects/input.md | 19 ++++++++++++++ 3 files changed, 92 insertions(+) create mode 100644 test/m2m/template-objects/expect.md create mode 100644 test/m2m/template-objects/expect.tex create mode 100644 test/m2m/template-objects/input.md diff --git a/test/m2m/template-objects/expect.md b/test/m2m/template-objects/expect.md new file mode 100644 index 00000000..d6727e86 --- /dev/null +++ b/test/m2m/template-objects/expect.md @@ -0,0 +1,37 @@ +Section 1 {#sec:1} +========= + +Section 1.1 {#sec:11} +----------- + +Section 2 {#sec:2 type="cha"} +========= + +Section 2.1 {#sec:21} +----------- + +### Section 2.1.1 {#sec:211} + +### Section 2.1.2 {#sec:212 type="par"} + +Section 3 +========= + +List of Sections +================ + +::: {.list} +1\. Section 1 + +2\. Section 1.1 + +3\. Chapter: Section 2 + +4\. Section 2.1 + +5\. Section 2.1.1 + +6\. Paragraph: Section 2.1.2 + +7\. Section 3 +::: diff --git a/test/m2m/template-objects/expect.tex b/test/m2m/template-objects/expect.tex new file mode 100644 index 00000000..bf6c3cb3 --- /dev/null +++ b/test/m2m/template-objects/expect.tex @@ -0,0 +1,36 @@ +\hypertarget{sec:1}{% +\section{Section 1}\label{sec:1}} + +\hypertarget{sec:11}{% +\subsection{Section 1.1}\label{sec:11}} + +\hypertarget{sec:2}{% +\section{Section 2}\label{sec:2}} + +\hypertarget{sec:21}{% +\subsection{Section 2.1}\label{sec:21}} + +\hypertarget{sec:211}{% +\subsubsection{Section 2.1.1}\label{sec:211}} + +\hypertarget{sec:212}{% +\subsubsection{Section 2.1.2}\label{sec:212}} + +\hypertarget{section-3}{% +\section{Section 3}\label{section-3}} + +\section{List of Sections} + +1. Section 1 + +2. Section 1.1 + +3. Chapter: Section 2 + +4. Section 2.1 + +5. Section 2.1.1 + +6. Paragraph: Section 2.1.2 + +7. Section 3 diff --git a/test/m2m/template-objects/input.md b/test/m2m/template-objects/input.md new file mode 100644 index 00000000..b5d06be9 --- /dev/null +++ b/test/m2m/template-objects/input.md @@ -0,0 +1,19 @@ +--- +prefixes: + sec: + listItemTemplate: '$$i$$$$listItemNumberDelim$$$$sectionType[type]%: $$$$t$$' + sectionType: + cha: "Chapter" + sec: "Section" + par: "Paragraph" +... + +# Section 1 {#sec:1} +## Section 1.1 {#sec:11} +# Section 2 {#sec:2 type="cha"} +## Section 2.1 {#sec:21} +### Section 2.1.1 {#sec:211} +### Section 2.1.2 {#sec:212 type="par"} +# Section 3 + +\listof{sec} From 7a7157d3bebd29de3120e05a7336d396596decc0 Mon Sep 17 00:00:00 2001 From: Nikolay Yakimov Date: Fri, 8 Mar 2019 05:19:08 +0300 Subject: [PATCH 068/134] Test/example of numbering parts --- test/m2m/numbering-parts/expect.md | 32 ++++++++++++++++++++ test/m2m/numbering-parts/expect.tex | 34 ++++++++++++++++++++++ test/m2m/numbering-parts/input.md | 45 +++++++++++++++++++++++++++++ 3 files changed, 111 insertions(+) create mode 100644 test/m2m/numbering-parts/expect.md create mode 100644 test/m2m/numbering-parts/expect.tex create mode 100644 test/m2m/numbering-parts/input.md diff --git a/test/m2m/numbering-parts/expect.md b/test/m2m/numbering-parts/expect.md new file mode 100644 index 00000000..a7c6c155 --- /dev/null +++ b/test/m2m/numbering-parts/expect.md @@ -0,0 +1,32 @@ +I. First part {#prt:prt1} +============= + +1. First chapter {#sec:cha1} +---------------- + +2. Second chapter {#sec:cha2} +----------------- + +### 2.1. A section {#sec:sec21} + +### 2.2. Another section {#sec:sec22} + +II. Second part {#prt:prt2} +=============== + +3. Third chapter {#sec:cha3} +---------------- + +prt. I; + +chp. 1; + +chp. 2; + +sec. 2.2.1; + +sec. 2.2.2; + +prt. II; + +chp. 3; diff --git a/test/m2m/numbering-parts/expect.tex b/test/m2m/numbering-parts/expect.tex new file mode 100644 index 00000000..b8bcaec2 --- /dev/null +++ b/test/m2m/numbering-parts/expect.tex @@ -0,0 +1,34 @@ +\hypertarget{prt:prt1}{% +\section{I. First part}\label{prt:prt1}} + +\hypertarget{sec:cha1}{% +\subsection{1. First chapter}\label{sec:cha1}} + +\hypertarget{sec:cha2}{% +\subsection{2. Second chapter}\label{sec:cha2}} + +\hypertarget{sec:sec21}{% +\subsubsection{2.1. A section}\label{sec:sec21}} + +\hypertarget{sec:sec22}{% +\subsubsection{2.2. Another section}\label{sec:sec22}} + +\hypertarget{prt:prt2}{% +\section{II. Second part}\label{prt:prt2}} + +\hypertarget{sec:cha3}{% +\subsection{3. Third chapter}\label{sec:cha3}} + +prt.~\ref{prt:prt1}; + +chp.~\ref{sec:cha1}; + +chp.~\ref{sec:cha2}; + +sec.~\ref{sec:sec21}; + +sec.~\ref{sec:sec22}; + +prt.~\ref{prt:prt2}; + +chp.~\ref{sec:cha3}; diff --git a/test/m2m/numbering-parts/input.md b/test/m2m/numbering-parts/input.md new file mode 100644 index 00000000..526dbb72 --- /dev/null +++ b/test/m2m/numbering-parts/input.md @@ -0,0 +1,45 @@ +--- +prefixes: + prt: + from: sec + title: Part + ref: ["prt.", "prts."] + numbering: roman + sec: + captionTemplate: '$$i$$$$titleDelim$$ $$t$$' # show part/etc numbers + titleDelim: '.' + numbering: arabic + title: Chapter + ref: ["chp.", "chps."] + sub: + # sub-sections can override any settings from parent + # Here we want to have sections scoped to chapters, so + scope: sec + title: Section + ref: ["sec.", "secs."] + # We also want to show parent scope number in reference and title + captionIndexTemplate: '$$s.i$$.$$i$$' + referenceIndexTemplate: '$$s.i$$.$$i$$' +... + +# First part {#prt:prt1} +## First chapter {#sec:cha1} +## Second chapter {#sec:cha2} +### A section {#sec:sec21} +### Another section {#sec:sec22} +# Second part {#prt:prt2} +## Third chapter {#sec:cha3} + +@prt:prt1; + +@sec:cha1; + +@sec:cha2; + +@sec:sec21; + +@sec:sec22; + +@prt:prt2; + +@sec:cha3; From ec33f99da3ef14b1faf9dec8ae5081b16e6a6f7e Mon Sep 17 00:00:00 2001 From: Nikolay Yakimov Date: Fri, 8 Mar 2019 05:57:05 +0300 Subject: [PATCH 069/134] Fix subtle inconsistency wrt $$i$$ var in captionIndexTemplate and elsewhere --- lib/Text/Pandoc/CrossRef/References/Blocks.hs | 10 ++++++---- lib/Text/Pandoc/CrossRef/References/Refs.hs | 8 ++++---- lib/Text/Pandoc/CrossRef/References/Types/Ref.hs | 3 ++- lib/Text/Pandoc/CrossRef/Util/Settings.hs | 2 +- lib/Text/Pandoc/CrossRef/Util/VarFunction.hs | 1 + pandoc-crossref.cabal | 11 ++++++++++- test/m2m/numbering-parts/expect.md | 4 ++-- test/m2m/numbering-parts/input.md | 3 +-- test/m2m/scoping/input.md | 2 +- test/m2m/section-template/input.md | 2 +- test/test-pandoc-crossref.hs | 1 + 11 files changed, 30 insertions(+), 17 deletions(-) diff --git a/lib/Text/Pandoc/CrossRef/References/Blocks.hs b/lib/Text/Pandoc/CrossRef/References/Blocks.hs index b979d53f..64472873 100644 --- a/lib/Text/Pandoc/CrossRef/References/Blocks.hs +++ b/lib/Text/Pandoc/CrossRef/References/Blocks.hs @@ -200,11 +200,12 @@ applyTitleTemplate :: RefRec -> B.Inlines applyTitleTemplate rr@RefRec{refPfxRec} = applyTemplate (prefixCaptionTemplate refPfxRec) (fix defaultVarFunc rr) -applyTitleIndexTemplate :: RefRec -> B.Inlines -> B.Inlines -applyTitleIndexTemplate rr@RefRec{..} label = +applyTitleIndexTemplate :: RefRec -> B.Inlines +applyTitleIndexTemplate rr@RefRec{..} = applyTemplate (prefixCaptionIndexTemplate refPfxRec) vf where - vf "i" = Just $ MetaInlines $ B.toList label + vf "i" = Nothing + vf "ri" = Just $ MetaInlines $ B.toList refIxInlRaw vf x = fix defaultVarFunc rr x divBlocks :: Options -> Block -> Block @@ -275,7 +276,8 @@ replaceAttr o scope label attrs title pfx refIndex = i , refTitle = title , refLabel = label' - , refIxInl = applyTitleIndexTemplate rec' $ B.text $ fromMaybe (customLabel iInSc) refLabel' + , refIxInl = applyTitleIndexTemplate rec' + , refIxInlRaw = B.text $ fromMaybe (customLabel iInSc) refLabel' , refScope = itemScope , refLevel = lvl , refPfx = pfx diff --git a/lib/Text/Pandoc/CrossRef/References/Refs.hs b/lib/Text/Pandoc/CrossRef/References/Refs.hs index ae7bba35..c3098caf 100644 --- a/lib/Text/Pandoc/CrossRef/References/Refs.hs +++ b/lib/Text/Pandoc/CrossRef/References/Refs.hs @@ -225,10 +225,10 @@ makeIndices o s = format $ concatMap f $ HT.groupBy g $ sort $ nub $ NE.toList s show' RefDataComplete{..} | linkReferences o = link ('#':refLabel rdRec) "" txt | otherwise = txt - where txt = applyIndexTemplate o rdcSuffix rdRec + where txt = applyIndexTemplate rdcSuffix rdRec -applyIndexTemplate :: Options -> Inlines -> RefRec -> Inlines -applyIndexTemplate opts suf rr = +applyIndexTemplate :: Inlines -> RefRec -> Inlines +applyIndexTemplate suf rr = let varsSc rr' "ref" = Just $ inlines False rr' varsSc rr' "Ref" = Just $ inlines True rr' varsSc rr' x = defaultVarFunc varsSc rr' x @@ -236,5 +236,5 @@ applyIndexTemplate opts suf rr = vars rr' x = defaultVarFunc varsSc rr' x template = prefixReferenceIndexTemplate $ refPfxRec rr inlines cap ref = MetaInlines $ toList $ - getRefPrefix cap 0 ref $ applyIndexTemplate opts mempty ref + getRefPrefix cap 0 ref $ applyIndexTemplate mempty ref in applyTemplate template (vars rr) diff --git a/lib/Text/Pandoc/CrossRef/References/Types/Ref.hs b/lib/Text/Pandoc/CrossRef/References/Types/Ref.hs index e02dc683..618f629a 100644 --- a/lib/Text/Pandoc/CrossRef/References/Types/Ref.hs +++ b/lib/Text/Pandoc/CrossRef/References/Types/Ref.hs @@ -30,7 +30,8 @@ import Text.Pandoc.Builder import Text.Pandoc.CrossRef.Util.Prefixes.Types data RefRec = RefRec { refIndex :: !Int -- global ordinal number for prefix - , refIxInl :: Inlines -- index as inilnes + , refIxInl :: Inlines -- templated index as inilnes + , refIxInlRaw :: !Inlines -- raw index as inilnes , refTitle :: !Inlines -- title text , refScope :: !(Maybe RefRec) -- reference to parent scope label (as specified in scopes array) , refLevel :: !Int -- number of upper scopes of the same prefix diff --git a/lib/Text/Pandoc/CrossRef/Util/Settings.hs b/lib/Text/Pandoc/CrossRef/Util/Settings.hs index 2a8d09d8..c8f1016a 100644 --- a/lib/Text/Pandoc/CrossRef/Util/Settings.hs +++ b/lib/Text/Pandoc/CrossRef/Util/Settings.hs @@ -78,7 +78,7 @@ defaultMeta = Settings $ <> collectedCaptionItemDelim (space <> str "–" <> space) -- these are merely the defaults, can (and will) be overridden in prefix configs <> captionTemplate (var "title%\160" <> var "i" <> var "titleDelim" <> var "t") - <> captionIndexTemplate (var "i") + <> captionIndexTemplate (var "ri") <> referenceTemplate (var "Ref[n]%\160" <> var "rs") <> listItemTemplate (var "i" <> var "listItemNumberDelim" <> var "t") <> collectedCaptionTemplate (var "i" <> var "collectedCaptionItemDelim" <> var "t") diff --git a/lib/Text/Pandoc/CrossRef/Util/VarFunction.hs b/lib/Text/Pandoc/CrossRef/Util/VarFunction.hs index 1616ba64..9a0b3aee 100644 --- a/lib/Text/Pandoc/CrossRef/Util/VarFunction.hs +++ b/lib/Text/Pandoc/CrossRef/Util/VarFunction.hs @@ -33,6 +33,7 @@ defaultVarFunc :: (RefRec -> String -> Maybe MetaValue) -> RefRec -> String -> Maybe MetaValue defaultVarFunc self RefRec{..} x = case x of "idx" -> Just $ MetaString $ show refIndex + "ri" -> Just $ MetaInlines $ B.toList refIxInlRaw "i" -> Just $ MetaInlines $ B.toList refIxInl "t" -> Just $ MetaInlines $ B.toList refTitle "lvl" -> Just $ MetaString $ show refLevel diff --git a/pandoc-crossref.cabal b/pandoc-crossref.cabal index 5b00a16d..2c82c6cf 100644 --- a/pandoc-crossref.cabal +++ b/pandoc-crossref.cabal @@ -4,7 +4,7 @@ cabal-version: 1.12 -- -- see: https://github.com/sol/hpack -- --- hash: 16bfa252f3b9110d753471255207a77e119b4a1311940c7c26c1aa9230c5a9ae +-- hash: dc05cfedfed6de367d50b717064291868887b68c7cb98c5bd0db3e93e4b1c700 name: pandoc-crossref version: 0.4.0.0 @@ -58,6 +58,9 @@ data-files: test/m2m/listing-captions-ids/expect.md test/m2m/listing-captions-ids/expect.tex test/m2m/listing-captions-ids/input.md + test/m2m/numbering-parts/expect.md + test/m2m/numbering-parts/expect.tex + test/m2m/numbering-parts/input.md test/m2m/ref-attrs/expect.md test/m2m/ref-attrs/expect.tex test/m2m/ref-attrs/input.md @@ -82,6 +85,12 @@ data-files: test/m2m/subfigures/expect.md test/m2m/subfigures/expect.tex test/m2m/subfigures/input.md + test/m2m/template-objects/expect.md + test/m2m/template-objects/expect.tex + test/m2m/template-objects/input.md + test/m2m/template-options/expect.md + test/m2m/template-options/expect.tex + test/m2m/template-options/input.md test/m2m/undefined-prefix/expect.md test/m2m/undefined-prefix/expect.tex test/m2m/undefined-prefix/input.md diff --git a/test/m2m/numbering-parts/expect.md b/test/m2m/numbering-parts/expect.md index a7c6c155..3c22af2f 100644 --- a/test/m2m/numbering-parts/expect.md +++ b/test/m2m/numbering-parts/expect.md @@ -23,9 +23,9 @@ chp. 1; chp. 2; -sec. 2.2.1; +sec. 2.1; -sec. 2.2.2; +sec. 2.2; prt. II; diff --git a/test/m2m/numbering-parts/input.md b/test/m2m/numbering-parts/input.md index 526dbb72..2f6e4a93 100644 --- a/test/m2m/numbering-parts/input.md +++ b/test/m2m/numbering-parts/input.md @@ -18,8 +18,7 @@ prefixes: title: Section ref: ["sec.", "secs."] # We also want to show parent scope number in reference and title - captionIndexTemplate: '$$s.i$$.$$i$$' - referenceIndexTemplate: '$$s.i$$.$$i$$' + captionIndexTemplate: '$$s.i$$.$$ri$$' ... # First part {#prt:prt1} diff --git a/test/m2m/scoping/input.md b/test/m2m/scoping/input.md index 95baff1c..ac6f819e 100644 --- a/test/m2m/scoping/input.md +++ b/test/m2m/scoping/input.md @@ -11,7 +11,7 @@ prefixes: referenceIndexTemplate: "$$i$$$$s.ref# (%)$$" sec: captionTemplate: '$$title% $$$$i$$$$titleDelim$$ $$t$$' - captionIndexTemplate: '$$s.i%.$$$$i$$' + captionIndexTemplate: '$$s.i%.$$$$ri$$' referenceIndexTemplate: '$$i$$$$s.ref# (%)$$' scope: sec titleDelim: '.' diff --git a/test/m2m/section-template/input.md b/test/m2m/section-template/input.md index badb2e94..2fa390da 100644 --- a/test/m2m/section-template/input.md +++ b/test/m2m/section-template/input.md @@ -2,7 +2,7 @@ prefixes: sec: captionTemplate: $$titleName[lvl]$$$$i$$. $$t$$ - captionIndexTemplate: '$$s.i%.$$$$i$$' + captionIndexTemplate: '$$s.i%.$$$$ri$$' scope: sec titleName: - "Chapter " diff --git a/test/test-pandoc-crossref.hs b/test/test-pandoc-crossref.hs index 73326f01..b0ea16dc 100644 --- a/test/test-pandoc-crossref.hs +++ b/test/test-pandoc-crossref.hs @@ -404,6 +404,7 @@ refRec' ref i tit cap = , RefRec { refIndex=i , refIxInl = str $ show i + , refIxInlRaw = str $ show i , refCaption= cap , refTitle=tit , refScope=Nothing From 2d320038c1b727c451dae47bcbf34fbdfc62cc76 Mon Sep 17 00:00:00 2001 From: Nikolay Yakimov Date: Fri, 8 Mar 2019 07:49:11 +0300 Subject: [PATCH 070/134] Caption placement initial --- lib/Text/Pandoc/CrossRef/References/Blocks.hs | 49 ++++++++++++------- .../Pandoc/CrossRef/References/Types/Ref.hs | 1 + .../Pandoc/CrossRef/Util/CodeBlockCaptions.hs | 8 +-- lib/Text/Pandoc/CrossRef/Util/Prefixes.hs | 3 ++ .../Pandoc/CrossRef/Util/Prefixes/Types.hs | 3 ++ lib/Text/Pandoc/CrossRef/Util/Settings.hs | 3 +- test/test-pandoc-crossref.hs | 18 ++++--- 7 files changed, 55 insertions(+), 30 deletions(-) diff --git a/lib/Text/Pandoc/CrossRef/References/Blocks.hs b/lib/Text/Pandoc/CrossRef/References/Blocks.hs index 64472873..2cd754ca 100644 --- a/lib/Text/Pandoc/CrossRef/References/Blocks.hs +++ b/lib/Text/Pandoc/CrossRef/References/Blocks.hs @@ -77,11 +77,12 @@ replaceElement opts scope (Sec n ns (label, cls, attrs) text' body) = do rec' <- case pfx' of Just p -> replaceAttr opts scope (Right label') attrs ititle p Nothing -> replaceAttr opts scope (Left defaultSecPfx) attrs ititle defaultSecPfx - let title' = B.toList $ applyTitleTemplate rec' + let title' = B.toList $ refCaption rec' replaceRecurse (newScope rec' scope) $ Sec n ns (label', cls, attrs) title' body replaceElement _ scope _ = noReplaceRecurse scope replaceBlock :: Options -> Scope -> Block -> WS (ReplacedResult Block) +-- tables replaceBlock opts scope (Div divOps@(label,_,attrs) [Table title align widths header cells]) | not $ null title , Just pfx <- getRefPrefix opts label @@ -91,19 +92,17 @@ replaceBlock opts scope (Div divOps@(label,_,attrs) [Table title align widths he let title' = B.toList $ case outFormat opts of f | isLatexFormat f -> B.rawInline "latex" (mkLaTeXLabel label) <> ititle - _ -> applyTitleTemplate idxStr + _ -> refCaption idxStr replaceNoRecurse $ Div divOps [Table title' align widths header cells] -replaceBlock opts scope (Div (label,"listing":_, []) [Para caption, CodeBlock ([],classes,attrs) code]) - | not $ null label - , Just pfx <- getRefPrefix opts label +-- code blocks +replaceBlock opts scope (Div (label, [], divattrs) [CodeBlock ([],classes,cbattrs) code, Para (Str ":":Space:caption)]) + | Just pfx <- getRefPrefix opts label = do - let icaption = B.fromList caption - idxStr <- replaceAttr opts scope (Right label) attrs icaption pfx - let caption' = applyTitleTemplate idxStr + idxStr <- replaceAttr opts scope (Right label) divattrs (B.fromList caption) pfx replaceNoRecurse $ case outFormat opts of f --if used with listings package, return code block with caption | isLatexFormat f, listings opts -> - CodeBlock (label,classes,("caption",stringify caption):attrs) code + CodeBlock (label,classes,("caption",stringify caption):cbattrs) code --if not using listings, however, wrap it in a codelisting environment | isLatexFormat f -> Div nullAttr [ @@ -112,13 +111,12 @@ replaceBlock opts scope (Div (label,"listing":_, []) [Para caption, CodeBlock ([ RawInline (Format "latex") "\\caption" , Span nullAttr caption ] - , CodeBlock (label,classes,attrs) code + , CodeBlock (label,classes,cbattrs) code , RawBlock (Format "latex") "\\end{codelisting}" ] - _ -> Div (label, "listing":classes, []) [ - mkCaption opts "Caption" caption' - , CodeBlock ([], classes, attrs) code - ] + _ -> Div (label, "listing":classes, []) $ placeCaption opts idxStr + [CodeBlock ([], classes, cbattrs) code] +-- Table display math replaceBlock opts scope (Para [Span ats@(label, _, attrs) [Math DisplayMath eq]]) | not $ isLatexFormat (outFormat opts) , tableEqns opts @@ -127,6 +125,7 @@ replaceBlock opts scope (Para [Span ats@(label, _, attrs) [Math DisplayMath eq]] = do (eq', idx) <- replaceEqn opts scope lbl attrs eq pfx replaceNoRecurse $ Div ats [Table [] [AlignCenter, AlignRight] [0.9, 0.09] [] [[[Plain [Math DisplayMath eq']], [Plain [Math DisplayMath $ "(" ++ idx ++ ")"]]]]] +-- Generic div replaceBlock opts scope x@(Div ats@(label, _, attrs) content) | Just pfx <- getRefPrefix opts label = do @@ -138,9 +137,16 @@ replaceBlock opts scope x@(Div ats@(label, _, attrs) content) rec' <- replaceAttr opts scope (Right label) attrs (fromMaybe mempty caption) pfx replaceRecurse (newScope rec' scope) $ case caption of Nothing -> x - Just _ -> Div ats $ init content <> [Para $ B.toList (applyTitleTemplate rec')] + Just _ -> Div ats . placeCaption opts rec' $ init content replaceBlock _ scope _ = noReplaceRecurse scope +placeCaption :: Options -> RefRec -> [Block] -> [Block] +placeCaption opts RefRec{..} body + | Above <- refCaptionPosition + = mkCaption opts "Caption" refCaption : body + | Below <- refCaptionPosition + = body <> [mkCaption opts "Caption" refCaption] + replaceEqn :: Options -> Scope -> Either String String -> [(String, String)] -> String -> String -> WS (String, String) replaceEqn opts scope label attrs eq pfx = do idxStr <- replaceAttr opts scope label attrs (B.math eq) pfx @@ -174,7 +180,7 @@ replaceInline opts scope (Image attr@(label,_,attrs) alt img@(_, tit)) idxStr <- replaceAttr opts scope lbl attrs ialt pfx let alt' = B.toList $ case outFormat opts of f | isLatexFormat f -> ialt - _ -> applyTitleTemplate idxStr + _ -> refCaption idxStr replaceNoRecurse $ Image attr alt' img replaceInline opts scope (Span (label,_,attrs) content) | Just pfx <- getRefPrefix opts label @@ -209,16 +215,20 @@ applyTitleIndexTemplate rr@RefRec{..} = vf x = fix defaultVarFunc rr x divBlocks :: Options -> Block -> Block +divBlocks opts (Table [Span (label, cls, attr) title] align widths header cells) + | not $ null title + , isJust $ getRefPrefix opts label + = Div (label, cls, attr) [Table (dropWhileEnd isSpace $ init title) align widths header cells] divBlocks opts (Table title align widths header cells) | not $ null title , Just label <- getRefLabel opts [last title] = Div (label,[],[]) [Table (dropWhileEnd isSpace $ init title) align widths header cells] divBlocks opts (CodeBlock (label, classes, attrs) code) | Just caption <- lookup "caption" attrs - , Just _ <- getRefPrefix opts label - = let p = Para $ B.toList $ B.text caption + , isJust $ getRefPrefix opts label + = let p = Para $ Str ":" : Space : B.toList (B.text caption) cb' = CodeBlock ([], classes, delete ("caption", caption) attrs) code - in Div (label,"listing":classes, []) [p, cb'] + in Div (label, [], []) [cb', p] divBlocks _ x = x splitMath :: [Block] -> [Block] @@ -284,6 +294,7 @@ replaceAttr o scope label attrs title pfx , refPfxRec = ropt , refCaption = applyTitleTemplate rec' , refAttrs = metaAttrMap + , refCaptionPosition = prefixCaptionPosition ropt } modify referenceData $ M.insert label' rec' return rec' diff --git a/lib/Text/Pandoc/CrossRef/References/Types/Ref.hs b/lib/Text/Pandoc/CrossRef/References/Types/Ref.hs index 618f629a..87de6220 100644 --- a/lib/Text/Pandoc/CrossRef/References/Types/Ref.hs +++ b/lib/Text/Pandoc/CrossRef/References/Types/Ref.hs @@ -40,6 +40,7 @@ data RefRec = RefRec { refIndex :: !Int -- global ordinal number for prefix , refPfxRec :: !Prefix -- reference prefix, the part in label before : , refCaption :: Inlines -- caption after applying template; must be non-strict , refAttrs :: !(M.Map String MetaValue) -- attribute map + , refCaptionPosition :: !CaptionPosition } instance Eq RefRec where diff --git a/lib/Text/Pandoc/CrossRef/Util/CodeBlockCaptions.hs b/lib/Text/Pandoc/CrossRef/Util/CodeBlockCaptions.hs index 6a873904..1d916eb0 100644 --- a/lib/Text/Pandoc/CrossRef/Util/CodeBlockCaptions.hs +++ b/lib/Text/Pandoc/CrossRef/Util/CodeBlockCaptions.hs @@ -42,14 +42,14 @@ orderAgnostic opts (Para ils:CodeBlock (label,classes,attrs) code:xs) , Just caption <- getCodeBlockCaption ils , not $ null label , Just _ <- getRefPrefix opts label - = return $ Div (label,"listing":classes, []) - [Para caption, CodeBlock ([],classes,attrs) code] : xs + = return $ Div (label, [], []) + [CodeBlock ([],classes,attrs) code, Para $ Str ":":Space:caption] : xs orderAgnostic opts (Para ils:CodeBlock (_,classes,attrs) code:xs) | codeBlockCaptions opts , Just (caption, labinl) <- splitLast <$> getCodeBlockCaption ils , Just label <- getRefLabel opts labinl - = return $ Div (label,"listing":classes, []) - [Para $ init caption, CodeBlock ([],classes,attrs) code] : xs + = return $ Div (label, [], []) + [CodeBlock ([],classes,attrs) code, Para $ Str ":":Space:init caption] : xs where splitLast xs' = splitAt (length xs' - 1) xs' orderAgnostic _ _ = Nothing diff --git a/lib/Text/Pandoc/CrossRef/Util/Prefixes.hs b/lib/Text/Pandoc/CrossRef/Util/Prefixes.hs index 42ca2e99..b446837c 100644 --- a/lib/Text/Pandoc/CrossRef/Util/Prefixes.hs +++ b/lib/Text/Pandoc/CrossRef/Util/Prefixes.hs @@ -54,6 +54,9 @@ getPrefixes varN dtv $ lookupSettings varName kv) , prefixSubcaptions = getMetaBool "subcaptions" kv , prefixSubcaptionsGrid = getMetaBool "subcaptionsGrid" kv + , prefixCaptionPosition = case getMetaString "captionPosition" kv of + "above" -> Above + _ -> Below , prefixSub = m2p k . (`merge` MetaMap kv') <$> lookupSettings "sub" (Settings (Meta kv') <> from) } where kv = Settings (Meta kv') <> from <> dtv diff --git a/lib/Text/Pandoc/CrossRef/Util/Prefixes/Types.hs b/lib/Text/Pandoc/CrossRef/Util/Prefixes/Types.hs index a78fa19e..85238c1c 100644 --- a/lib/Text/Pandoc/CrossRef/Util/Prefixes/Types.hs +++ b/lib/Text/Pandoc/CrossRef/Util/Prefixes/Types.hs @@ -28,6 +28,8 @@ import Text.Pandoc.Builder type Prefixes = M.Map String Prefix +data CaptionPosition = Above | Below + data Prefix = Prefix { prefixCaptionTemplate :: !Template , prefixReferenceIndexTemplate :: !Template @@ -41,5 +43,6 @@ data Prefix = Prefix { , prefixNumbering :: !(Int -> String) , prefixSubcaptions :: !Bool , prefixSubcaptionsGrid :: !Bool + , prefixCaptionPosition :: !CaptionPosition , prefixSub :: !(Maybe Prefix) } diff --git a/lib/Text/Pandoc/CrossRef/Util/Settings.hs b/lib/Text/Pandoc/CrossRef/Util/Settings.hs index c8f1016a..e700d28f 100644 --- a/lib/Text/Pandoc/CrossRef/Util/Settings.hs +++ b/lib/Text/Pandoc/CrossRef/Util/Settings.hs @@ -97,7 +97,8 @@ defaultMeta = Settings $ ], "lst" .: [ "ref" .= map str ["lst.", "lsts."], - "title" .= text "Listing" + "title" .= text "Listing", + "captionPosition" .= "above" ], "tbl" .: [ "ref" .= map str ["tbl.", "tbls."], diff --git a/test/test-pandoc-crossref.hs b/test/test-pandoc-crossref.hs index b0ea16dc..4055ad7f 100644 --- a/test/test-pandoc-crossref.hs +++ b/test/test-pandoc-crossref.hs @@ -215,13 +215,13 @@ main = hspec $ do ) it "Labels code blocks" $ testAll (codeBlock' "Test code block" "codeblock") - (codeBlockDiv "Listing\160\&1: Test code block" "codeblock", + (codeBlockDiv' "Listing\160\&1: Test code block" "codeblock", (referenceData =: M.fromList [refRec' "lst:codeblock" 1 "Test code block" "Listing\160\&1: Test code block"]) . (pfxCounter =: M.singleton "lst" $ CounterRec {crIndex = 1, crIndexInScope = M.singleton Nothing 1}) ) it "Labels code block divs" $ testAll (codeBlockDiv "Test code block" "codeblock") - (codeBlockDiv "Listing\160\&1: Test code block" "codeblock", + (codeBlockDiv' "Listing\160\&1: Test code block" "codeblock", (referenceData =: M.fromList [refRec' "lst:codeblock" 1 "Test code block" "Listing\160\&1: Test code block"]) . (pfxCounter =: M.singleton "lst" $ CounterRec {crIndex = 1, crIndexInScope = M.singleton Nothing 1}) ) @@ -413,6 +413,7 @@ refRec' ref i tit cap = , refLabel=ref , refAttrs = M.empty , refPfxRec = pfxRec + , refCaptionPosition = Below } ) @@ -437,6 +438,7 @@ instance Show Prefix where instance Show Template where show _ = "Template{}" deriving instance Show RefRec +deriving instance Show CaptionPosition deriving instance Show CounterRec deriving instance Eq CounterRec deriving instance Show References @@ -485,10 +487,14 @@ paraText :: String -> Blocks paraText s = para $ text s codeBlockDiv :: String -> String -> Blocks -codeBlockDiv title ref = divWith ("lst:"++ref, ["listing","haskell"],[]) $ - para (text title) <> - codeBlockWith - ("",["haskell"],[]) "main :: IO ()" +codeBlockDiv title ref = divWith ("lst:"++ref, [], []) $ + codeBlockWith ("",["haskell"],[]) "main :: IO ()" + <> para (text $ ": " <> title) + +codeBlockDiv' :: String -> String -> Blocks +codeBlockDiv' title ref = divWith ("lst:"++ref, ["listing", "haskell"], []) $ + para (text title) + <> codeBlockWith ("",["haskell"],[]) "main :: IO ()" ref' :: String -> String -> Inlines ref' p n | null n = mempty From e49b0bc7d04133124f5d4428f811edb2e2f6f2ec Mon Sep 17 00:00:00 2001 From: Nikolay Yakimov Date: Fri, 8 Mar 2019 23:13:05 +0300 Subject: [PATCH 071/134] Configurable default and auto section prefix --- lib/Text/Pandoc/CrossRef/References/Blocks.hs | 15 ++++++++------- lib/Text/Pandoc/CrossRef/Util/Options/Types.hs | 3 ++- lib/Text/Pandoc/CrossRef/Util/Settings.hs | 3 +-- 3 files changed, 11 insertions(+), 10 deletions(-) diff --git a/lib/Text/Pandoc/CrossRef/References/Blocks.hs b/lib/Text/Pandoc/CrossRef/References/Blocks.hs index 2cd754ca..2294f505 100644 --- a/lib/Text/Pandoc/CrossRef/References/Blocks.hs +++ b/lib/Text/Pandoc/CrossRef/References/Blocks.hs @@ -50,7 +50,7 @@ import Prelude replaceAll :: Options -> [Block] -> WS [Block] replaceAll opts = fmap unhierarchicalize - . runReplace [] (mkRR (replaceElement opts) `extRR` replaceBlock opts `extRR` replaceInline opts) + . runReplace [] (mkRR replaceElement `extRR` replaceBlock opts `extRR` replaceInline opts) . hierarchicalize . runSplitMath . everywhere (mkT $ makeSubfigures opts) @@ -62,10 +62,11 @@ replaceAll opts = = everywhere (mkT splitMath) | otherwise = id -replaceElement :: Options -> Scope -> Element -> WS (ReplacedResult Element) -replaceElement opts scope (Sec n ns (label, cls, attrs) text' body) = do - let label' = if autoSectionLabels opts && isNothing pfx - then "sec:"++label +replaceElement :: Scope -> Element -> WS (ReplacedResult Element) +replaceElement scope (Sec n ns (label, cls, attrs) text' body) = do + opts@Options{..} <- asks creOptions + let label' = if isNothing pfx + then maybe label (<> ":" <> label) autoSectionLabels else label pfx = getRefPrefix opts label if "unnumbered" `elem` cls @@ -73,13 +74,13 @@ replaceElement opts scope (Sec n ns (label, cls, attrs) text' body) = do else do let pfx' = getRefPrefix opts label' ititle = B.fromList text' - defaultSecPfx = "sec" + defaultSecPfx = fromMaybe defaultSectionPrefix autoSectionLabels rec' <- case pfx' of Just p -> replaceAttr opts scope (Right label') attrs ititle p Nothing -> replaceAttr opts scope (Left defaultSecPfx) attrs ititle defaultSecPfx let title' = B.toList $ refCaption rec' replaceRecurse (newScope rec' scope) $ Sec n ns (label', cls, attrs) title' body -replaceElement _ scope _ = noReplaceRecurse scope +replaceElement scope _ = noReplaceRecurse scope replaceBlock :: Options -> Scope -> Block -> WS (ReplacedResult Block) -- tables diff --git a/lib/Text/Pandoc/CrossRef/Util/Options/Types.hs b/lib/Text/Pandoc/CrossRef/Util/Options/Types.hs index a1e91da5..1a1566cb 100644 --- a/lib/Text/Pandoc/CrossRef/Util/Options/Types.hs +++ b/lib/Text/Pandoc/CrossRef/Util/Options/Types.hs @@ -26,7 +26,8 @@ import Text.Pandoc.Builder data Options = Options { cref :: Bool , listings :: Bool , codeBlockCaptions :: Bool - , autoSectionLabels :: Bool + , autoSectionLabels :: Maybe String + , defaultSectionPrefix :: String , rangeDelim :: Inlines , pairDelim :: Inlines , lastDelim :: Inlines diff --git a/lib/Text/Pandoc/CrossRef/Util/Settings.hs b/lib/Text/Pandoc/CrossRef/Util/Settings.hs index e700d28f..97bac4aa 100644 --- a/lib/Text/Pandoc/CrossRef/Util/Settings.hs +++ b/lib/Text/Pandoc/CrossRef/Util/Settings.hs @@ -62,8 +62,7 @@ defaultMeta = Settings $ cref False <> listings False <> codeBlockCaptions False - <> autoSectionLabels False - -- <> numberSections False + <> defaultSectionPrefix "sec" <> titleDelim (str ":" <> space) <> listItemNumberDelim (str "." <> space) <> rangeDelim (str "-") From 28b1b30b82d325a16b86190e544f8f904fa40afe Mon Sep 17 00:00:00 2001 From: Nikolay Yakimov Date: Sat, 9 Mar 2019 05:06:47 +0300 Subject: [PATCH 072/134] Give up on "nice" LaTeX output for now. This commit removes most LaTeX-specific code, and just treats LaTeX as any other output format. This should (mostly) work for the purpose of PDF output, but the resulting LaTeX code wouldn't be much different from a plaintext file. Anyway, reimplementing pandoc-crossref algorithms in LaTeX might be a fun challenge, but it will take an unreasonable amount of time. LaTeX gurus are welcome to help out. --- lib/Text/Pandoc/CrossRef/References/Blocks.hs | 71 +++----- lib/Text/Pandoc/CrossRef/References/List.hs | 10 -- lib/Text/Pandoc/CrossRef/References/Refs.hs | 29 +--- .../Pandoc/CrossRef/References/Subfigures.hs | 60 +++---- lib/Text/Pandoc/CrossRef/Util/ModifyMeta.hs | 74 +------- .../Pandoc/CrossRef/Util/Options/Types.hs | 4 +- lib/Text/Pandoc/CrossRef/Util/Settings.hs | 4 +- lib/Text/Pandoc/CrossRef/Util/Util.hs | 2 +- pandoc-crossref.cabal | 25 +-- test/m2m/capitalization/expect.tex | 36 ---- test/m2m/custom-prefixes/expect.md | 8 +- test/m2m/custom-prefixes/expect.tex | 14 -- test/m2m/delim/expect.tex | 49 ------ test/m2m/equations-auto/expect.tex | 39 ----- test/m2m/equations-tables-auto/expect.tex | 39 ----- test/m2m/equations-tables/expect.tex | 37 ---- test/m2m/equations/expect.tex | 49 ------ test/m2m/links-names/expect.tex | 49 ------ test/m2m/links/expect.tex | 49 ------ test/m2m/list-of/expect.md | 23 +-- test/m2m/list-of/expect.tex | 100 ----------- test/m2m/listing-captions-ids/expect.tex | 162 ------------------ test/m2m/numbering-parts/expect.tex | 34 ---- test/m2m/ref-attrs/expect.tex | 52 ------ test/m2m/regresssion-219/expect.tex | 2 - test/m2m/scoping/expect.md | 12 +- test/m2m/scoping/expect.tex | 70 -------- test/m2m/section-template/expect.tex | 19 -- test/m2m/subfigures-ccsDelim/expect.tex | 53 ------ test/m2m/subfigures-grid/expect.tex | 53 ------ .../subfigures-template-collect/expect.tex | 53 ------ test/m2m/subfigures/expect.tex | 53 ------ test/m2m/template-objects/expect.tex | 36 ---- test/m2m/template-options/expect.tex | 36 ---- test/m2m/undefined-prefix/expect.tex | 2 - test/test-integrative.hs | 7 - test/test-pandoc-crossref.hs | 47 +---- 37 files changed, 76 insertions(+), 1386 deletions(-) delete mode 100644 test/m2m/capitalization/expect.tex delete mode 100644 test/m2m/custom-prefixes/expect.tex delete mode 100644 test/m2m/delim/expect.tex delete mode 100644 test/m2m/equations-auto/expect.tex delete mode 100644 test/m2m/equations-tables-auto/expect.tex delete mode 100644 test/m2m/equations-tables/expect.tex delete mode 100644 test/m2m/equations/expect.tex delete mode 100644 test/m2m/links-names/expect.tex delete mode 100644 test/m2m/links/expect.tex delete mode 100644 test/m2m/list-of/expect.tex delete mode 100644 test/m2m/listing-captions-ids/expect.tex delete mode 100644 test/m2m/numbering-parts/expect.tex delete mode 100644 test/m2m/ref-attrs/expect.tex delete mode 100644 test/m2m/regresssion-219/expect.tex delete mode 100644 test/m2m/scoping/expect.tex delete mode 100644 test/m2m/section-template/expect.tex delete mode 100644 test/m2m/subfigures-ccsDelim/expect.tex delete mode 100644 test/m2m/subfigures-grid/expect.tex delete mode 100644 test/m2m/subfigures-template-collect/expect.tex delete mode 100644 test/m2m/subfigures/expect.tex delete mode 100644 test/m2m/template-objects/expect.tex delete mode 100644 test/m2m/template-options/expect.tex delete mode 100644 test/m2m/undefined-prefix/expect.tex diff --git a/lib/Text/Pandoc/CrossRef/References/Blocks.hs b/lib/Text/Pandoc/CrossRef/References/Blocks.hs index 2294f505..aa36ac05 100644 --- a/lib/Text/Pandoc/CrossRef/References/Blocks.hs +++ b/lib/Text/Pandoc/CrossRef/References/Blocks.hs @@ -58,7 +58,6 @@ replaceAll opts = . everywhere (mkT $ mkCodeBlockCaptions opts) where runSplitMath | tableEqns opts - , not $ isLatexFormat (outFormat opts) = everywhere (mkT splitMath) | otherwise = id @@ -89,56 +88,36 @@ replaceBlock opts scope (Div divOps@(label,_,attrs) [Table title align widths he , Just pfx <- getRefPrefix opts label = do let ititle = B.fromList title - idxStr <- replaceAttr opts scope (Right label) attrs ititle pfx - let title' = B.toList $ - case outFormat opts of - f | isLatexFormat f -> B.rawInline "latex" (mkLaTeXLabel label) <> ititle - _ -> refCaption idxStr - replaceNoRecurse $ Div divOps [Table title' align widths header cells] + RefRec{..} <- replaceAttr opts scope (Right label) attrs ititle pfx + replaceNoRecurse $ Div divOps [Table (B.toList refCaption) align widths header cells] -- code blocks replaceBlock opts scope (Div (label, [], divattrs) [CodeBlock ([],classes,cbattrs) code, Para (Str ":":Space:caption)]) | Just pfx <- getRefPrefix opts label = do - idxStr <- replaceAttr opts scope (Right label) divattrs (B.fromList caption) pfx - replaceNoRecurse $ case outFormat opts of - f --if used with listings package, return code block with caption - | isLatexFormat f, listings opts -> - CodeBlock (label,classes,("caption",stringify caption):cbattrs) code - --if not using listings, however, wrap it in a codelisting environment - | isLatexFormat f -> - Div nullAttr [ - RawBlock (Format "latex") "\\begin{codelisting}" - , Plain [ - RawInline (Format "latex") "\\caption" - , Span nullAttr caption - ] - , CodeBlock (label,classes,cbattrs) code - , RawBlock (Format "latex") "\\end{codelisting}" - ] - _ -> Div (label, "listing":classes, []) $ placeCaption opts idxStr - [CodeBlock ([], classes, cbattrs) code] + ref <- replaceAttr opts scope (Right label) divattrs (B.fromList caption) pfx + replaceNoRecurse $ + Div (label, "listing":classes, []) + $ placeCaption opts ref [CodeBlock ([], classes, cbattrs) code] -- Table display math replaceBlock opts scope (Para [Span ats@(label, _, attrs) [Math DisplayMath eq]]) - | not $ isLatexFormat (outFormat opts) - , tableEqns opts + | tableEqns opts , Just pfx <- getRefPrefix opts label <|> autoEqnLabels opts , Just lbl <- autoLabel pfx label = do (eq', idx) <- replaceEqn opts scope lbl attrs eq pfx replaceNoRecurse $ Div ats [Table [] [AlignCenter, AlignRight] [0.9, 0.09] [] [[[Plain [Math DisplayMath eq']], [Plain [Math DisplayMath $ "(" ++ idx ++ ")"]]]]] -- Generic div -replaceBlock opts scope x@(Div ats@(label, _, attrs) content) +replaceBlock opts scope (Div ats@(label, _, attrs) content) | Just pfx <- getRefPrefix opts label = do - let caption + let (caption, content') | not (null content) , Para (Str ":":Space:c) <- last content - = Just $ B.fromList c - | otherwise = Nothing - rec' <- replaceAttr opts scope (Right label) attrs (fromMaybe mempty caption) pfx - replaceRecurse (newScope rec' scope) $ case caption of - Nothing -> x - Just _ -> Div ats . placeCaption opts rec' $ init content + = (B.fromList c, init content) + | otherwise = (mempty, content) + ref <- replaceAttr opts scope (Right label) attrs caption pfx + replaceRecurse (newScope ref scope) $ + Div ats $ placeCaption opts ref content' replaceBlock _ scope _ = noReplaceRecurse scope placeCaption :: Options -> RefRec -> [Block] -> [Block] @@ -167,27 +146,21 @@ replaceInline opts scope (Span ats@(label,_,attrs) [Math DisplayMath eq]) , Just lbl <- autoLabel pfx label = do (eq', _) <- replaceEqn opts scope lbl attrs eq pfx - replaceNoRecurse $ case outFormat opts of - f | isLatexFormat f -> - RawInline (Format "latex") - $ "\\begin{equation}"++eq++mkLaTeXLabel label++"\\end{equation}" - _ -> Span ats [Math DisplayMath eq'] + replaceNoRecurse $ Span ats [Math DisplayMath eq'] replaceInline opts scope (Image attr@(label,_,attrs) alt img@(_, tit)) | Just pfx <- getRefPrefix opts label <|> autoFigLabels opts , Just lbl <- autoLabel pfx label , "fig:" `isPrefixOf` tit = do - let ialt = B.fromList alt - idxStr <- replaceAttr opts scope lbl attrs ialt pfx - let alt' = B.toList $ case outFormat opts of - f | isLatexFormat f -> ialt - _ -> refCaption idxStr - replaceNoRecurse $ Image attr alt' img -replaceInline opts scope (Span (label,_,attrs) content) + RefRec{..} <- replaceAttr opts scope lbl attrs (B.fromList alt) pfx + replaceNoRecurse $ Image attr (B.toList refCaption) img +-- generic span +replaceInline opts scope (Span (label,cls,attrs) content) | Just pfx <- getRefPrefix opts label = do - rec' <- replaceAttr opts scope (Right label) attrs (B.fromList content) pfx - noReplaceRecurse (newScope rec' scope) + ref@RefRec{..} <- replaceAttr opts scope (Right label) attrs (B.fromList content) pfx + replaceRecurse (newScope ref scope) . Span (label, cls, attrs) + . B.toList $ applyTitleTemplate ref replaceInline _opts (scope@RefRec{refPfxRec=Prefix{..}}:_) (Span ("",_,attrs) []) = do rd <- get referenceData let ccd = filter ((== Just scope) . refScope) . M.elems $ rd diff --git a/lib/Text/Pandoc/CrossRef/References/List.hs b/lib/Text/Pandoc/CrossRef/References/List.hs index 2336cda7..b14cf993 100644 --- a/lib/Text/Pandoc/CrossRef/References/List.hs +++ b/lib/Text/Pandoc/CrossRef/References/List.hs @@ -41,16 +41,6 @@ listOf opts (RawBlock fmt cmd:xs) , Just pfxBrace <- "\\listof{" `stripPrefix` cmd , (pfx, "}") <- span (/='}') pfxBrace = getPfxData pfx >>= fmap toList . makeList opts pfx (fromList xs) -listOf Options{outFormat=f} x | isLatexFormat f = return x -listOf opts (RawBlock fmt "\\listoffigures":xs) - | isLaTeXRawBlockFmt fmt - = getPfxData "fig" >>= fmap toList . makeList opts "fig" (fromList xs) -listOf opts (RawBlock fmt "\\listoftables":xs) - | isLaTeXRawBlockFmt fmt - = getPfxData "tbl" >>= fmap toList . makeList opts "tbl" (fromList xs) -listOf opts (RawBlock fmt "\\listoflistings":xs) - | isLaTeXRawBlockFmt fmt - = getPfxData "lst" >>= fmap toList . makeList opts "lst" (fromList xs) listOf _ x = return x getPfxData :: String -> WS RefMap diff --git a/lib/Text/Pandoc/CrossRef/References/Refs.hs b/lib/Text/Pandoc/CrossRef/References/Refs.hs index c3098caf..82927d62 100644 --- a/lib/Text/Pandoc/CrossRef/References/Refs.hs +++ b/lib/Text/Pandoc/CrossRef/References/Refs.hs @@ -64,7 +64,7 @@ replaceRefs opts ils eqPred = (==) `on` liftM2 (,) rdLevel rdPrefix intrclt = intercalate' (text ", ") replaceRefs' (Left xs) = restoreCits' xs - replaceRefs' (Right xs) = intrclt <$> mapM replaceRefs'' (NE.groupBy eqPred xs) + replaceRefs' (Right xs) = intrclt <$> mapM (replaceRefsOther opts) (NE.groupBy eqPred xs) restoreCits' refs = liftM2 cite cits' il' where cits' = mapM getCit refs @@ -80,9 +80,6 @@ replaceRefs opts ils citationToInlines c = fromList (citationPrefix c) <> text ("@" ++ citationId c) <> fromList (citationSuffix c) - replaceRefs'' - | isLatexFormat (outFormat opts) = replaceRefsLatex opts - | otherwise = replaceRefsOther opts replaceRefs _ x = return x getRefPrefix :: Bool -> Int -> RefRec -> Inlines -> Inlines @@ -93,27 +90,6 @@ getRefPrefix capitalize num rr@RefRec{..} cit = vf "n" = Just $ MetaString $ show num vf x = fix defaultVarFunc rr x -replaceRefsLatex :: Options -> NonEmpty RefDataComplete -> WS Inlines -replaceRefsLatex opts cits - | cref opts - = return . rawInline "tex" $ cref'++"{"++listLabels "" "," "" cits++"}" - | otherwise - = intercalate' (text ", ") <$> - mapM replaceRefsLatex' (NE.groupBy citationGroupPred cits) - where - RefDataComplete{rdSuppressPrefix, rdUpperCase} = NE.head cits - cref' | rdSuppressPrefix = "\\labelcref" - | rdUpperCase = "\\Cref" - | otherwise = "\\cref" - -replaceRefsLatex' :: NonEmpty RefDataComplete -> WS Inlines -replaceRefsLatex' cits - = return . writePrefix cits . rawInline "tex" - $ listLabels "\\ref{" ", " "}" cits - -listLabels :: String -> String -> String -> NonEmpty RefDataComplete -> String -listLabels p sep s = intercalate sep . NE.toList . NE.map ((p ++) . (++ s) . mkLaTeXLabel' . rdLabel) - replaceRefsOther :: Options -> NonEmpty RefDataComplete -> WS Inlines replaceRefsOther opts cits = intercalate' (text ", ") <$> mapM (replaceRefsOther' opts) (NE.groupBy citationGroupPred cits) @@ -160,9 +136,6 @@ rdScope RefDataComplete{rdRec} = refScope rdRec rdPrefix :: RefDataComplete -> String rdPrefix RefDataComplete{rdRec} = refPfx rdRec -rdLabel :: RefDataComplete -> String -rdLabel RefDataComplete{rdRec} = refLabel rdRec - rdLevel :: RefDataComplete -> Int rdLevel RefDataComplete{rdRec} = refLevel rdRec diff --git a/lib/Text/Pandoc/CrossRef/References/Subfigures.hs b/lib/Text/Pandoc/CrossRef/References/Subfigures.hs index 4c59ecee..182754b7 100644 --- a/lib/Text/Pandoc/CrossRef/References/Subfigures.hs +++ b/lib/Text/Pandoc/CrossRef/References/Subfigures.hs @@ -87,33 +87,33 @@ toTable blks = [Table [] align widths [] $ map blkToRow blks] inlToCell (Image (id', cs, as) txt tgt) = Just [Para [Image (id', cs, setW as) txt tgt]] inlToCell _ = Nothing setW as = ("width", "100%"):filter ((/="width") . fst) as - -latexSubFigure :: Inline -> String -> [Inline] -latexSubFigure (Image (_, cls, attrs) alt (src, title)) label = - let - title' = fromMaybe title $ stripPrefix "fig:" title - texlabel | null label = [] - | otherwise = [RawInline (Format "latex") $ mkLaTeXLabel label] - texalt | "nocaption" `elem` cls = [] - | otherwise = concat - [ [ RawInline (Format "latex") "["] - , alt - , [ RawInline (Format "latex") "]"] - ] - img = Image (label, cls, attrs) alt (src, title') - in concat [ - [ RawInline (Format "latex") "\\subfloat" ] - , texalt - , [Span nullAttr $ img:texlabel] - ] -latexSubFigure x _ = [x] - -latexEnv :: String -> [Block] -> [Inline] -> String -> Block -latexEnv env contents caption label = - Div (label, [], []) $ - [ RawBlock (Format "latex") $ "\\begin{"<>env<>"}\n\\centering" ] - ++ contents ++ - [ Para [RawInline (Format "latex") "\\caption" - , Span nullAttr caption] - , RawBlock (Format "latex") $ mkLaTeXLabel label - , RawBlock (Format "latex") $ "\\end{"<>env<>"}"] +-- +-- latexSubFigure :: Inline -> String -> [Inline] +-- latexSubFigure (Image (_, cls, attrs) alt (src, title)) label = +-- let +-- title' = fromMaybe title $ stripPrefix "fig:" title +-- texlabel | null label = [] +-- | otherwise = [RawInline (Format "latex") $ mkLaTeXLabel label] +-- texalt | "nocaption" `elem` cls = [] +-- | otherwise = concat +-- [ [ RawInline (Format "latex") "["] +-- , alt +-- , [ RawInline (Format "latex") "]"] +-- ] +-- img = Image (label, cls, attrs) alt (src, title') +-- in concat [ +-- [ RawInline (Format "latex") "\\subfloat" ] +-- , texalt +-- , [Span nullAttr $ img:texlabel] +-- ] +-- latexSubFigure x _ = [x] +-- +-- latexEnv :: String -> [Block] -> [Inline] -> String -> Block +-- latexEnv env contents caption label = +-- Div (label, [], []) $ +-- [ RawBlock (Format "latex") $ "\\begin{"<>env<>"}\n\\centering" ] +-- ++ contents ++ +-- [ Para [RawInline (Format "latex") "\\caption" +-- , Span nullAttr caption] +-- , RawBlock (Format "latex") $ mkLaTeXLabel label +-- , RawBlock (Format "latex") $ "\\end{"<>env<>"}"] diff --git a/lib/Text/Pandoc/CrossRef/Util/ModifyMeta.hs b/lib/Text/Pandoc/CrossRef/Util/ModifyMeta.hs index 6ed0e4d3..4488431e 100644 --- a/lib/Text/Pandoc/CrossRef/Util/ModifyMeta.hs +++ b/lib/Text/Pandoc/CrossRef/Util/ModifyMeta.hs @@ -25,19 +25,16 @@ module Text.Pandoc.CrossRef.Util.ModifyMeta modifyMeta ) where -import Data.List (intercalate) import Text.Pandoc -import Text.Pandoc.Shared (blocksToInlines) import Text.Pandoc.Builder hiding ((<>)) import Text.Pandoc.CrossRef.Util.Options import Text.Pandoc.CrossRef.References.Types import Text.Pandoc.CrossRef.Util.Settings.Types import Text.Pandoc.CrossRef.Util.Util -import qualified Data.Text as T modifyMeta :: CrossRef Meta modifyMeta = do - opts@Options{..} <- asks creOptions + Options{..} <- asks creOptions settings <- asks creSettings let headerInc :: Maybe MetaValue -> MetaValue @@ -46,75 +43,8 @@ modifyMeta = do headerInc (Just x) = MetaList [x, incList] incList = MetaBlocks $ return $ RawBlock (Format "latex") $ unlines $ execWriter $ do tell [ "\\makeatletter" ] - tell subfig - tell floatnames - tell listnames - unless listings $ - tell codelisting - tell lolcommand - when cref $ do - tell cleveref - unless listings $ - tell cleverefCodelisting + tell [ "\\@ifpackageloaded{caption}{\\captionsetup{labelformat=empty}}{\\usepackage[labelformat=empty]{caption}}" ] tell [ "\\makeatother" ] - subfig = [ - usepackage [] "subfig" - , usepackage [] "caption" - , "\\captionsetup[subfloat]{margin=0.5em}" - ] - floatnames = [ - "\\AtBeginDocument{%" - , "\\renewcommand*\\figurename{"++getFloatCaption "fig"++"}" - , "\\renewcommand*\\tablename{"++getFloatCaption "tbl"++"}" - , "}" - ] - listnames = [ - "\\AtBeginDocument{%" - , "\\renewcommand*\\listfigurename{"++getListOfTitle "fig"++"}" - , "\\renewcommand*\\listtablename{"++getListOfTitle "tbl"++"}" - , "}" - ] - codelisting = [ - usepackage [] "float" - , "\\floatstyle{ruled}" - , "\\@ifundefined{c@chapter}{\\newfloat{codelisting}{h}{lop}}{\\newfloat{codelisting}{h}{lop}[chapter]}" - , "\\floatname{codelisting}{"++getFloatCaption "lst"++"}" - ] - lolcommand - | listings = [ - "\\newcommand*\\listoflistings\\lstlistoflistings" - , "\\AtBeginDocument{%" - , "\\renewcommand*{\\lstlistlistingname}{"++getListOfTitle "lst"++"}" - , "}" - ] - | otherwise = ["\\newcommand*\\listoflistings{\\listof{codelisting}{"++getListOfTitle "lst"++"}}"] - cleveref = [ usepackage cleverefOpts "cleveref" ] - -- <> crefname "figure" (pfxRef "fig") - -- <> crefname "table" (pfxRef "tbl") - -- <> crefname "equation" (pfxRef "eq") - -- <> crefname "listing" (pfxRef "lst") - -- <> crefname "section" (pfxRef "sec") - -- pfxRef labelPrefix = prefixRef . flip getPfx labelPrefix - cleverefCodelisting = [ - "\\crefname{codelisting}{\\cref@listing@name}{\\cref@listing@name@plural}" - , "\\Crefname{codelisting}{\\Cref@listing@name}{\\Cref@listing@name@plural}" - ] - cleverefOpts | nameInLink = [ "nameinlink" ] - | otherwise = [] - -- crefname n f = [ - -- "\\crefname{" ++ n ++ "}" ++ prefix f False - -- , "\\Crefname{" ++ n ++ "}" ++ prefix f True - -- ] - usepackage [] p = "\\@ifpackageloaded{"++p++"}{}{\\usepackage{"++p++"}}" - usepackage xs p = "\\@ifpackageloaded{"++p++"}{}{\\usepackage"++o++"{"++p++"}}" - where o = "[" ++ intercalate "," xs ++ "]" - toLatex = either (error . show) T.unpack . runPure . writeLaTeX def . Pandoc nullMeta . return . Plain - -- TODO: Log - getListOfTitle = either (const mempty) (toLatex . blocksToInlines . toList) . getTitleForListOf opts - getFloatCaption = const mempty - -- prefix f uc = "{" ++ toLatex (toList $ f opts uc 0) ++ "}" ++ - -- "{" ++ toLatex (toList $ f opts uc 1) ++ "}" - return $ if isLatexFormat outFormat then setMeta "header-includes" (headerInc $ lookupSettings "header-includes" settings) diff --git a/lib/Text/Pandoc/CrossRef/Util/Options/Types.hs b/lib/Text/Pandoc/CrossRef/Util/Options/Types.hs index 1a1566cb..3bcb700c 100644 --- a/lib/Text/Pandoc/CrossRef/Util/Options/Types.hs +++ b/lib/Text/Pandoc/CrossRef/Util/Options/Types.hs @@ -23,9 +23,7 @@ import Text.Pandoc.Definition import Text.Pandoc.CrossRef.Util.Prefixes import Text.Pandoc.Builder -data Options = Options { cref :: Bool - , listings :: Bool - , codeBlockCaptions :: Bool +data Options = Options { codeBlockCaptions :: Bool , autoSectionLabels :: Maybe String , defaultSectionPrefix :: String , rangeDelim :: Inlines diff --git a/lib/Text/Pandoc/CrossRef/Util/Settings.hs b/lib/Text/Pandoc/CrossRef/Util/Settings.hs index 97bac4aa..7f9b9020 100644 --- a/lib/Text/Pandoc/CrossRef/Util/Settings.hs +++ b/lib/Text/Pandoc/CrossRef/Util/Settings.hs @@ -59,9 +59,7 @@ readSettings fmt inMeta = do defaultMeta :: Settings defaultMeta = Settings $ - cref False - <> listings False - <> codeBlockCaptions False + codeBlockCaptions False <> defaultSectionPrefix "sec" <> titleDelim (str ":" <> space) <> listItemNumberDelim (str "." <> space) diff --git a/lib/Text/Pandoc/CrossRef/Util/Util.hs b/lib/Text/Pandoc/CrossRef/Util/Util.hs index 052bdbc4..ce699252 100644 --- a/lib/Text/Pandoc/CrossRef/Util/Util.hs +++ b/lib/Text/Pandoc/CrossRef/Util/Util.hs @@ -18,7 +18,7 @@ with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -} -{-# LANGUAGE FlexibleContexts, Rank2Types #-} +{-# LANGUAGE FlexibleContexts, RecordWildCards #-} module Text.Pandoc.CrossRef.Util.Util where import Text.Pandoc.CrossRef.References.Types.Ref diff --git a/pandoc-crossref.cabal b/pandoc-crossref.cabal index 2c82c6cf..609b0123 100644 --- a/pandoc-crossref.cabal +++ b/pandoc-crossref.cabal @@ -4,7 +4,7 @@ cabal-version: 1.12 -- -- see: https://github.com/sol/hpack -- --- hash: dc05cfedfed6de367d50b717064291868887b68c7cb98c5bd0db3e93e4b1c700 +-- hash: a722e828c9b63f37754f36f155ac6cec7d4a7d0fb0e3897dd14d6cc3aa54f0d6 name: pandoc-crossref version: 0.4.0.0 @@ -26,73 +26,50 @@ data-files: docs/demo/demo.md docs/index.md test/m2m/capitalization/expect.md - test/m2m/capitalization/expect.tex test/m2m/capitalization/input.md test/m2m/custom-prefixes/expect.md - test/m2m/custom-prefixes/expect.tex test/m2m/custom-prefixes/input.md test/m2m/delim/expect.md - test/m2m/delim/expect.tex test/m2m/delim/input.md test/m2m/equations-auto/expect.md - test/m2m/equations-auto/expect.tex test/m2m/equations-auto/input.md test/m2m/equations-tables-auto/expect.md - test/m2m/equations-tables-auto/expect.tex test/m2m/equations-tables-auto/input.md test/m2m/equations-tables/expect.md - test/m2m/equations-tables/expect.tex test/m2m/equations-tables/input.md test/m2m/equations/expect.md - test/m2m/equations/expect.tex test/m2m/equations/input.md test/m2m/links-names/expect.md - test/m2m/links-names/expect.tex test/m2m/links-names/input.md test/m2m/links/expect.md - test/m2m/links/expect.tex test/m2m/links/input.md test/m2m/list-of/expect.md - test/m2m/list-of/expect.tex test/m2m/list-of/input.md test/m2m/listing-captions-ids/expect.md - test/m2m/listing-captions-ids/expect.tex test/m2m/listing-captions-ids/input.md test/m2m/numbering-parts/expect.md - test/m2m/numbering-parts/expect.tex test/m2m/numbering-parts/input.md test/m2m/ref-attrs/expect.md - test/m2m/ref-attrs/expect.tex test/m2m/ref-attrs/input.md test/m2m/regresssion-219/expect.md - test/m2m/regresssion-219/expect.tex test/m2m/regresssion-219/input.md test/m2m/scoping/expect.md - test/m2m/scoping/expect.tex test/m2m/scoping/input.md test/m2m/section-template/expect.md - test/m2m/section-template/expect.tex test/m2m/section-template/input.md test/m2m/subfigures-ccsDelim/expect.md - test/m2m/subfigures-ccsDelim/expect.tex test/m2m/subfigures-ccsDelim/input.md test/m2m/subfigures-grid/expect.md - test/m2m/subfigures-grid/expect.tex test/m2m/subfigures-grid/input.md test/m2m/subfigures-template-collect/expect.md - test/m2m/subfigures-template-collect/expect.tex test/m2m/subfigures-template-collect/input.md test/m2m/subfigures/expect.md - test/m2m/subfigures/expect.tex test/m2m/subfigures/input.md test/m2m/template-objects/expect.md - test/m2m/template-objects/expect.tex test/m2m/template-objects/input.md test/m2m/template-options/expect.md - test/m2m/template-options/expect.tex test/m2m/template-options/input.md test/m2m/undefined-prefix/expect.md - test/m2m/undefined-prefix/expect.tex test/m2m/undefined-prefix/input.md source-repository head diff --git a/test/m2m/capitalization/expect.tex b/test/m2m/capitalization/expect.tex deleted file mode 100644 index 855d9900..00000000 --- a/test/m2m/capitalization/expect.tex +++ /dev/null @@ -1,36 +0,0 @@ -\begin{equation}eqn\label{eq:1}\end{equation} - -\begin{figure} -\hypertarget{fig:1}{% -\centering -\includegraphics{img.png} -\caption{Image}\label{fig:1} -} -\end{figure} - -\hypertarget{tbl:1}{} -\begin{longtable}[]{@{}ll@{}} -\caption{\label{tbl:1}Table}\tabularnewline -\toprule -a & b\tabularnewline -\midrule -\endfirsthead -\toprule -a & b\tabularnewline -\midrule -\endhead -c & d\tabularnewline -\bottomrule -\end{longtable} - -eq.~\ref{eq:1}, Eq.~\ref{eq:1}, fig.~\ref{fig:1}, Fig.~\ref{fig:1}, -tbl.~\ref{tbl:1}, Tbl.~\ref{tbl:1} - -eq.~\ref{eq:1}, Eq.~\ref{eq:1}, fig.~\ref{fig:1}, Fig.~\ref{fig:1}, -tbl.~\ref{tbl:1}, Tbl.~\ref{tbl:1} - -eqs.~\ref{eq:1}, \ref{eq:1}, figs.~\ref{fig:1}, \ref{fig:1}, -tbls.~\ref{tbl:1}, \ref{tbl:1} - -Eqs.~\ref{eq:1}, \ref{eq:1}, Figs.~\ref{fig:1}, \ref{fig:1}, -Tbls.~\ref{tbl:1}, \ref{tbl:1} diff --git a/test/m2m/custom-prefixes/expect.md b/test/m2m/custom-prefixes/expect.md index 2a63f562..39407cb2 100644 --- a/test/m2m/custom-prefixes/expect.md +++ b/test/m2m/custom-prefixes/expect.md @@ -1,9 +1,11 @@ ::: {#dfn:ring} A *ring* is a triple $(R,+,*)$ satisfying: -1. [$+$ is an abelian group]{#cl:addgp} -2. [$*$ is a monoid]{#cl:multmon} -3. [$*$ distributes over $+$]{#cl:distrib} +1. [1: $+$ is an abelian group]{#cl:addgp} +2. [2: $*$ is a monoid]{#cl:multmon} +3. [3: $*$ distributes over $+$]{#cl:distrib} + +Definition 1: ::: cl. 1, cl. 3, dfn. 1 diff --git a/test/m2m/custom-prefixes/expect.tex b/test/m2m/custom-prefixes/expect.tex deleted file mode 100644 index ca7e6579..00000000 --- a/test/m2m/custom-prefixes/expect.tex +++ /dev/null @@ -1,14 +0,0 @@ -\leavevmode\hypertarget{dfn:ring}{}% -A \emph{ring} is a triple \((R,+,*)\) satisfying: - -\begin{enumerate} -\tightlist -\item - \protect\hypertarget{cl:addgp}{}{\(+\) is an abelian group} -\item - \protect\hypertarget{cl:multmon}{}{\(*\) is a monoid} -\item - \protect\hypertarget{cl:distrib}{}{\(*\) distributes over \(+\)} -\end{enumerate} - -cl.~\ref{cl:addgp}, cl.~\ref{cl:distrib}, dfn.~\ref{dfn:ring} diff --git a/test/m2m/delim/expect.tex b/test/m2m/delim/expect.tex deleted file mode 100644 index 832eb2c5..00000000 --- a/test/m2m/delim/expect.tex +++ /dev/null @@ -1,49 +0,0 @@ -This is a test file with some referenced equations, line \[ this \] - -Some equations might be inside of text, \[ for example \] this one. - -Some equations might be on start of paragraphs: - -\[ start \] of paragraph. - -Other might be on separate paragraphs of their own: - -\[ separate \] - -Some of those can be labelled: - -This is a test file with some referenced equations, line -\begin{equation} this \label{eq:0}\end{equation} - -Some equations might be inside of text, -\begin{equation} for example \label{eq:1}\end{equation} this one. - -Some equations might be on start of paragraphs: - -\begin{equation} start \label{eq:2}\end{equation} of paragraph. - -Other might be on separate paragraphs of their own: - -\begin{equation} separate \label{eq:3}\end{equation} - -Then they can be referenced: - -Individually eq.~\ref{eq:0}, eq.~\ref{eq:1}, eq.~\ref{eq:2}, -eq.~\ref{eq:3} - -Or in groups eqns.~\ref{eq:0}, \ref{eq:1}, \ref{eq:3} - -Groups will be compacted -eqns.~\ref{eq:0}, \ref{eq:1}, \ref{eq:3}, \ref{eq:2} - -Unknown references will print labels eq.~\ref{eq:0}, {[}@eq:none{]}, -eqns.~\ref{eq:3}, \ref{eq:2} - -Reference prefix will override default prefix Equation \ref{eq:0}, -eqns.~\ref{eq:3}, \ref{eq:2} - -References with \texttt{-} prepended won't have prefix at all: -\ref{eq:0}, \ref{eq:1}, eqns.~\ref{eq:2}, \ref{eq:3} - -References with suffix will have suffix printed after index -(configurable): eqns.~\ref{eq:0}, \ref{eq:1}, \ref{eq:2} diff --git a/test/m2m/equations-auto/expect.tex b/test/m2m/equations-auto/expect.tex deleted file mode 100644 index c8a545be..00000000 --- a/test/m2m/equations-auto/expect.tex +++ /dev/null @@ -1,39 +0,0 @@ -This is a test file with some referenced equations, line -\begin{equation} this \end{equation} - -Some equations might be inside of text, -\begin{equation} for example \end{equation} this one. - -Some equations might be on start of paragraphs: - -\begin{equation} start \end{equation} of paragraph. - -Other might be on separate paragraphs of their own: - -\begin{equation} separate \end{equation} - -Some of those can be labelled: - -This is a test file with some referenced equations, line -\begin{equation} this \label{eq:0}\end{equation} - -Some equations might be inside of text, -\begin{equation} for example \label{eq:1}\end{equation} this one. - -Some equations might be on start of paragraphs: - -\begin{equation} start \label{eq:2}\end{equation} of paragraph. - -Other might be on separate paragraphs of their own: - -\begin{equation} separate \label{eq:3}\end{equation} - -Then they can be referenced: - -Individually eq.~\ref{eq:0}, eq.~\ref{eq:1}, eq.~\ref{eq:2}, -eq.~\ref{eq:3} - -Or in groups eqns.~\ref{eq:0}, \ref{eq:1}, \ref{eq:3} - -Groups will be compacted -eqns.~\ref{eq:0}, \ref{eq:1}, \ref{eq:3}, \ref{eq:2} diff --git a/test/m2m/equations-tables-auto/expect.tex b/test/m2m/equations-tables-auto/expect.tex deleted file mode 100644 index c8a545be..00000000 --- a/test/m2m/equations-tables-auto/expect.tex +++ /dev/null @@ -1,39 +0,0 @@ -This is a test file with some referenced equations, line -\begin{equation} this \end{equation} - -Some equations might be inside of text, -\begin{equation} for example \end{equation} this one. - -Some equations might be on start of paragraphs: - -\begin{equation} start \end{equation} of paragraph. - -Other might be on separate paragraphs of their own: - -\begin{equation} separate \end{equation} - -Some of those can be labelled: - -This is a test file with some referenced equations, line -\begin{equation} this \label{eq:0}\end{equation} - -Some equations might be inside of text, -\begin{equation} for example \label{eq:1}\end{equation} this one. - -Some equations might be on start of paragraphs: - -\begin{equation} start \label{eq:2}\end{equation} of paragraph. - -Other might be on separate paragraphs of their own: - -\begin{equation} separate \label{eq:3}\end{equation} - -Then they can be referenced: - -Individually eq.~\ref{eq:0}, eq.~\ref{eq:1}, eq.~\ref{eq:2}, -eq.~\ref{eq:3} - -Or in groups eqns.~\ref{eq:0}, \ref{eq:1}, \ref{eq:3} - -Groups will be compacted -eqns.~\ref{eq:0}, \ref{eq:1}, \ref{eq:3}, \ref{eq:2} diff --git a/test/m2m/equations-tables/expect.tex b/test/m2m/equations-tables/expect.tex deleted file mode 100644 index b2b7d18a..00000000 --- a/test/m2m/equations-tables/expect.tex +++ /dev/null @@ -1,37 +0,0 @@ -This is a test file with some referenced equations, line \[ this \] - -Some equations might be inside of text, \[ for example \] this one. - -Some equations might be on start of paragraphs: - -\[ start \] of paragraph. - -Other might be on separate paragraphs of their own: - -\[ separate \] - -Some of those can be labelled: - -This is a test file with some referenced equations, line -\begin{equation} this \label{eq:0}\end{equation} - -Some equations might be inside of text, -\begin{equation} for example \label{eq:1}\end{equation} this one. - -Some equations might be on start of paragraphs: - -\begin{equation} start \label{eq:2}\end{equation} of paragraph. - -Other might be on separate paragraphs of their own: - -\begin{equation} separate \label{eq:3}\end{equation} - -Then they can be referenced: - -Individually eq.~\ref{eq:0}, eq.~\ref{eq:1}, eq.~\ref{eq:2}, -eq.~\ref{eq:3} - -Or in groups eqns.~\ref{eq:0}, \ref{eq:1}, \ref{eq:3} - -Groups will be compacted -eqns.~\ref{eq:0}, \ref{eq:1}, \ref{eq:3}, \ref{eq:2} diff --git a/test/m2m/equations/expect.tex b/test/m2m/equations/expect.tex deleted file mode 100644 index 832eb2c5..00000000 --- a/test/m2m/equations/expect.tex +++ /dev/null @@ -1,49 +0,0 @@ -This is a test file with some referenced equations, line \[ this \] - -Some equations might be inside of text, \[ for example \] this one. - -Some equations might be on start of paragraphs: - -\[ start \] of paragraph. - -Other might be on separate paragraphs of their own: - -\[ separate \] - -Some of those can be labelled: - -This is a test file with some referenced equations, line -\begin{equation} this \label{eq:0}\end{equation} - -Some equations might be inside of text, -\begin{equation} for example \label{eq:1}\end{equation} this one. - -Some equations might be on start of paragraphs: - -\begin{equation} start \label{eq:2}\end{equation} of paragraph. - -Other might be on separate paragraphs of their own: - -\begin{equation} separate \label{eq:3}\end{equation} - -Then they can be referenced: - -Individually eq.~\ref{eq:0}, eq.~\ref{eq:1}, eq.~\ref{eq:2}, -eq.~\ref{eq:3} - -Or in groups eqns.~\ref{eq:0}, \ref{eq:1}, \ref{eq:3} - -Groups will be compacted -eqns.~\ref{eq:0}, \ref{eq:1}, \ref{eq:3}, \ref{eq:2} - -Unknown references will print labels eq.~\ref{eq:0}, {[}@eq:none{]}, -eqns.~\ref{eq:3}, \ref{eq:2} - -Reference prefix will override default prefix Equation \ref{eq:0}, -eqns.~\ref{eq:3}, \ref{eq:2} - -References with \texttt{-} prepended won't have prefix at all: -\ref{eq:0}, \ref{eq:1}, eqns.~\ref{eq:2}, \ref{eq:3} - -References with suffix will have suffix printed after index -(configurable): eqns.~\ref{eq:0}, \ref{eq:1}, \ref{eq:2} diff --git a/test/m2m/links-names/expect.tex b/test/m2m/links-names/expect.tex deleted file mode 100644 index 832eb2c5..00000000 --- a/test/m2m/links-names/expect.tex +++ /dev/null @@ -1,49 +0,0 @@ -This is a test file with some referenced equations, line \[ this \] - -Some equations might be inside of text, \[ for example \] this one. - -Some equations might be on start of paragraphs: - -\[ start \] of paragraph. - -Other might be on separate paragraphs of their own: - -\[ separate \] - -Some of those can be labelled: - -This is a test file with some referenced equations, line -\begin{equation} this \label{eq:0}\end{equation} - -Some equations might be inside of text, -\begin{equation} for example \label{eq:1}\end{equation} this one. - -Some equations might be on start of paragraphs: - -\begin{equation} start \label{eq:2}\end{equation} of paragraph. - -Other might be on separate paragraphs of their own: - -\begin{equation} separate \label{eq:3}\end{equation} - -Then they can be referenced: - -Individually eq.~\ref{eq:0}, eq.~\ref{eq:1}, eq.~\ref{eq:2}, -eq.~\ref{eq:3} - -Or in groups eqns.~\ref{eq:0}, \ref{eq:1}, \ref{eq:3} - -Groups will be compacted -eqns.~\ref{eq:0}, \ref{eq:1}, \ref{eq:3}, \ref{eq:2} - -Unknown references will print labels eq.~\ref{eq:0}, {[}@eq:none{]}, -eqns.~\ref{eq:3}, \ref{eq:2} - -Reference prefix will override default prefix Equation \ref{eq:0}, -eqns.~\ref{eq:3}, \ref{eq:2} - -References with \texttt{-} prepended won't have prefix at all: -\ref{eq:0}, \ref{eq:1}, eqns.~\ref{eq:2}, \ref{eq:3} - -References with suffix will have suffix printed after index -(configurable): eqns.~\ref{eq:0}, \ref{eq:1}, \ref{eq:2} diff --git a/test/m2m/links/expect.tex b/test/m2m/links/expect.tex deleted file mode 100644 index 832eb2c5..00000000 --- a/test/m2m/links/expect.tex +++ /dev/null @@ -1,49 +0,0 @@ -This is a test file with some referenced equations, line \[ this \] - -Some equations might be inside of text, \[ for example \] this one. - -Some equations might be on start of paragraphs: - -\[ start \] of paragraph. - -Other might be on separate paragraphs of their own: - -\[ separate \] - -Some of those can be labelled: - -This is a test file with some referenced equations, line -\begin{equation} this \label{eq:0}\end{equation} - -Some equations might be inside of text, -\begin{equation} for example \label{eq:1}\end{equation} this one. - -Some equations might be on start of paragraphs: - -\begin{equation} start \label{eq:2}\end{equation} of paragraph. - -Other might be on separate paragraphs of their own: - -\begin{equation} separate \label{eq:3}\end{equation} - -Then they can be referenced: - -Individually eq.~\ref{eq:0}, eq.~\ref{eq:1}, eq.~\ref{eq:2}, -eq.~\ref{eq:3} - -Or in groups eqns.~\ref{eq:0}, \ref{eq:1}, \ref{eq:3} - -Groups will be compacted -eqns.~\ref{eq:0}, \ref{eq:1}, \ref{eq:3}, \ref{eq:2} - -Unknown references will print labels eq.~\ref{eq:0}, {[}@eq:none{]}, -eqns.~\ref{eq:3}, \ref{eq:2} - -Reference prefix will override default prefix Equation \ref{eq:0}, -eqns.~\ref{eq:3}, \ref{eq:2} - -References with \texttt{-} prepended won't have prefix at all: -\ref{eq:0}, \ref{eq:1}, eqns.~\ref{eq:2}, \ref{eq:3} - -References with suffix will have suffix printed after index -(configurable): eqns.~\ref{eq:0}, \ref{eq:1}, \ref{eq:2} diff --git a/test/m2m/list-of/expect.md b/test/m2m/list-of/expect.md index 925fb249..4331df02 100644 --- a/test/m2m/list-of/expect.md +++ b/test/m2m/list-of/expect.md @@ -64,24 +64,5 @@ List of Tables 3\. Table 3 ::: -List of Figures -=============== - -::: {.list} -1\. Image 1 - -2\. Image 2 - -3\. Image 3 -::: - -List of Tables -============== - -::: {.list} -1\. Table 1 - -2\. Table 2 - -3\. Table 3 -::: +\listoffigures +\listoftables diff --git a/test/m2m/list-of/expect.tex b/test/m2m/list-of/expect.tex deleted file mode 100644 index 85efe989..00000000 --- a/test/m2m/list-of/expect.tex +++ /dev/null @@ -1,100 +0,0 @@ -\begin{equation}eqn1\label{eq:1}\end{equation} -\begin{equation}eqn2\label{eq:2}\end{equation} -\begin{equation}eqn3\label{eq:3}\end{equation} - -\begin{figure} -\hypertarget{fig:1}{% -\centering -\includegraphics{img.png} -\caption{Image 1}\label{fig:1} -} -\end{figure} - -\begin{figure} -\hypertarget{fig:2}{% -\centering -\includegraphics{img.png} -\caption{Image 2}\label{fig:2} -} -\end{figure} - -\begin{figure} -\hypertarget{fig:3}{% -\centering -\includegraphics{img.png} -\caption{Image 3}\label{fig:3} -} -\end{figure} - -\hypertarget{tbl:1}{} -\begin{longtable}[]{@{}ll@{}} -\caption{\label{tbl:1}Table 1}\tabularnewline -\toprule -a & b\tabularnewline -\midrule -\endfirsthead -\toprule -a & b\tabularnewline -\midrule -\endhead -c & d\tabularnewline -\bottomrule -\end{longtable} - -\hypertarget{tbl:2}{} -\begin{longtable}[]{@{}ll@{}} -\caption{\label{tbl:2}Table 2}\tabularnewline -\toprule -a & b\tabularnewline -\midrule -\endfirsthead -\toprule -a & b\tabularnewline -\midrule -\endhead -c & d\tabularnewline -\bottomrule -\end{longtable} - -\hypertarget{tbl:3}{} -\begin{longtable}[]{@{}ll@{}} -\caption{\label{tbl:3}Table 3}\tabularnewline -\toprule -a & b\tabularnewline -\midrule -\endfirsthead -\toprule -a & b\tabularnewline -\midrule -\endhead -c & d\tabularnewline -\bottomrule -\end{longtable} - -\section{List of Figures} - -1. Image 1 - -2. Image 2 - -3. Image 3 - -\section{List of Equations} - -1. \(eqn1\) - -2. \(eqn2\) - -3. \(eqn3\) - -\section{List of Tables} - -1. Table 1 - -2. Table 2 - -3. Table 3 - -\listoffigures - -\listoftables diff --git a/test/m2m/listing-captions-ids/expect.tex b/test/m2m/listing-captions-ids/expect.tex deleted file mode 100644 index a4a4127c..00000000 --- a/test/m2m/listing-captions-ids/expect.tex +++ /dev/null @@ -1,162 +0,0 @@ -After code block - -\begin{codelisting} - -\caption{Listing caption 1} - -\hypertarget{lst:code1}{% -\label{lst:code1}}% -\begin{Shaded} -\begin{Highlighting}[] -\OtherTok{main ::} \DataTypeTok{IO}\NormalTok{ ()} -\NormalTok{main }\OtherTok{=} \FunctionTok{putStrLn} \StringTok{"Hello World!"} -\end{Highlighting} -\end{Shaded} - -\end{codelisting} - -\begin{codelisting} - -\caption{Listing caption 2} - -\hypertarget{lst:code2}{% -\label{lst:code2}}% -\begin{Shaded} -\begin{Highlighting}[] -\OtherTok{main ::} \DataTypeTok{IO}\NormalTok{ ()} -\NormalTok{main }\OtherTok{=} \FunctionTok{putStrLn} \StringTok{"Hello World!"} -\end{Highlighting} -\end{Shaded} - -\end{codelisting} - -\begin{codelisting} - -\caption{Listing caption 3} - -\hypertarget{lst:code3}{% -\label{lst:code3}}% -\begin{Shaded} -\begin{Highlighting}[] -\OtherTok{main ::} \DataTypeTok{IO}\NormalTok{ ()} -\NormalTok{main }\OtherTok{=} \FunctionTok{putStrLn} \StringTok{"Hello World!"} -\end{Highlighting} -\end{Shaded} - -\end{codelisting} - -\begin{codelisting} - -\caption{Listing caption 4} - -\hypertarget{lst:code4}{% -\label{lst:code4}}% -\begin{Shaded} -\begin{Highlighting}[] -\OtherTok{main ::} \DataTypeTok{IO}\NormalTok{ ()} -\NormalTok{main }\OtherTok{=} \FunctionTok{putStrLn} \StringTok{"Hello World!"} -\end{Highlighting} -\end{Shaded} - -\end{codelisting} - -\begin{Shaded} -\begin{Highlighting}[] -\OtherTok{main ::} \DataTypeTok{IO}\NormalTok{ ()} -\NormalTok{main }\OtherTok{=} \FunctionTok{putStrLn} \StringTok{"Hello World!"} -\end{Highlighting} -\end{Shaded} - -: Listing caption 5 (invalid) - -\begin{Shaded} -\begin{Highlighting}[] -\OtherTok{main ::} \DataTypeTok{IO}\NormalTok{ ()} -\NormalTok{main }\OtherTok{=} \FunctionTok{putStrLn} \StringTok{"Hello World!"} -\end{Highlighting} -\end{Shaded} - -: Listing caption 6 (invalid) - -Before code block - -\begin{codelisting} - -\caption{Listing caption 11} - -\hypertarget{lst:code11}{% -\label{lst:code11}}% -\begin{Shaded} -\begin{Highlighting}[] -\OtherTok{main ::} \DataTypeTok{IO}\NormalTok{ ()} -\NormalTok{main }\OtherTok{=} \FunctionTok{putStrLn} \StringTok{"Hello World!"} -\end{Highlighting} -\end{Shaded} - -\end{codelisting} - -\begin{codelisting} - -\caption{Listing caption 12} - -\hypertarget{lst:code12}{% -\label{lst:code12}}% -\begin{Shaded} -\begin{Highlighting}[] -\OtherTok{main ::} \DataTypeTok{IO}\NormalTok{ ()} -\NormalTok{main }\OtherTok{=} \FunctionTok{putStrLn} \StringTok{"Hello World!"} -\end{Highlighting} -\end{Shaded} - -\end{codelisting} - -\begin{codelisting} - -\caption{Listing caption 13} - -\hypertarget{lst:code13}{% -\label{lst:code13}}% -\begin{Shaded} -\begin{Highlighting}[] -\OtherTok{main ::} \DataTypeTok{IO}\NormalTok{ ()} -\NormalTok{main }\OtherTok{=} \FunctionTok{putStrLn} \StringTok{"Hello World!"} -\end{Highlighting} -\end{Shaded} - -\end{codelisting} - -\begin{codelisting} - -\caption{Listing caption 14} - -\hypertarget{lst:code14}{% -\label{lst:code14}}% -\begin{Shaded} -\begin{Highlighting}[] -\OtherTok{main ::} \DataTypeTok{IO}\NormalTok{ ()} -\NormalTok{main }\OtherTok{=} \FunctionTok{putStrLn} \StringTok{"Hello World!"} -\end{Highlighting} -\end{Shaded} - -\end{codelisting} - -\begin{center}\rule{0.5\linewidth}{\linethickness}\end{center} - -: Listing caption 15 (invalid) - -\begin{Shaded} -\begin{Highlighting}[] -\OtherTok{main ::} \DataTypeTok{IO}\NormalTok{ ()} -\NormalTok{main }\OtherTok{=} \FunctionTok{putStrLn} \StringTok{"Hello World!"} -\end{Highlighting} -\end{Shaded} - -: Listing caption 16 (invalid) - -\begin{Shaded} -\begin{Highlighting}[] -\OtherTok{main ::} \DataTypeTok{IO}\NormalTok{ ()} -\NormalTok{main }\OtherTok{=} \FunctionTok{putStrLn} \StringTok{"Hello World!"} -\end{Highlighting} -\end{Shaded} - diff --git a/test/m2m/numbering-parts/expect.tex b/test/m2m/numbering-parts/expect.tex deleted file mode 100644 index b8bcaec2..00000000 --- a/test/m2m/numbering-parts/expect.tex +++ /dev/null @@ -1,34 +0,0 @@ -\hypertarget{prt:prt1}{% -\section{I. First part}\label{prt:prt1}} - -\hypertarget{sec:cha1}{% -\subsection{1. First chapter}\label{sec:cha1}} - -\hypertarget{sec:cha2}{% -\subsection{2. Second chapter}\label{sec:cha2}} - -\hypertarget{sec:sec21}{% -\subsubsection{2.1. A section}\label{sec:sec21}} - -\hypertarget{sec:sec22}{% -\subsubsection{2.2. Another section}\label{sec:sec22}} - -\hypertarget{prt:prt2}{% -\section{II. Second part}\label{prt:prt2}} - -\hypertarget{sec:cha3}{% -\subsection{3. Third chapter}\label{sec:cha3}} - -prt.~\ref{prt:prt1}; - -chp.~\ref{sec:cha1}; - -chp.~\ref{sec:cha2}; - -sec.~\ref{sec:sec21}; - -sec.~\ref{sec:sec22}; - -prt.~\ref{prt:prt2}; - -chp.~\ref{sec:cha3}; diff --git a/test/m2m/ref-attrs/expect.tex b/test/m2m/ref-attrs/expect.tex deleted file mode 100644 index f94ec9a4..00000000 --- a/test/m2m/ref-attrs/expect.tex +++ /dev/null @@ -1,52 +0,0 @@ -\begin{figure} -\hypertarget{fig:1}{% -\centering -\includegraphics{img.png} -\caption{Image 1}\label{fig:1} -} -\end{figure} - -\begin{figure} -\hypertarget{fig:2}{% -\centering -\includegraphics{img.png} -\caption{Image 2}\label{fig:2} -} -\end{figure} - -\begin{figure} -\hypertarget{fig:3}{% -\centering -\includegraphics{img.png} -\caption{Image 3}\label{fig:3} -} -\end{figure} - -This should have custom prefix: img.~\ref{fig:1} - -This should have custom prefix: img.~\ref{fig:2} - -This should have normal prefix: fig.~\ref{fig:3} - -This should have custom prefix: imgs.~\ref{fig:1}, \ref{fig:2} - -This should have custom prefix: -imgs.~\ref{fig:1}, \ref{fig:2}, \ref{fig:3} - -This should have normal prefix: -figs.~\ref{fig:3}, \ref{fig:1}, \ref{fig:2} - -This should have custom prefix (capitalized): Img.~\ref{fig:1} - -This should have custom prefix (capitalized): Img.~\ref{fig:2} - -This should have normal prefix (capitalized): Fig.~\ref{fig:3} - -This should have custom prefix (capitalized): -Imgs.~\ref{fig:1}, \ref{fig:2} - -This should have custom prefix (capitalized): -Imgs.~\ref{fig:1}, \ref{fig:2}, \ref{fig:3} - -This should have normal prefix (capitalized): -Figs.~\ref{fig:3}, \ref{fig:1}, \ref{fig:2} diff --git a/test/m2m/regresssion-219/expect.tex b/test/m2m/regresssion-219/expect.tex deleted file mode 100644 index dba69aae..00000000 --- a/test/m2m/regresssion-219/expect.tex +++ /dev/null @@ -1,2 +0,0 @@ -A citation starting with ``fig'', like {[}@Figueroa2012-tu{]} should not -be interpreted as a reference. diff --git a/test/m2m/scoping/expect.md b/test/m2m/scoping/expect.md index ee8d576d..1198b535 100644 --- a/test/m2m/scoping/expect.md +++ b/test/m2m/scoping/expect.md @@ -7,7 +7,9 @@ Section 1.1. Section 1.1 {#sec:11} ::: {#dfn:group} A *group* is a pair $(R,*)$ satisfying: -1. [$*$ is a monoid]{#cl:grpmul} +1. [1: $*$ is a monoid]{#cl:grpmul} + +Definition 1: ::: Chapter 2. Section 2 {#sec:2} @@ -23,9 +25,11 @@ Section 2.1. Section 2.1 {#sec:21} ::: {#dfn:ring} A *ring* is a triple $(R,+,*)$ satisfying: -1. [$+$ is an abelian group]{#cl:addgp} -2. [$*$ is a monoid]{#cl:multmon} -3. [$*$ distributes over $+$]{#cl:distrib} +1. [1: $+$ is an abelian group]{#cl:addgp} +2. [2: $*$ is a monoid]{#cl:multmon} +3. [3: $*$ distributes over $+$]{#cl:distrib} + +Definition 1: ::: Chapter 3. Section 3 {#section-3} diff --git a/test/m2m/scoping/expect.tex b/test/m2m/scoping/expect.tex deleted file mode 100644 index 8319db4b..00000000 --- a/test/m2m/scoping/expect.tex +++ /dev/null @@ -1,70 +0,0 @@ -\hypertarget{sec:1}{% -\section{Chapter 1. Section 1}\label{sec:1}} - -\hypertarget{sec:11}{% -\subsection{Section 1.1. Section 1.1}\label{sec:11}} - -\leavevmode\hypertarget{dfn:group}{}% -A \emph{group} is a pair \((R,*)\) satisfying: - -\begin{enumerate} -\tightlist -\item - \protect\hypertarget{cl:grpmul}{}{\(*\) is a monoid} -\end{enumerate} - -\hypertarget{sec:2}{% -\section{Chapter 2. Section 2}\label{sec:2}} - -\hypertarget{sec:21}{% -\subsection{Section 2.1. Section 2.1}\label{sec:21}} - -\hypertarget{sec:211}{% -\subsubsection{Paragraph 2.1.1. Section 2.1.1}\label{sec:211}} - -\hypertarget{sec:212}{% -\subsubsection{Paragraph 2.1.2. Section 2.1.2}\label{sec:212}} - -\leavevmode\hypertarget{dfn:ring}{}% -A \emph{ring} is a triple \((R,+,*)\) satisfying: - -\begin{enumerate} -\tightlist -\item - \protect\hypertarget{cl:addgp}{}{\(+\) is an abelian group} -\item - \protect\hypertarget{cl:multmon}{}{\(*\) is a monoid} -\item - \protect\hypertarget{cl:distrib}{}{\(*\) distributes over \(+\)} -\end{enumerate} - -\hypertarget{section-3}{% -\section{Chapter 3. Section 3}\label{section-3}} - -\begin{itemize} -\tightlist -\item - chp.~\ref{sec:1} -\item - sec.~\ref{sec:11} -\item - dfn.~\ref{dfn:group} -\item - cl.~\ref{cl:grpmul} -\end{itemize} - -\begin{center}\rule{0.5\linewidth}{\linethickness}\end{center} - -\begin{itemize} -\tightlist -\item - chp.~\ref{sec:2} -\item - dfn.~\ref{dfn:ring} -\item - cl.~\ref{cl:addgp} -\item - Cl.~\ref{cl:multmon} -\item - Cl.~\ref{cl:distrib} -\end{itemize} diff --git a/test/m2m/section-template/expect.tex b/test/m2m/section-template/expect.tex deleted file mode 100644 index 101c9178..00000000 --- a/test/m2m/section-template/expect.tex +++ /dev/null @@ -1,19 +0,0 @@ -\hypertarget{first-level-section}{% -\section{Chapter 1. First Level Section}\label{first-level-section}} - -\hypertarget{second-level-section}{% -\subsection{Section 1.1. Second Level -Section}\label{second-level-section}} - -\hypertarget{thrid-level-section}{% -\subsubsection{Paragraph 1.1.1. Thrid Level -Section}\label{thrid-level-section}} - -\hypertarget{fourth-level-section}{% -\paragraph{1.1.1.1. Fourth Level Section}\label{fourth-level-section}} - -\hypertarget{fifth-level-section}{% -\subparagraph{1.1.1.1.1. Fifth Level -Section}\label{fifth-level-section}} - -1.1.1.1.1.1. Sixth Level Section diff --git a/test/m2m/subfigures-ccsDelim/expect.tex b/test/m2m/subfigures-ccsDelim/expect.tex deleted file mode 100644 index 97fcf563..00000000 --- a/test/m2m/subfigures-ccsDelim/expect.tex +++ /dev/null @@ -1,53 +0,0 @@ -You can define subfigures: - -\begin{figure} -\centering - -\subfloat[1]{\includegraphics{fig1.png}\label{fig:subfig1}} -\subfloat[2]{\includegraphics{fig2.png}\label{fig:subfig2}} -\subfloat[3]{\includegraphics{fig3.png}} - -\subfloat[4]{\includegraphics{fig4.png}\label{fig:subfig4}} -\subfloat[5]{\includegraphics{fig5.png}} -\subfloat[6]{\includegraphics{fig6.png}\label{fig:subfig6}} - -\subfloat[7]{\includegraphics{fig7.png}\label{fig:subfig7}} -\subfloat[8]{\includegraphics{fig8.png}} -\subfloat[9]{\includegraphics{fig9.png}\label{fig:subfig9}} - -\caption{Caption} - -\label{fig:subfigures} - -\end{figure} - -\begin{figure} -\centering - -\subfloat[1]{\includegraphics{fig1.png}\label{fig:subfig21}} - -\subfloat[2]{\includegraphics{fig2.png}\label{fig:subfig22}} - -\subfloat[3]{\includegraphics{fig3.png}} - -\subfloat[4]{\includegraphics{fig4.png}\label{fig:subfig24}} - -\subfloat[5]{\includegraphics{fig5.png}} - -\subfloat[6]{\includegraphics{fig6.png}\label{fig:subfig26}} - -\subfloat[7]{\includegraphics{fig7.png}\label{fig:subfig27}} - -\subfloat[8]{\includegraphics{fig8.png}} - -\subfloat[9]{\includegraphics{fig9.png}\label{fig:subfig29}} - -\caption{Caption} - -\label{fig:subfigures2} - -\end{figure} - -Figures themselves can be referenced fig.~\ref{fig:subfigures2}, as well -as individual subfigures: -figs.~\ref{fig:subfig1}, \ref{fig:subfig2}, \ref{fig:subfig29} diff --git a/test/m2m/subfigures-grid/expect.tex b/test/m2m/subfigures-grid/expect.tex deleted file mode 100644 index 3b609587..00000000 --- a/test/m2m/subfigures-grid/expect.tex +++ /dev/null @@ -1,53 +0,0 @@ -You can define subfigures: - -\begin{figure} -\centering - -\subfloat[1]{\includegraphics[width=0.3\textwidth,height=\textheight]{fig1.png}\label{fig:subfig1}} -\subfloat[2]{\includegraphics[width=0.3\textwidth,height=\textheight]{fig2.png}\label{fig:subfig2}} -\subfloat[3]{\includegraphics[width=0.3\textwidth,height=\textheight]{fig3.png}} - -\subfloat[4]{\includegraphics[width=0.3\textwidth,height=\textheight]{fig4.png}\label{fig:subfig4}} -\subfloat[5]{\includegraphics[width=0.3\textwidth,height=\textheight]{fig5.png}} -\subfloat[6]{\includegraphics[width=0.3\textwidth,height=\textheight]{fig6.png}\label{fig:subfig6}} - -\subfloat[7]{\includegraphics[width=0.3\textwidth,height=\textheight]{fig7.png}\label{fig:subfig7}} -\subfloat[8]{\includegraphics[width=0.3\textwidth,height=\textheight]{fig8.png}} -\subfloat[9]{\includegraphics[width=0.3\textwidth,height=\textheight]{fig9.png}\label{fig:subfig9}} - -\caption{Caption} - -\label{fig:subfigures} - -\end{figure} - -\begin{figure} -\centering - -\subfloat[1]{\includegraphics{fig1.png}\label{fig:subfig21}} - -\subfloat[2]{\includegraphics{fig2.png}\label{fig:subfig22}} - -\subfloat[3]{\includegraphics{fig3.png}} - -\subfloat[4]{\includegraphics{fig4.png}\label{fig:subfig24}} - -\subfloat[5]{\includegraphics{fig5.png}} - -\subfloat[6]{\includegraphics{fig6.png}\label{fig:subfig26}} - -\subfloat[7]{\includegraphics{fig7.png}\label{fig:subfig27}} - -\subfloat[8]{\includegraphics{fig8.png}} - -\subfloat[9]{\includegraphics{fig9.png}\label{fig:subfig29}} - -\caption{Caption} - -\label{fig:subfigures2} - -\end{figure} - -Figures themselves can be referenced fig.~\ref{fig:subfigures2}, as well -as individual subfigures: -figs.~\ref{fig:subfig1}, \ref{fig:subfig2}, \ref{fig:subfig29} diff --git a/test/m2m/subfigures-template-collect/expect.tex b/test/m2m/subfigures-template-collect/expect.tex deleted file mode 100644 index 97fcf563..00000000 --- a/test/m2m/subfigures-template-collect/expect.tex +++ /dev/null @@ -1,53 +0,0 @@ -You can define subfigures: - -\begin{figure} -\centering - -\subfloat[1]{\includegraphics{fig1.png}\label{fig:subfig1}} -\subfloat[2]{\includegraphics{fig2.png}\label{fig:subfig2}} -\subfloat[3]{\includegraphics{fig3.png}} - -\subfloat[4]{\includegraphics{fig4.png}\label{fig:subfig4}} -\subfloat[5]{\includegraphics{fig5.png}} -\subfloat[6]{\includegraphics{fig6.png}\label{fig:subfig6}} - -\subfloat[7]{\includegraphics{fig7.png}\label{fig:subfig7}} -\subfloat[8]{\includegraphics{fig8.png}} -\subfloat[9]{\includegraphics{fig9.png}\label{fig:subfig9}} - -\caption{Caption} - -\label{fig:subfigures} - -\end{figure} - -\begin{figure} -\centering - -\subfloat[1]{\includegraphics{fig1.png}\label{fig:subfig21}} - -\subfloat[2]{\includegraphics{fig2.png}\label{fig:subfig22}} - -\subfloat[3]{\includegraphics{fig3.png}} - -\subfloat[4]{\includegraphics{fig4.png}\label{fig:subfig24}} - -\subfloat[5]{\includegraphics{fig5.png}} - -\subfloat[6]{\includegraphics{fig6.png}\label{fig:subfig26}} - -\subfloat[7]{\includegraphics{fig7.png}\label{fig:subfig27}} - -\subfloat[8]{\includegraphics{fig8.png}} - -\subfloat[9]{\includegraphics{fig9.png}\label{fig:subfig29}} - -\caption{Caption} - -\label{fig:subfigures2} - -\end{figure} - -Figures themselves can be referenced fig.~\ref{fig:subfigures2}, as well -as individual subfigures: -figs.~\ref{fig:subfig1}, \ref{fig:subfig2}, \ref{fig:subfig29} diff --git a/test/m2m/subfigures/expect.tex b/test/m2m/subfigures/expect.tex deleted file mode 100644 index 97fcf563..00000000 --- a/test/m2m/subfigures/expect.tex +++ /dev/null @@ -1,53 +0,0 @@ -You can define subfigures: - -\begin{figure} -\centering - -\subfloat[1]{\includegraphics{fig1.png}\label{fig:subfig1}} -\subfloat[2]{\includegraphics{fig2.png}\label{fig:subfig2}} -\subfloat[3]{\includegraphics{fig3.png}} - -\subfloat[4]{\includegraphics{fig4.png}\label{fig:subfig4}} -\subfloat[5]{\includegraphics{fig5.png}} -\subfloat[6]{\includegraphics{fig6.png}\label{fig:subfig6}} - -\subfloat[7]{\includegraphics{fig7.png}\label{fig:subfig7}} -\subfloat[8]{\includegraphics{fig8.png}} -\subfloat[9]{\includegraphics{fig9.png}\label{fig:subfig9}} - -\caption{Caption} - -\label{fig:subfigures} - -\end{figure} - -\begin{figure} -\centering - -\subfloat[1]{\includegraphics{fig1.png}\label{fig:subfig21}} - -\subfloat[2]{\includegraphics{fig2.png}\label{fig:subfig22}} - -\subfloat[3]{\includegraphics{fig3.png}} - -\subfloat[4]{\includegraphics{fig4.png}\label{fig:subfig24}} - -\subfloat[5]{\includegraphics{fig5.png}} - -\subfloat[6]{\includegraphics{fig6.png}\label{fig:subfig26}} - -\subfloat[7]{\includegraphics{fig7.png}\label{fig:subfig27}} - -\subfloat[8]{\includegraphics{fig8.png}} - -\subfloat[9]{\includegraphics{fig9.png}\label{fig:subfig29}} - -\caption{Caption} - -\label{fig:subfigures2} - -\end{figure} - -Figures themselves can be referenced fig.~\ref{fig:subfigures2}, as well -as individual subfigures: -figs.~\ref{fig:subfig1}, \ref{fig:subfig2}, \ref{fig:subfig29} diff --git a/test/m2m/template-objects/expect.tex b/test/m2m/template-objects/expect.tex deleted file mode 100644 index bf6c3cb3..00000000 --- a/test/m2m/template-objects/expect.tex +++ /dev/null @@ -1,36 +0,0 @@ -\hypertarget{sec:1}{% -\section{Section 1}\label{sec:1}} - -\hypertarget{sec:11}{% -\subsection{Section 1.1}\label{sec:11}} - -\hypertarget{sec:2}{% -\section{Section 2}\label{sec:2}} - -\hypertarget{sec:21}{% -\subsection{Section 2.1}\label{sec:21}} - -\hypertarget{sec:211}{% -\subsubsection{Section 2.1.1}\label{sec:211}} - -\hypertarget{sec:212}{% -\subsubsection{Section 2.1.2}\label{sec:212}} - -\hypertarget{section-3}{% -\section{Section 3}\label{section-3}} - -\section{List of Sections} - -1. Section 1 - -2. Section 1.1 - -3. Chapter: Section 2 - -4. Section 2.1 - -5. Section 2.1.1 - -6. Paragraph: Section 2.1.2 - -7. Section 3 diff --git a/test/m2m/template-options/expect.tex b/test/m2m/template-options/expect.tex deleted file mode 100644 index c076719d..00000000 --- a/test/m2m/template-options/expect.tex +++ /dev/null @@ -1,36 +0,0 @@ -\hypertarget{sec:1}{% -\section{Section 1}\label{sec:1}} - -\hypertarget{sec:11}{% -\subsection{Section 1.1}\label{sec:11}} - -\hypertarget{sec:2}{% -\section{Section 2}\label{sec:2}} - -\hypertarget{sec:21}{% -\subsection{Section 2.1}\label{sec:21}} - -\hypertarget{sec:211}{% -\subsubsection{Section 2.1.1}\label{sec:211}} - -\hypertarget{sec:212}{% -\subsubsection{Section 2.1.2}\label{sec:212}} - -\hypertarget{section-3}{% -\section{Section 3}\label{section-3}} - -\section{List of Sections} - -1. Section 1 - -2. Section 1.1 - -3. Sec. 2 - -4. Section 2.1 - -5. Section 2.1.1 - -6. Sec. 2.1.2 - -7. Section 3 diff --git a/test/m2m/undefined-prefix/expect.tex b/test/m2m/undefined-prefix/expect.tex deleted file mode 100644 index 0bb59b38..00000000 --- a/test/m2m/undefined-prefix/expect.tex +++ /dev/null @@ -1,2 +0,0 @@ -Crossref shouldn't error out when it sees something that looks like a -reference, but with unknown prefix, like {[}@nonexistent:ref{]} diff --git a/test/test-integrative.hs b/test/test-integrative.hs index 150b5caf..6a0c7c97 100644 --- a/test/test-integrative.hs +++ b/test/test-integrative.hs @@ -44,13 +44,6 @@ m2m dir it "Markdown" $ do zipWithM_ shouldBe (lines' actual_md) (lines' expect_md) length' (lines' actual_md) `shouldBe` length' (lines' expect_md) -#ifdef FLAKY - expect_tex <- runIO $ readFile ("test" "m2m" dir "expect.tex") - let actual_tex = either (fail . show) T.unpack $ runPure $ writeLaTeX wo . evalCrossRefRes . runCrossRef meta (Just $ Format "latex") $ defaultCrossRefAction p - it "LaTeX" $ do - zipWithM_ shouldBe (lines' actual_tex) (lines' expect_tex) - length' (lines' actual_tex) `shouldBe` length' (lines' expect_tex) -#endif where lines' = zip [(1 :: Int)..] . lines length' = length . filter (not . null . snd) diff --git a/test/test-pandoc-crossref.hs b/test/test-pandoc-crossref.hs index 4055ad7f..13c63e4b 100644 --- a/test/test-pandoc-crossref.hs +++ b/test/test-pandoc-crossref.hs @@ -287,11 +287,11 @@ main = hspec $ do describe "References.List.listOf" $ do it "Generates list of tables" $ - testList (rawBlock "latex" "\\listoftables") + testList (rawBlock "latex" "\\listof{tbl}") (referenceData =: M.fromList [let l = "tbl:" <> show i; n = i + 3; sn = str $ show n in refRec' l n sn ("Table " <> sn <> ": " <> sn) | i <- [1..3]]) (header 1 (text "List of Tables") <> divWith ("",["list"],[]) (mconcat $ map (\i -> let n = show i in para $ text (n <> ". " <> n) ) [4..6 :: Int])) it "Generates list of figures" $ - testList (rawBlock "latex" "\\listoffigures") + testList (rawBlock "latex" "\\listof{fig}") (referenceData =: M.fromList [let l = "fig:" <> show i; n = i + 3; sn = str $ show n in refRec' l n sn ("Figure " <> sn <> ": " <> sn) | i <- [1..3]]) (header 1 (text "List of Figures") <> divWith ("",["list"],[]) (mconcat $ map (\i -> let n = show i in para $ text (n <> ". " <> n) ) [4..6 :: Int])) @@ -346,49 +346,6 @@ main = hspec $ do res `shouldBe` Right Native.demochapters #endif - describe "LaTeX" $ do - let test = test' nullMeta - infixr 5 `test` - test' m i o = getLatex m i `shouldBe` o - getLatex m i = either (fail . show) T.unpack (runPure $ writeLaTeX def (Pandoc m . evalCrossRefRes . runCrossRef m (Just $ Format "latex") $ crossRefBlocks (toList i))) - - describe "Labels" $ do - - it "Section labels" $ - headerWith ("sec:section_label1", [], []) 1 (text "Section") - <> para (citeGen "sec:section_label" [1]) - `test` "\\hypertarget{sec:section_label1}{%\n\\section{Section}\\label{sec:section_label1}}\n\nsec.~\\ref{sec:section_label1}" - - it "Image labels" $ - figure "img.png" [] "Title" "figure_label1" - <> para (citeGen "fig:figure_label" [1]) - `test` "\\begin{figure}\n\\hypertarget{fig:figure_label1}{%\n\\centering\n\\includegraphics{img.png}\n\\caption{Title}\\label{fig:figure_label1}\n}\n\\end{figure}\n\nfig.~\\ref{fig:figure_label1}" - - it "Eqn labels" $ - equation "x^2" "some_equation1" - <> para (citeGen "eq:some_equation" [1]) - `test` "\\begin{equation}x^2\\label{eq:some_equation1}\\end{equation}\n\neq.~\\ref{eq:some_equation1}" - -#ifdef FLAKY - it "Tbl labels" $ - table' "A table" "some_table1" - <> para (citeGen "tbl:some_table" [1]) - `test` "\\hypertarget{tbl:some_table1}{}\n\\begin{longtable}[]{@{}@{}}\n\\caption{\\label{tbl:some_table1}A table}\\tabularnewline\n\\toprule\n\\endhead\n\\tabularnewline\n\\bottomrule\n\\end{longtable}\n\ntbl.~\\ref{tbl:some_table1}" -#endif - - it "Code block labels" $ do - codeBlock' "A code block" "some_codeblock1" - <> para (citeGen "lst:some_codeblock" [1]) - `test` "\\begin{codelisting}\n\n\\caption{A code block}\n\n\\hypertarget{lst:some_codeblock1}{%\n\\label{lst:some_codeblock1}}%\n\\begin{Shaded}\n\\begin{Highlighting}[]\n\\OtherTok{main ::} \\DataTypeTok{IO}\\NormalTok{ ()}\n\\end{Highlighting}\n\\end{Shaded}\n\n\\end{codelisting}\n\nlst.~\\ref{lst:some_codeblock1}" - codeBlock' "A code block with under_score" "some_codeblock1" - <> para (citeGen "lst:some_codeblock" [1]) - `test` "\\begin{codelisting}\n\n\\caption{A code block with under\\_score}\n\n\\hypertarget{lst:some_codeblock1}{%\n\\label{lst:some_codeblock1}}%\n\\begin{Shaded}\n\\begin{Highlighting}[]\n\\OtherTok{main ::} \\DataTypeTok{IO}\\NormalTok{ ()}\n\\end{Highlighting}\n\\end{Shaded}\n\n\\end{codelisting}\n\nlst.~\\ref{lst:some_codeblock1}" - let test1 = test' $ setMeta "codeBlockCaptions" True nullMeta - infixr 5 `test1` - codeBlockForTable "some_codeblock1" <> paraText ": A code block" - <> para (citeGen "lst:some_codeblock" [1]) - `test1` "\\begin{codelisting}\n\n\\caption{A code block}\n\n\\hypertarget{lst:some_codeblock1}{%\n\\label{lst:some_codeblock1}}%\n\\begin{Shaded}\n\\begin{Highlighting}[]\n\\OtherTok{main ::} \\DataTypeTok{IO}\\NormalTok{ ()}\n\\end{Highlighting}\n\\end{Shaded}\n\n\\end{codelisting}\n\nlst.~\\ref{lst:some_codeblock1}" - citeGen :: String -> [Int] -> Inlines citeGen p l = cite (mconcat $ map (cit . (p++) . show) l) $ text $ "[" ++ intercalate "; " (map (("@"++) . (p++) . show) l) ++ "]" From dcc9965b5c5403b545ad8e0de2716d8e153f2577 Mon Sep 17 00:00:00 2001 From: Nikolay Yakimov Date: Sat, 9 Mar 2019 06:23:58 +0300 Subject: [PATCH 073/134] Streamline math handling --- lib/Text/Pandoc/CrossRef/References/Blocks.hs | 36 ++----------------- .../Pandoc/CrossRef/Util/Options/Types.hs | 1 - lib/Text/Pandoc/CrossRef/Util/Settings.hs | 3 +- 3 files changed, 3 insertions(+), 37 deletions(-) diff --git a/lib/Text/Pandoc/CrossRef/References/Blocks.hs b/lib/Text/Pandoc/CrossRef/References/Blocks.hs index aa36ac05..5b97e7fc 100644 --- a/lib/Text/Pandoc/CrossRef/References/Blocks.hs +++ b/lib/Text/Pandoc/CrossRef/References/Blocks.hs @@ -52,14 +52,9 @@ replaceAll opts = fmap unhierarchicalize . runReplace [] (mkRR replaceElement `extRR` replaceBlock opts `extRR` replaceInline opts) . hierarchicalize - . runSplitMath . everywhere (mkT $ makeSubfigures opts) . everywhere (mkT (divBlocks opts) `extT` spanInlines opts) . everywhere (mkT $ mkCodeBlockCaptions opts) - where - runSplitMath | tableEqns opts - = everywhere (mkT splitMath) - | otherwise = id replaceElement :: Scope -> Element -> WS (ReplacedResult Element) replaceElement scope (Sec n ns (label, cls, attrs) text' body) = do @@ -98,14 +93,6 @@ replaceBlock opts scope (Div (label, [], divattrs) [CodeBlock ([],classes,cbattr replaceNoRecurse $ Div (label, "listing":classes, []) $ placeCaption opts ref [CodeBlock ([], classes, cbattrs) code] --- Table display math -replaceBlock opts scope (Para [Span ats@(label, _, attrs) [Math DisplayMath eq]]) - | tableEqns opts - , Just pfx <- getRefPrefix opts label <|> autoEqnLabels opts - , Just lbl <- autoLabel pfx label - = do - (eq', idx) <- replaceEqn opts scope lbl attrs eq pfx - replaceNoRecurse $ Div ats [Table [] [AlignCenter, AlignRight] [0.9, 0.09] [] [[[Plain [Math DisplayMath eq']], [Plain [Math DisplayMath $ "(" ++ idx ++ ")"]]]]] -- Generic div replaceBlock opts scope (Div ats@(label, _, attrs) content) | Just pfx <- getRefPrefix opts label @@ -127,13 +114,6 @@ placeCaption opts RefRec{..} body | Below <- refCaptionPosition = body <> [mkCaption opts "Caption" refCaption] -replaceEqn :: Options -> Scope -> Either String String -> [(String, String)] -> String -> String -> WS (String, String) -replaceEqn opts scope label attrs eq pfx = do - idxStr <- replaceAttr opts scope label attrs (B.math eq) pfx - let eq' | tableEqns opts = eq - | otherwise = eq++"\\qquad("++stringify (refIxInl idxStr)++")" - return (eq', stringify (refIxInl idxStr)) - autoLabel :: String -> String -> Maybe (Either String String) autoLabel pfx label | null label = Just $ Left pfx @@ -145,8 +125,8 @@ replaceInline opts scope (Span ats@(label,_,attrs) [Math DisplayMath eq]) | Just pfx <- getRefPrefix opts label <|> autoEqnLabels opts , Just lbl <- autoLabel pfx label = do - (eq', _) <- replaceEqn opts scope lbl attrs eq pfx - replaceNoRecurse $ Span ats [Math DisplayMath eq'] + RefRec{..} <- replaceAttr opts scope lbl attrs (B.displayMath eq) pfx + replaceNoRecurse $ Span ats [Math DisplayMath $ stringify refCaption] replaceInline opts scope (Image attr@(label,_,attrs) alt img@(_, tit)) | Just pfx <- getRefPrefix opts label <|> autoFigLabels opts , Just lbl <- autoLabel pfx label @@ -205,18 +185,6 @@ divBlocks opts (CodeBlock (label, classes, attrs) code) in Div (label, [], []) [cb', p] divBlocks _ x = x -splitMath :: [Block] -> [Block] -splitMath (Para ils:xs) - | length ils > 1 = map Para (split [] [] ils) ++ xs - where - split res acc [] = reverse (reverse acc : res) - split res acc (x@(Span _ [Math DisplayMath _]):ys) = - split ([x] : reverse (dropSpaces acc) : res) - [] (dropSpaces ys) - split res acc (y:ys) = split res (y:acc) ys - dropSpaces = dropWhile isSpace -splitMath xs = xs - spanInlines :: Options -> [Inline] -> [Inline] spanInlines opts (math@(Math DisplayMath _eq):ils) | c:ils' <- dropWhile isSpace ils diff --git a/lib/Text/Pandoc/CrossRef/Util/Options/Types.hs b/lib/Text/Pandoc/CrossRef/Util/Options/Types.hs index 3bcb700c..7fca1b74 100644 --- a/lib/Text/Pandoc/CrossRef/Util/Options/Types.hs +++ b/lib/Text/Pandoc/CrossRef/Util/Options/Types.hs @@ -31,7 +31,6 @@ data Options = Options { codeBlockCaptions :: Bool , lastDelim :: Inlines , refDelim :: Inlines , outFormat :: Maybe Format - , tableEqns :: Bool , autoEqnLabels :: Maybe String , autoFigLabels :: Maybe String , linkReferences :: Bool diff --git a/lib/Text/Pandoc/CrossRef/Util/Settings.hs b/lib/Text/Pandoc/CrossRef/Util/Settings.hs index 7f9b9020..40eca53b 100644 --- a/lib/Text/Pandoc/CrossRef/Util/Settings.hs +++ b/lib/Text/Pandoc/CrossRef/Util/Settings.hs @@ -68,7 +68,6 @@ defaultMeta = Settings $ <> lastDelim (str "," <> space) <> refDelim (str "," <> space) <> crossrefYaml "pandoc-crossref.yaml" - <> tableEqns False <> linkReferences False <> nameInLink False <> collectedCaptionDelim (str "," <> space) @@ -85,7 +84,7 @@ defaultMeta = Settings $ <> prefixes' [ "eq" .: [ "ref" .= map str ["eq.", "eqns."], - "captionTemplate" .= var "i", + "captionTemplate" .= var "t" <> str "\\qquad(" <> var "i" <> str ")", "title" .= text "Equation" ], "fig" .: [ From 3c94139caaec0d6eab94fa127e5a53c47574eba5 Mon Sep 17 00:00:00 2001 From: Nikolay Yakimov Date: Wed, 17 Apr 2019 20:46:19 +0300 Subject: [PATCH 074/134] Remove some unused TH code --- lib/Text/Pandoc/CrossRef/Util/Settings/Template.hs | 7 ------- 1 file changed, 7 deletions(-) diff --git a/lib/Text/Pandoc/CrossRef/Util/Settings/Template.hs b/lib/Text/Pandoc/CrossRef/Util/Settings/Template.hs index 611fc639..d65a135e 100644 --- a/lib/Text/Pandoc/CrossRef/Util/Settings/Template.hs +++ b/lib/Text/Pandoc/CrossRef/Util/Settings/Template.hs @@ -28,7 +28,6 @@ import qualified Data.Map as M import Language.Haskell.TH hiding (Inline) import Language.Haskell.TH.Syntax hiding (Inline) import Data.List -import Text.Pandoc.CrossRef.Util.Template import Text.Pandoc.CrossRef.Util.Prefixes namedFields :: Con -> [VarStrictType] @@ -70,14 +69,11 @@ makeCon t cname = fromRecDef t cname makeCon' RecConE makeCon' :: Name -> Name -> Q [(Name, Exp)] makeCon' t accName = do VarI _ t' _ <- reify accName - funT <- [t|$(conT t) -> Bool -> Int -> Inlines|] inlT <- [t|$(conT t) -> Inlines|] blkT <- [t|$(conT t) -> Blocks|] fmtT <- [t|$(conT t) -> Maybe Format|] boolT <- [t|$(conT t) -> Bool|] intT <- [t|$(conT t) -> Int|] - tmplT <- [t|$(conT t) -> Template|] - clT <- [t|$(conT t) -> String -> Int -> Maybe String|] pfxT <- [t|$(conT t) -> Prefixes|] strT <- [t|$(conT t) -> String|] mstT <- [t|$(conT t) -> Maybe String|] @@ -87,11 +83,8 @@ makeCon' t accName = do if | t' == boolT -> [|getMetaBool $(varName) $(dtv)|] | t' == intT -> [|read $ getMetaString $(varName) $(dtv)|] - | t' == funT -> [|tryCapitalizeM (flip (getMetaList (toInlines $(varName))) $(dtv)) $(varName)|] | t' == inlT -> [|getMetaInlines $(varName) $(dtv)|] | t' == blkT -> [|getMetaBlock $(varName) $(dtv)|] - | t' == tmplT -> [|makeTemplate $(dtv) $ getMetaInlines $(varName) $(dtv)|] - | t' == clT -> [|customLabel $(dtv)|] | t' == fmtT -> return $ VarE $ mkName "fmt" | t' == pfxT -> [|getPrefixes $(varName) $(dtv)|] | t' == strT -> [|getMetaString $(varName) $(dtv)|] From 525988ad39f968bb82b729d1db0ccfa7e947559f Mon Sep 17 00:00:00 2001 From: Nikolay Yakimov Date: Fri, 26 Apr 2019 05:44:31 +0300 Subject: [PATCH 075/134] Remove obsolete tests --- pandoc-crossref.cabal | 6 +- test/m2m/equations-tables-auto/expect.md | 97 ------------------------ test/m2m/equations-tables-auto/input.md | 38 ---------- test/m2m/equations-tables/expect.md | 61 --------------- test/m2m/equations-tables/input.md | 37 --------- 5 files changed, 1 insertion(+), 238 deletions(-) delete mode 100644 test/m2m/equations-tables-auto/expect.md delete mode 100644 test/m2m/equations-tables-auto/input.md delete mode 100644 test/m2m/equations-tables/expect.md delete mode 100644 test/m2m/equations-tables/input.md diff --git a/pandoc-crossref.cabal b/pandoc-crossref.cabal index 609b0123..a1672184 100644 --- a/pandoc-crossref.cabal +++ b/pandoc-crossref.cabal @@ -4,7 +4,7 @@ cabal-version: 1.12 -- -- see: https://github.com/sol/hpack -- --- hash: a722e828c9b63f37754f36f155ac6cec7d4a7d0fb0e3897dd14d6cc3aa54f0d6 +-- hash: 29a16982bbf4d0374a7ea424d1f675afda7029727f410eadca021ecf8636ee26 name: pandoc-crossref version: 0.4.0.0 @@ -33,10 +33,6 @@ data-files: test/m2m/delim/input.md test/m2m/equations-auto/expect.md test/m2m/equations-auto/input.md - test/m2m/equations-tables-auto/expect.md - test/m2m/equations-tables-auto/input.md - test/m2m/equations-tables/expect.md - test/m2m/equations-tables/input.md test/m2m/equations/expect.md test/m2m/equations/input.md test/m2m/links-names/expect.md diff --git a/test/m2m/equations-tables-auto/expect.md b/test/m2m/equations-tables-auto/expect.md deleted file mode 100644 index 2144a630..00000000 --- a/test/m2m/equations-tables-auto/expect.md +++ /dev/null @@ -1,97 +0,0 @@ -This is a test file with some referenced equations, line - -
- - --------------------------------------------------------------- --------- - $$ this $$ $$(1)$$ - - --------------------------------------------------------------- --------- - -
- -Some equations might be inside of text, - -
- - --------------------------------------------------------------- --------- - $$ for example $$ $$(2)$$ - - --------------------------------------------------------------- --------- - -
- -this one. - -Some equations might be on start of paragraphs: - -
- - --------------------------------------------------------------- --------- - $$ start $$ $$(3)$$ - - --------------------------------------------------------------- --------- - -
- -of paragraph. - -Other might be on separate paragraphs of their own: - -
- - --------------------------------------------------------------- --------- - $$ separate $$ $$(4)$$ - - --------------------------------------------------------------- --------- - -
- -Some of those can be labelled: - -This is a test file with some referenced equations, line - -::: {#eq:0} - --------------------------------------------------------------- --------- - $$ this $$ $$(5)$$ - - --------------------------------------------------------------- --------- -::: - -Some equations might be inside of text, - -::: {#eq:1} - --------------------------------------------------------------- --------- - $$ for example $$ $$(6)$$ - - --------------------------------------------------------------- --------- -::: - -this one. - -Some equations might be on start of paragraphs: - -::: {#eq:2} - --------------------------------------------------------------- --------- - $$ start $$ $$(7)$$ - - --------------------------------------------------------------- --------- -::: - -of paragraph. - -Other might be on separate paragraphs of their own: - -::: {#eq:3} - --------------------------------------------------------------- --------- - $$ separate $$ $$(8)$$ - - --------------------------------------------------------------- --------- -::: - -Then they can be referenced: - -Individually eq. 5, eq. 6, eq. 7, eq. 8 - -Or in groups eqns. 5, 6, 8 - -Groups will be compacted eqns. 5-8 diff --git a/test/m2m/equations-tables-auto/input.md b/test/m2m/equations-tables-auto/input.md deleted file mode 100644 index f5b9e048..00000000 --- a/test/m2m/equations-tables-auto/input.md +++ /dev/null @@ -1,38 +0,0 @@ ---- -tableEqns: true -autoEqnLabels: eq -... - -This is a test file with some referenced equations, line $$ this $$ - -Some equations might be inside of text, $$ for example $$ this one. - -Some equations might be on start of paragraphs: - -$$ start $$ of paragraph. - -Other might be on separate paragraphs of their own: - -$$ separate $$ - -Some of those can be labelled: - -This is a test file with some referenced equations, line $$ this $${#eq:0} - -Some equations might be inside of text, $$ for example $${#eq:1} this one. - -Some equations might be on start of paragraphs: - -$$ start $${#eq:2} of paragraph. - -Other might be on separate paragraphs of their own: - -$$ separate $${#eq:3} - -Then they can be referenced: - -Individually @eq:0, @eq:1, @eq:2, @eq:3 - -Or in groups [@eq:0; @eq:1; @eq:3] - -Groups will be compacted [@eq:0; @eq:1; @eq:3; @eq:2] diff --git a/test/m2m/equations-tables/expect.md b/test/m2m/equations-tables/expect.md deleted file mode 100644 index 16a779ec..00000000 --- a/test/m2m/equations-tables/expect.md +++ /dev/null @@ -1,61 +0,0 @@ -This is a test file with some referenced equations, line $$ this $$ - -Some equations might be inside of text, $$ for example $$ this one. - -Some equations might be on start of paragraphs: - -$$ start $$ of paragraph. - -Other might be on separate paragraphs of their own: - -$$ separate $$ - -Some of those can be labelled: - -This is a test file with some referenced equations, line - -::: {#eq:0} - --------------------------------------------------------------- --------- - $$ this $$ $$(1)$$ - - --------------------------------------------------------------- --------- -::: - -Some equations might be inside of text, - -::: {#eq:1} - --------------------------------------------------------------- --------- - $$ for example $$ $$(2)$$ - - --------------------------------------------------------------- --------- -::: - -this one. - -Some equations might be on start of paragraphs: - -::: {#eq:2} - --------------------------------------------------------------- --------- - $$ start $$ $$(3)$$ - - --------------------------------------------------------------- --------- -::: - -of paragraph. - -Other might be on separate paragraphs of their own: - -::: {#eq:3} - --------------------------------------------------------------- --------- - $$ separate $$ $$(4)$$ - - --------------------------------------------------------------- --------- -::: - -Then they can be referenced: - -Individually eq. 1, eq. 2, eq. 3, eq. 4 - -Or in groups eqns. 1, 2, 4 - -Groups will be compacted eqns. 1-4 diff --git a/test/m2m/equations-tables/input.md b/test/m2m/equations-tables/input.md deleted file mode 100644 index f44b85a2..00000000 --- a/test/m2m/equations-tables/input.md +++ /dev/null @@ -1,37 +0,0 @@ ---- -tableEqns: true -... - -This is a test file with some referenced equations, line $$ this $$ - -Some equations might be inside of text, $$ for example $$ this one. - -Some equations might be on start of paragraphs: - -$$ start $$ of paragraph. - -Other might be on separate paragraphs of their own: - -$$ separate $$ - -Some of those can be labelled: - -This is a test file with some referenced equations, line $$ this $${#eq:0} - -Some equations might be inside of text, $$ for example $${#eq:1} this one. - -Some equations might be on start of paragraphs: - -$$ start $${#eq:2} of paragraph. - -Other might be on separate paragraphs of their own: - -$$ separate $${#eq:3} - -Then they can be referenced: - -Individually @eq:0, @eq:1, @eq:2, @eq:3 - -Or in groups [@eq:0; @eq:1; @eq:3] - -Groups will be compacted [@eq:0; @eq:1; @eq:3; @eq:2] From fe99969a98835112c74ca49fe7482bb605829d75 Mon Sep 17 00:00:00 2001 From: Nikolay Yakimov Date: Fri, 26 Apr 2019 05:45:03 +0300 Subject: [PATCH 076/134] Clean up subfigures code --- .../Pandoc/CrossRef/References/Subfigures.hs | 18 ++++++++++-------- 1 file changed, 10 insertions(+), 8 deletions(-) diff --git a/lib/Text/Pandoc/CrossRef/References/Subfigures.hs b/lib/Text/Pandoc/CrossRef/References/Subfigures.hs index 182754b7..adecf5d9 100644 --- a/lib/Text/Pandoc/CrossRef/References/Subfigures.hs +++ b/lib/Text/Pandoc/CrossRef/References/Subfigures.hs @@ -21,7 +21,6 @@ with this program; if not, write to the Free Software Foundation, Inc., module Text.Pandoc.CrossRef.References.Subfigures where import Text.Pandoc.Definition -import Text.Pandoc.Walk import Data.List import Data.Maybe import Data.Monoid @@ -40,20 +39,23 @@ makeSubfigures opts (Div (label,cls,attrs) contents) $ if prefixSubcaptionsGrid pfxRec then toTable (init cont) ++ [last cont] else cont - where cont = walk figImageParas contents -- modified contents + where cont = map figImageParas contents -- modified contents figImageParas (Para cs) | all isImageOrSpace cs - = Para $ map addFigureAttr cs + = Para $ mapMaybe mkFigure cs figImageParas (Plain cs) | all isImageOrSpace cs - = Plain $ map addFigureAttr cs + = Para $ mapMaybe mkFigure cs figImageParas x = x isImageOrSpace Image{} = True isImageOrSpace x = isSpace x - addFigureAttr (Image attr alt (src, tit)) - | not $ "fig:" `isPrefixOf` tit - = Image attr alt (src, "fig:" <> tit) - addFigureAttr x = x + mkFigure (Image attr alt (src, tit)) + = Just $ Image attr alt (src, + if "fig:" `isPrefixOf` tit + then tit + else "fig:" <> tit + ) + mkFigure _ = Nothing makeSubfigures _ x = x toTable :: [Block] -> [Block] From b9718f93e578847100d01adc6488ca7a8b35bcef Mon Sep 17 00:00:00 2001 From: Nikolay Yakimov Date: Fri, 26 Apr 2019 05:45:46 +0300 Subject: [PATCH 077/134] Enable subcaptionsGrid by default --- lib/Text/Pandoc/CrossRef/Util/Meta.hs | 7 +++++++ lib/Text/Pandoc/CrossRef/Util/Prefixes.hs | 2 +- 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/lib/Text/Pandoc/CrossRef/Util/Meta.hs b/lib/Text/Pandoc/CrossRef/Util/Meta.hs index 17558d6c..67982d11 100644 --- a/lib/Text/Pandoc/CrossRef/Util/Meta.hs +++ b/lib/Text/Pandoc/CrossRef/Util/Meta.hs @@ -22,6 +22,7 @@ with this program; if not, write to the Free Software Foundation, Inc., module Text.Pandoc.CrossRef.Util.Meta ( getMetaList , getMetaBool + , getMetaBoolDefault , getMetaInlines , getMetaBlock , getMetaString @@ -56,6 +57,9 @@ getMetaStringList name (Settings meta) = maybe [] (getList' name) $ lookupMeta n getMetaBool :: String -> Settings -> Bool getMetaBool = getScalar toBool +getMetaBoolDefault :: String -> Settings -> Bool -> Bool +getMetaBoolDefault = getScalarDefault toBool + getMetaInlines :: String -> Settings -> Inlines getMetaInlines = getScalar toInlines @@ -71,6 +75,9 @@ getMetaStringMaybe = getScalar (const toMaybeString) getScalar :: Def b => (String -> MetaValue -> b) -> String -> Settings -> b getScalar conv name (Settings meta) = maybe def' (conv name) $ lookupMeta name meta +getScalarDefault :: (String -> MetaValue -> b) -> String -> Settings -> b -> b +getScalarDefault conv name (Settings meta) dv = maybe dv (conv name) $ lookupMeta name meta + class Def a where def' :: a diff --git a/lib/Text/Pandoc/CrossRef/Util/Prefixes.hs b/lib/Text/Pandoc/CrossRef/Util/Prefixes.hs index b446837c..380bc920 100644 --- a/lib/Text/Pandoc/CrossRef/Util/Prefixes.hs +++ b/lib/Text/Pandoc/CrossRef/Util/Prefixes.hs @@ -53,7 +53,7 @@ getPrefixes varN dtv (fromMaybe (reportError prettyVarName "Numbering") $ lookupSettings varName kv) , prefixSubcaptions = getMetaBool "subcaptions" kv - , prefixSubcaptionsGrid = getMetaBool "subcaptionsGrid" kv + , prefixSubcaptionsGrid = getMetaBoolDefault "subcaptionsGrid" kv True , prefixCaptionPosition = case getMetaString "captionPosition" kv of "above" -> Above _ -> Below From a472cc25e86bf4c18cd79a8741249b6b358df663 Mon Sep 17 00:00:00 2001 From: Nikolay Yakimov Date: Fri, 26 Apr 2019 05:46:34 +0300 Subject: [PATCH 078/134] Update m2m tests --- test/m2m/list-of/expect.md | 6 +++--- test/m2m/subfigures-ccsDelim/expect.md | 9 +++------ test/m2m/subfigures-ccsDelim/input.md | 1 + test/m2m/subfigures-template-collect/expect.md | 9 +++------ test/m2m/subfigures-template-collect/input.md | 1 + test/m2m/subfigures/expect.md | 9 +++------ test/m2m/subfigures/input.md | 2 +- 7 files changed, 15 insertions(+), 22 deletions(-) diff --git a/test/m2m/list-of/expect.md b/test/m2m/list-of/expect.md index 4331df02..73002e44 100644 --- a/test/m2m/list-of/expect.md +++ b/test/m2m/list-of/expect.md @@ -46,11 +46,11 @@ List of Equations ================= ::: {.list} -1\. $eqn1$ +1\. $$eqn1$$ -2\. $eqn2$ +2\. $$eqn2$$ -3\. $eqn3$ +3\. $$eqn3$$ ::: List of Tables diff --git a/test/m2m/subfigures-ccsDelim/expect.md b/test/m2m/subfigures-ccsDelim/expect.md index 7f55459f..b1844c93 100644 --- a/test/m2m/subfigures-ccsDelim/expect.md +++ b/test/m2m/subfigures-ccsDelim/expect.md @@ -1,14 +1,11 @@ You can define subfigures: ::: {#fig:subfigures .subcaption} -![a](fig1.png "fig:"){#fig:subfig1} ![b](fig2.png "fig:"){#fig:subfig2} -![c](fig3.png "fig:") +![a](fig1.png "fig:"){#fig:subfig1}![b](fig2.png "fig:"){#fig:subfig2}![c](fig3.png "fig:") -![d](fig4.png "fig:"){#fig:subfig4} ![e](fig5.png "fig:") -![f](fig6.png "fig:"){#fig:subfig6} +![d](fig4.png "fig:"){#fig:subfig4}![e](fig5.png "fig:")![f](fig6.png "fig:"){#fig:subfig6} -![g](fig7.png "fig:"){#fig:subfig7} ![h](fig8.png "fig:") -![i](fig9.png "fig:"){#fig:subfig9} +![g](fig7.png "fig:"){#fig:subfig7}![h](fig8.png "fig:")![i](fig9.png "fig:"){#fig:subfig9} Figure 1: Caption. a -- 1; b -- 2; c -- 3; d -- 4; e -- 5; f -- 6; g -- 7; h -- 8; i -- 9 diff --git a/test/m2m/subfigures-ccsDelim/input.md b/test/m2m/subfigures-ccsDelim/input.md index 2fb0a9a3..cb6a4b80 100644 --- a/test/m2m/subfigures-ccsDelim/input.md +++ b/test/m2m/subfigures-ccsDelim/input.md @@ -3,6 +3,7 @@ autoFigLabels: fig prefixes: fig: subcaptions: true + subcaptionsGrid: false collectedCaptionDelim: "; " sub: numbering: alpha a diff --git a/test/m2m/subfigures-template-collect/expect.md b/test/m2m/subfigures-template-collect/expect.md index 3ba67c6e..ec760644 100644 --- a/test/m2m/subfigures-template-collect/expect.md +++ b/test/m2m/subfigures-template-collect/expect.md @@ -1,14 +1,11 @@ You can define subfigures: ::: {#fig:subfigures .subcaption} -![a](fig1.png "fig:"){#fig:subfig1} ![b](fig2.png "fig:"){#fig:subfig2} -![c](fig3.png "fig:") +![a](fig1.png "fig:"){#fig:subfig1}![b](fig2.png "fig:"){#fig:subfig2}![c](fig3.png "fig:") -![d](fig4.png "fig:"){#fig:subfig4} ![e](fig5.png "fig:") -![f](fig6.png "fig:"){#fig:subfig6} +![d](fig4.png "fig:"){#fig:subfig4}![e](fig5.png "fig:")![f](fig6.png "fig:"){#fig:subfig6} -![g](fig7.png "fig:"){#fig:subfig7} ![h](fig8.png "fig:") -![i](fig9.png "fig:"){#fig:subfig9} +![g](fig7.png "fig:"){#fig:subfig7}![h](fig8.png "fig:")![i](fig9.png "fig:"){#fig:subfig9} Figure 1: Caption. a -- 1, b -- 2, c -- 3, d -- 4, e -- 5, f -- 6, g -- 7, h -- 8, i -- 9 diff --git a/test/m2m/subfigures-template-collect/input.md b/test/m2m/subfigures-template-collect/input.md index 28cbbc9f..8548675f 100644 --- a/test/m2m/subfigures-template-collect/input.md +++ b/test/m2m/subfigures-template-collect/input.md @@ -3,6 +3,7 @@ autoFigLabels: fig prefixes: fig: subcaptions: true + subcaptionsGrid: false captionTemplate: '$$title% $$$$i$$$$titleDelim$$$$t$$. []{}' sub: numbering: alpha a diff --git a/test/m2m/subfigures/expect.md b/test/m2m/subfigures/expect.md index 3ba67c6e..ec760644 100644 --- a/test/m2m/subfigures/expect.md +++ b/test/m2m/subfigures/expect.md @@ -1,14 +1,11 @@ You can define subfigures: ::: {#fig:subfigures .subcaption} -![a](fig1.png "fig:"){#fig:subfig1} ![b](fig2.png "fig:"){#fig:subfig2} -![c](fig3.png "fig:") +![a](fig1.png "fig:"){#fig:subfig1}![b](fig2.png "fig:"){#fig:subfig2}![c](fig3.png "fig:") -![d](fig4.png "fig:"){#fig:subfig4} ![e](fig5.png "fig:") -![f](fig6.png "fig:"){#fig:subfig6} +![d](fig4.png "fig:"){#fig:subfig4}![e](fig5.png "fig:")![f](fig6.png "fig:"){#fig:subfig6} -![g](fig7.png "fig:"){#fig:subfig7} ![h](fig8.png "fig:") -![i](fig9.png "fig:"){#fig:subfig9} +![g](fig7.png "fig:"){#fig:subfig7}![h](fig8.png "fig:")![i](fig9.png "fig:"){#fig:subfig9} Figure 1: Caption. a -- 1, b -- 2, c -- 3, d -- 4, e -- 5, f -- 6, g -- 7, h -- 8, i -- 9 diff --git a/test/m2m/subfigures/input.md b/test/m2m/subfigures/input.md index 7e35fb3f..e87a0d64 100644 --- a/test/m2m/subfigures/input.md +++ b/test/m2m/subfigures/input.md @@ -3,7 +3,7 @@ autoFigLabels: fig prefixes: fig: subcaptions: true - # subcaptionsGrid: true + subcaptionsGrid: false sub: numbering: alpha a referenceIndexTemplate: $$s.i$$ ($$i$$) From e3c5601f3ef4593b00c5e74d4fc6de7a5b4320f8 Mon Sep 17 00:00:00 2001 From: Nikolay Yakimov Date: Fri, 26 Apr 2019 05:47:06 +0300 Subject: [PATCH 079/134] Suppress toprule and bottomrule in subcaptions grid LaTeX output --- lib/Text/Pandoc/CrossRef/References/Subfigures.hs | 7 ++++++- lib/Text/Pandoc/CrossRef/Util/ModifyMeta.hs | 1 + 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/lib/Text/Pandoc/CrossRef/References/Subfigures.hs b/lib/Text/Pandoc/CrossRef/References/Subfigures.hs index adecf5d9..308ad1c9 100644 --- a/lib/Text/Pandoc/CrossRef/References/Subfigures.hs +++ b/lib/Text/Pandoc/CrossRef/References/Subfigures.hs @@ -37,7 +37,7 @@ makeSubfigures opts (Div (label,cls,attrs) contents) , prefixSubcaptions pfxRec = Div (label, "subcaption":cls, attrs) $ if prefixSubcaptionsGrid pfxRec - then toTable (init cont) ++ [last cont] + then wrapSubcaptionEnv (toTable (init cont)) <> [last cont] else cont where cont = map figImageParas contents -- modified contents figImageParas (Para cs) @@ -56,6 +56,11 @@ makeSubfigures opts (Div (label,cls,attrs) contents) else "fig:" <> tit ) mkFigure _ = Nothing + wrapSubcaptionEnv p + | isLatexFormat $ outFormat opts + = RawBlock (Format "latex") "\\begin{pandoccrossrefsubcaption}\n" : + (p <> [RawBlock (Format "latex") "\\end{pandoccrossrefsubcaption}\n"]) + | otherwise = p makeSubfigures _ x = x toTable :: [Block] -> [Block] diff --git a/lib/Text/Pandoc/CrossRef/Util/ModifyMeta.hs b/lib/Text/Pandoc/CrossRef/Util/ModifyMeta.hs index 4488431e..49968d2f 100644 --- a/lib/Text/Pandoc/CrossRef/Util/ModifyMeta.hs +++ b/lib/Text/Pandoc/CrossRef/Util/ModifyMeta.hs @@ -44,6 +44,7 @@ modifyMeta = do incList = MetaBlocks $ return $ RawBlock (Format "latex") $ unlines $ execWriter $ do tell [ "\\makeatletter" ] tell [ "\\@ifpackageloaded{caption}{\\captionsetup{labelformat=empty}}{\\usepackage[labelformat=empty]{caption}}" ] + tell [ "\\newenvironment{pandoccrossrefsubcaption}{\\renewcommand{\\toprule}{}\\renewcommand{\\bottomrule}{}}{}" ] tell [ "\\makeatother" ] return $ if isLatexFormat outFormat then setMeta "header-includes" From 2035f425e93890a79d94b206afd7e8e64a47c603 Mon Sep 17 00:00:00 2001 From: Nikolay Yakimov Date: Fri, 26 Apr 2019 06:23:48 +0300 Subject: [PATCH 080/134] Wrap subcaptionGrid cells in a bogus div for compat with ODT writer --- lib/Text/Pandoc/CrossRef/References/Subfigures.hs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/Text/Pandoc/CrossRef/References/Subfigures.hs b/lib/Text/Pandoc/CrossRef/References/Subfigures.hs index 308ad1c9..62ceabef 100644 --- a/lib/Text/Pandoc/CrossRef/References/Subfigures.hs +++ b/lib/Text/Pandoc/CrossRef/References/Subfigures.hs @@ -91,7 +91,7 @@ toTable blks = [Table [] align widths [] $ map blkToRow blks] blkToRow (Para inls) = mapMaybe inlToCell inls blkToRow x = [[x]] inlToCell :: Inline -> Maybe [Block] - inlToCell (Image (id', cs, as) txt tgt) = Just [Para [Image (id', cs, setW as) txt tgt]] + inlToCell (Image (id', cs, as) txt tgt) = Just [Div nullAttr [Para [Image (id', cs, setW as) txt tgt]]] inlToCell _ = Nothing setW as = ("width", "100%"):filter ((/="width") . fst) as -- From a54452b12606c485da046078d7cc6143a2098260 Mon Sep 17 00:00:00 2001 From: Nikolay Yakimov Date: Fri, 26 Apr 2019 06:32:40 +0300 Subject: [PATCH 081/134] Update subcaptionGrid test --- test/m2m/subfigures-grid/expect.md | 48 ++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) diff --git a/test/m2m/subfigures-grid/expect.md b/test/m2m/subfigures-grid/expect.md index 0b1b780d..5b58c24c 100644 --- a/test/m2m/subfigures-grid/expect.md +++ b/test/m2m/subfigures-grid/expect.md @@ -2,17 +2,29 @@ You can define subfigures: ::: {#fig:subfigures .subcaption} +:------------------:+:------------------:+:------------------:+ +|
|
|
| +| | | | | ![a](fig1.png){#fi | ![b](fig2.png){#fi | ![c](fig3.png){wid | | g:subfig1 | g:subfig2 | th="100%"} | | width="100%"} | width="100%"} | | +| | |
| +|
|
| | +--------------------+--------------------+--------------------+ +|
|
|
| +| | | | | ![d](fig4.png){#fi | ![e](fig5.png){wid | ![f](fig6.png){#fi | | g:subfig4 | th="100%"} | g:subfig6 | | width="100%"} | | width="100%"} | +| |
| | +|
| |
| +--------------------+--------------------+--------------------+ +|
|
|
| +| | | | | ![g](fig7.png){#fi | ![h](fig8.png){wid | ![i](fig9.png){#fi | | g:subfig7 | th="100%"} | g:subfig9 | | width="100%"} | | width="100%"} | +| |
| | +|
| |
| +--------------------+--------------------+--------------------+ Figure 1: Caption. a -- 1, b -- 2, c -- 3, d -- 4, e -- 5, f -- 6, g -- @@ -21,23 +33,59 @@ Figure 1: Caption. a -- 1, b -- 2, c -- 3, d -- 4, e -- 5, f -- 6, g -- ::: {#fig:subfigures2 .subcaption} +:--------------------------------------------------------------------:+ +|
| +| | | ![a](fig1.png){#fig:subfig21 width="100%"} | +| | +|
| +----------------------------------------------------------------------+ +|
| +| | | ![b](fig2.png){#fig:subfig22 width="100%"} | +| | +|
| +----------------------------------------------------------------------+ +|
| +| | | ![c](fig3.png){width="100%"} | +| | +|
| +----------------------------------------------------------------------+ +|
| +| | | ![d](fig4.png){#fig:subfig24 width="100%"} | +| | +|
| +----------------------------------------------------------------------+ +|
| +| | | ![e](fig5.png){width="100%"} | +| | +|
| +----------------------------------------------------------------------+ +|
| +| | | ![f](fig6.png){#fig:subfig26 width="100%"} | +| | +|
| +----------------------------------------------------------------------+ +|
| +| | | ![g](fig7.png){#fig:subfig27 width="100%"} | +| | +|
| +----------------------------------------------------------------------+ +|
| +| | | ![h](fig8.png){width="100%"} | +| | +|
| +----------------------------------------------------------------------+ +|
| +| | | ![i](fig9.png){#fig:subfig29 width="100%"} | +| | +|
| +----------------------------------------------------------------------+ Figure 2: Caption. a -- 1, b -- 2, c -- 3, d -- 4, e -- 5, f -- 6, g -- From c763a7e1aec0da59cb007c1767417c5701d98a9d Mon Sep 17 00:00:00 2001 From: Nikolay Yakimov Date: Wed, 1 May 2019 14:29:02 +0300 Subject: [PATCH 082/134] Access raw prefix definition via varfunc (incl. scope's definition); streamline templates; --- lib/Text/Pandoc/CrossRef/References/Blocks.hs | 2 +- .../Pandoc/CrossRef/References/Types/Ref.hs | 2 +- lib/Text/Pandoc/CrossRef/Util/Options.hs | 4 +++- lib/Text/Pandoc/CrossRef/Util/Prefixes.hs | 17 ++++++++--------- .../Pandoc/CrossRef/Util/Prefixes/Types.hs | 1 + lib/Text/Pandoc/CrossRef/Util/Template.hs | 18 ++++++++---------- .../Pandoc/CrossRef/Util/Template/Types.hs | 3 +-- lib/Text/Pandoc/CrossRef/Util/VarFunction.hs | 9 ++++++--- test/test-pandoc-crossref.hs | 8 +++++--- 9 files changed, 34 insertions(+), 30 deletions(-) diff --git a/lib/Text/Pandoc/CrossRef/References/Blocks.hs b/lib/Text/Pandoc/CrossRef/References/Blocks.hs index 5b97e7fc..1593372f 100644 --- a/lib/Text/Pandoc/CrossRef/References/Blocks.hs +++ b/lib/Text/Pandoc/CrossRef/References/Blocks.hs @@ -235,7 +235,7 @@ replaceAttr o scope label attrs title pfx , refPfx = pfx , refPfxRec = ropt , refCaption = applyTitleTemplate rec' - , refAttrs = metaAttrMap + , refAttrs = (`M.lookup` metaAttrMap) , refCaptionPosition = prefixCaptionPosition ropt } modify referenceData $ M.insert label' rec' diff --git a/lib/Text/Pandoc/CrossRef/References/Types/Ref.hs b/lib/Text/Pandoc/CrossRef/References/Types/Ref.hs index 87de6220..a9e61e11 100644 --- a/lib/Text/Pandoc/CrossRef/References/Types/Ref.hs +++ b/lib/Text/Pandoc/CrossRef/References/Types/Ref.hs @@ -39,7 +39,7 @@ data RefRec = RefRec { refIndex :: !Int -- global ordinal number for prefix , refPfx :: !String -- reference prefix, the part in label before : , refPfxRec :: !Prefix -- reference prefix, the part in label before : , refCaption :: Inlines -- caption after applying template; must be non-strict - , refAttrs :: !(M.Map String MetaValue) -- attribute map + , refAttrs :: !(String -> Maybe MetaValue) -- attribute map , refCaptionPosition :: !CaptionPosition } diff --git a/lib/Text/Pandoc/CrossRef/Util/Options.hs b/lib/Text/Pandoc/CrossRef/Util/Options.hs index cf979231..2e509442 100644 --- a/lib/Text/Pandoc/CrossRef/Util/Options.hs +++ b/lib/Text/Pandoc/CrossRef/Util/Options.hs @@ -70,4 +70,6 @@ getRefLabel opts ils getRefLabel _ _ = Nothing getTitleForListOf :: Options -> String -> PureErr Blocks -getTitleForListOf opts = fmap (flip applyBlockTemplate (const Nothing) . prefixListOfTitle) . getPfx opts +getTitleForListOf opts pfxn = do + pfx <- getPfx opts pfxn + return $ applyBlockTemplate (prefixListOfTitle pfx) (prefixDef pfx) diff --git a/lib/Text/Pandoc/CrossRef/Util/Prefixes.hs b/lib/Text/Pandoc/CrossRef/Util/Prefixes.hs index 380bc920..07c175a5 100644 --- a/lib/Text/Pandoc/CrossRef/Util/Prefixes.hs +++ b/lib/Text/Pandoc/CrossRef/Util/Prefixes.hs @@ -37,13 +37,13 @@ getPrefixes varN dtv | Just (MetaMap m) <- lookupSettings varN dtv = let m2p k (MetaMap kv') = Prefix { - prefixCaptionTemplate = mkT $ getTemplInline "captionTemplate" - , prefixReferenceTemplate = mkT $ getTemplInline "referenceTemplate" - , prefixReferenceIndexTemplate = mkT $ getTemplInline "referenceIndexTemplate" - , prefixCaptionIndexTemplate = mkT $ getTemplInline "captionIndexTemplate" - , prefixListItemTemplate = mkT $ getTemplInline "listItemTemplate" - , prefixCollectedCaptionTemplate = mkT $ getTemplInline "collectedCaptionTemplate" - , prefixListOfTitle = mkT $ getTemplBlock "listOfTitle" + prefixCaptionTemplate = makeTemplate $ getTemplInline "captionTemplate" + , prefixReferenceTemplate = makeTemplate $ getTemplInline "referenceTemplate" + , prefixReferenceIndexTemplate = makeTemplate $ getTemplInline "referenceIndexTemplate" + , prefixCaptionIndexTemplate = makeTemplate $ getTemplInline "captionIndexTemplate" + , prefixListItemTemplate = makeTemplate $ getTemplInline "listItemTemplate" + , prefixCollectedCaptionTemplate = makeTemplate $ getTemplInline "collectedCaptionTemplate" + , prefixListOfTitle = makeTemplate $ getTemplBlock "listOfTitle" , prefixCollectedCaptionDelim = getMetaInlines "collectedCaptionDelim" kv , prefixScope = getMetaStringList "scope" kv , prefixNumbering = @@ -58,14 +58,13 @@ getPrefixes varN dtv "above" -> Above _ -> Below , prefixSub = m2p k . (`merge` MetaMap kv') <$> lookupSettings "sub" (Settings (Meta kv') <> from) + , prefixDef = (`lookupSettings` kv) } where kv = Settings (Meta kv') <> from <> dtv from | Just fromRef <- M.lookup "from" kv' , Just (MetaMap kv'') <- M.lookup (toString "from" fromRef) m = Settings (Meta kv'') | otherwise = mempty - mkT :: MakeTemplate a => ElemT a -> a - mkT = makeTemplate kv getTemplInline = getTemplDefault getMetaInlines getTemplBlock = getTemplDefault getMetaBlock getTemplDefault f n = diff --git a/lib/Text/Pandoc/CrossRef/Util/Prefixes/Types.hs b/lib/Text/Pandoc/CrossRef/Util/Prefixes/Types.hs index 85238c1c..91a064de 100644 --- a/lib/Text/Pandoc/CrossRef/Util/Prefixes/Types.hs +++ b/lib/Text/Pandoc/CrossRef/Util/Prefixes/Types.hs @@ -45,4 +45,5 @@ data Prefix = Prefix { , prefixSubcaptionsGrid :: !Bool , prefixCaptionPosition :: !CaptionPosition , prefixSub :: !(Maybe Prefix) + , prefixDef :: !(String -> Maybe MetaValue) } diff --git a/lib/Text/Pandoc/CrossRef/Util/Template.hs b/lib/Text/Pandoc/CrossRef/Util/Template.hs index 3fa37cbc..a19b5080 100644 --- a/lib/Text/Pandoc/CrossRef/Util/Template.hs +++ b/lib/Text/Pandoc/CrossRef/Util/Template.hs @@ -35,7 +35,6 @@ import Text.Pandoc.Definition import Text.Pandoc.Builder import Text.Pandoc.Generic import Text.Pandoc.CrossRef.Util.Meta -import Text.Pandoc.CrossRef.Util.Settings.Types import Text.Pandoc.CrossRef.Util.Template.Types import Control.Applicative hiding (many, optional) import Text.Read hiding ((<++), (+++)) @@ -70,26 +69,25 @@ parse = uncurry <$> (ParseRes <$> var) <*> option ("", "") ps <* eof instance MakeTemplate Template where type ElemT Template = Inlines - makeTemplate dtv xs' = Template (genTemplate dtv xs') + makeTemplate xs' = Template (genTemplate xs') instance MakeTemplate BlockTemplate where type ElemT BlockTemplate = Blocks - makeTemplate dtv xs' = BlockTemplate (genTemplate dtv xs') + makeTemplate xs' = BlockTemplate (genTemplate xs') instance MakeTemplate RefTemplate where type ElemT RefTemplate = Inlines - makeTemplate dtv xs' = RefTemplate $ \vars cap -> g (vf vars cap) - where Template g = makeTemplate dtv xs' + makeTemplate xs' = RefTemplate $ \vars cap -> g (vf vars cap) + where Template g = makeTemplate xs' vf vars cap (vc:vs) - | isUpper vc && cap = capitalize lookup' var - | otherwise = lookup' var + | isUpper vc && cap = capitalize vars var + | otherwise = vars var where var = toLower vc : vs - lookup' x = vars x <|> lookupSettings x dtv vf _ _ [] = error "Empty variable name" -genTemplate :: (Data a) => Settings -> Many a -> VarFunc -> Many a -genTemplate dtv xs' vf = fromList $ scan (\var -> vf var <|> lookupSettings var dtv) $ toList xs' +genTemplate :: (Data a) => Many a -> VarFunc -> Many a +genTemplate xs' vf = fromList $ scan vf $ toList xs' scan :: (Data a) => VarFunc -> [a] -> [a] scan = bottomUp . go diff --git a/lib/Text/Pandoc/CrossRef/Util/Template/Types.hs b/lib/Text/Pandoc/CrossRef/Util/Template/Types.hs index 3fad90c2..e375f204 100644 --- a/lib/Text/Pandoc/CrossRef/Util/Template/Types.hs +++ b/lib/Text/Pandoc/CrossRef/Util/Template/Types.hs @@ -24,7 +24,6 @@ module Text.Pandoc.CrossRef.Util.Template.Types where import Text.Pandoc.Definition import Text.Pandoc.Builder -import Text.Pandoc.CrossRef.Util.Settings.Types type VarFunc = String -> Maybe MetaValue newtype Template = Template { applyTemplate :: VarFunc -> Inlines } @@ -33,4 +32,4 @@ newtype BlockTemplate = BlockTemplate { applyBlockTemplate :: VarFunc -> Blocks class MakeTemplate a where type ElemT a - makeTemplate :: Settings -> ElemT a -> a + makeTemplate :: ElemT a -> a diff --git a/lib/Text/Pandoc/CrossRef/Util/VarFunction.hs b/lib/Text/Pandoc/CrossRef/Util/VarFunction.hs index 9a0b3aee..5932f468 100644 --- a/lib/Text/Pandoc/CrossRef/Util/VarFunction.hs +++ b/lib/Text/Pandoc/CrossRef/Util/VarFunction.hs @@ -22,12 +22,13 @@ with this program; if not, write to the Free Software Foundation, Inc., module Text.Pandoc.CrossRef.Util.VarFunction where +import Control.Applicative import Text.Pandoc.Definition import qualified Text.Pandoc.Builder as B import Data.List -import qualified Data.Map as M -import Text.Pandoc.CrossRef.References.Types as Types +import Text.Pandoc.CrossRef.References.Types +import Text.Pandoc.CrossRef.Util.Prefixes.Types defaultVarFunc :: (RefRec -> String -> Maybe MetaValue) -> RefRec -> String -> Maybe MetaValue @@ -42,4 +43,6 @@ defaultVarFunc self RefRec{..} x = case x of _ | Just y <- stripPrefix "s." x , Just rs <- refScope -> self rs y - _ -> M.lookup x refAttrs + _ | Just y <- stripPrefix "def." x + -> prefixDef refPfxRec y + _ -> refAttrs x <|> prefixDef refPfxRec x diff --git a/test/test-pandoc-crossref.hs b/test/test-pandoc-crossref.hs index 13c63e4b..c3a40135 100644 --- a/test/test-pandoc-crossref.hs +++ b/test/test-pandoc-crossref.hs @@ -19,7 +19,7 @@ with this program; if not, write to the Free Software Foundation, Inc., -} {-# OPTIONS_GHC -fno-warn-orphans #-} -{-# LANGUAGE FlexibleContexts, CPP, OverloadedStrings, TypeSynonymInstances +{-# LANGUAGE FlexibleContexts, CPP, OverloadedStrings , FlexibleInstances, StandaloneDeriving #-} import Test.Hspec import Text.Pandoc hiding (getDataFileName, Template) @@ -306,10 +306,10 @@ main = hspec $ do describe "Util.Template" $ it "Applies templates" $ let template=Util.Template.makeTemplate - (defaultMeta <> Settings (Meta (M.singleton "figureTitle" (toMetaValue $ text "Figure")))) (displayMath "figureTitle" <> displayMath "i" <> displayMath "t") vf "i" = Just $ MetaInlines $ toList $ text "1" vf "t" = Just $ MetaInlines $ toList $ text "title" + vf "figureTitle" = Just $ toMetaValue $ text "Figure" vf _ = Nothing in Util.Template.applyTemplate template vf `shouldBe` (str "Figure" <> str "1" <> str "title") @@ -368,7 +368,7 @@ refRec' ref i tit cap = , refLevel=0 , refPfx=pfx , refLabel=ref - , refAttrs = M.empty + , refAttrs = const Nothing , refPfxRec = pfxRec , refCaptionPosition = Below } @@ -394,6 +394,8 @@ instance Show Prefix where show _ = "Prefix{}" instance Show Template where show _ = "Template{}" +instance Show (String -> Maybe MetaValue) where + show _ = "String -> Maybe MetaValue" deriving instance Show RefRec deriving instance Show CaptionPosition deriving instance Show CounterRec From 097bfe57623517a6fc5caa25838e6c1c6f577ea3 Mon Sep 17 00:00:00 2001 From: Nikolay Yakimov Date: Wed, 1 May 2019 14:29:17 +0300 Subject: [PATCH 083/134] Update demo.md --- docs/demo/demo.md | 13 +++++--- test/demo-chapters.inc | 76 +++++++++++++++++++++++------------------- test/demo.inc | 66 +++++++++++++++++++----------------- 3 files changed, 86 insertions(+), 69 deletions(-) diff --git a/docs/demo/demo.md b/docs/demo/demo.md index a340f7c1..e560d388 100644 --- a/docs/demo/demo.md +++ b/docs/demo/demo.md @@ -18,7 +18,12 @@ prefixes: ## List of Tables captionTemplate: | *$$title$$ $$i$$*$$titleDelim$$ $$t$$ -autoSectionLabels: True + sec: + scope: sec + sub: + referenceIndexTemplate: $$s.i%.$$$$i$$ + captionTemplate: $$i$$. $$t$$ +autoSectionLabels: sec title: pandoc-crossref demo document --- @@ -132,11 +137,11 @@ $$ S(x) = \int_{x_1}^{x_2} a x+b \ \mathrm{d}x $$ {#eq:eqn2} It's also possible to show lists of figures and tables, like this: -\listoffigures +\listof{fig} -\listoftables +\listof{tbl} -\listoflistings +\listof{lst} # Appendix A. Custom labels {label=AppA} diff --git a/test/demo-chapters.inc b/test/demo-chapters.inc index 4dfbb912..74f5bcf3 100644 --- a/test/demo-chapters.inc +++ b/test/demo-chapters.inc @@ -1,28 +1,32 @@ - [Para [Str "This",Space,Str "is",Space,Str "a",Space,Str "demo",Space,Str "file",Space,Str "for",Space,Str "pandoc-crossref.",Space,Str "With",Space,Str "this",Space,Str "filter,",Space,Str "you",Space,Str "can",Space,Str "cross-reference",Space,Str "figures",Space,Str "(see",Space,Str "figs.\160\&1.1-1.3),",Space,Str "display",Space,Str "equations",Space,Str "(see",Space,Str "eq.\160\&2.1),",Space,Str "tables",Space,Str "(see",Space,Str "tbl.\160\&3.1)",Space,Str "and",Space,Str "sections",Space,Str "(",Str "secs.\160\&1,",Space,Str "2,",Space,Str "4.1-4.3)"] + [Para [Str "This",Space,Str "is",Space,Str "a",Space,Str "demo",Space,Str "file",Space,Str "for",Space,Str "pandoc-crossref.",Space,Str "With",Space,Str "this",Space,Str "filter,",Space,Str "you",Space,Str "can",Space,Str "cross-reference",Space,Str "figures",Space,Str "(see",Space,Str "figs.\160\&2-4),",Space,Str "display",Space,Str "equations",Space,Str "(see",Space,Str "eq.\160\&1),",Space,Str "tables",Space,Str "(see",Space,Str "tbl.\160\&1)",Space,Str "and",Space,Str "sections",Space,Str "(",Str "secs.\160\&1,",Space,Str "2,",Space,Str "secs.\160.41-.43)"] ,Para [Str "For",Space,Str "immediate",Space,Str "example,",Space,Str "see",Space,Str "fig.\160\&1"] - ,Para [Image ("fig:figure0",[],[]) [Str "Figure",Space,Str "#",Space,Str "1:",Space,Str "A",Space,Str "figure"] ("img1.jpg","fig:")] - ,Para [Str "There",Space,Str "is",Space,Str "also",Space,Str "support",Space,Str "for",Space,Str "code",Space,Str "blocks,",Space,Str "for",Space,Str "example,",Space,Str "lsts.\160\&4.1-4.3"] - ,Para [Str "It\8217s",Space,Str "possible",Space,Str "to",Space,Str "capitalize",Space,Str "reference",Space,Str "prefixes,",Space,Str "like",Space,Str "this:",Space,Str "Fig.\160\&1.1."] - ,Para [Str "In",Space,Str "case",Space,Str "of",Space,Str "multiple",Space,Str "references,",Space,Str "capitalization",Space,Str "is",Space,Str "determined",Space,Str "by",Space,Str "first",Space,Str "reference.",Space,Str "Figs.\160\&1.1,",Space,Str "1.2",Space,Str "is",Space,Str "capitalized,",Space,Str "while",Space,Str "figs.\160\&1.1,",Space,Str "1.2",Space,Str "is",Space,Str "not."] - ,Para [Str "It",Space,Str "is",Space,Str "also",Space,Str "possible",Space,Str "to",Space,Str "mix",Space,Str "different",Space,Str "references,",Space,Str "like",Space,Str "fig.\160\&1.1,",Space,Str "tbl.\160\&3.1,",Space,Str "lsts.\160\&4.1,",Space,Str "4.2,",Space,Str "figs.\160\&1.2,",Space,Str "1.3,",Space,Str "which",Space,Str "will",Space,Str "be",Space,Str "grouped",Space,Str "in",Space,Str "order",Space,Str "they",Space,Str "are",Space,Str "specified.",Space,Str "You",Space,Str "can",Space,Str "even",Space,Str "intermix",Space,Str "this",Space,Str "with",Space,Str "regular",Space,Str "citations,",Space,Str "although",Space,Str "it\8217s",Space,Str "not",Space,Str "recommended:",Space,Str "fig.\160\&1.1,",Space,Str "tbl.\160\&3.1,",Space,Cite [Citation {citationId = "unprocessedCitation", citationPrefix = [], citationSuffix = [], citationMode = NormalCitation, citationNoteNum = 0, citationHash = 0}] [Str "[@unprocessedCitation]"]] - ,Para [Str "You",Space,Str "can",Space,Str "also",Space,Str "have",Space,Str "custom",Space,Str "chapter",Space,Str "reference",Space,Str "labels,",Space,Str "like",Space,Str "sec.\160AppA.CustLab"] - ,Para [Str "Subfigures",Space,Str "are",Space,Str "supported,",Space,Str "see",Space,Str "figs.\160\&1.4,",Space,Str "1.4",Space,Str "(b)"] + ,Para [Image ("fig:figure0",[],[]) [Str "Figure",Space,Str "#\160\&1:",Space,Str "A",Space,Str "figure"] ("img1.jpg","fig:")] + ,Para [Str "There",Space,Str "is",Space,Str "also",Space,Str "support",Space,Str "for",Space,Str "code",Space,Str "blocks,",Space,Str "for",Space,Str "example,",Space,Str "lsts.\160\&1-3"] + ,Para [Str "It\8217s",Space,Str "possible",Space,Str "to",Space,Str "capitalize",Space,Str "reference",Space,Str "prefixes,",Space,Str "like",Space,Str "this:",Space,Str "Fig.\160\&2."] + ,Para [Str "In",Space,Str "case",Space,Str "of",Space,Str "multiple",Space,Str "references,",Space,Str "capitalization",Space,Str "is",Space,Str "determined",Space,Str "by",Space,Str "first",Space,Str "reference.",Space,Str "Figs.\160\&2,",Space,Str "3",Space,Str "is",Space,Str "capitalized,",Space,Str "while",Space,Str "figs.\160\&2,",Space,Str "3",Space,Str "is",Space,Str "not."] + ,Para [Str "It",Space,Str "is",Space,Str "also",Space,Str "possible",Space,Str "to",Space,Str "mix",Space,Str "different",Space,Str "references,",Space,Str "like",Space,Str "fig.\160\&2,",Space,Str "tbl.\160\&1,",Space,Str "lsts.\160\&1,",Space,Str "2,",Space,Str "figs.\160\&3,",Space,Str "4,",Space,Str "which",Space,Str "will",Space,Str "be",Space,Str "grouped",Space,Str "in",Space,Str "order",Space,Str "they",Space,Str "are",Space,Str "specified.",Space,Str "You",Space,Str "can",Space,Str "even",Space,Str "intermix",Space,Str "this",Space,Str "with",Space,Str "regular",Space,Str "citations,",Space,Str "although",Space,Str "it\8217s",Space,Str "not",Space,Str "recommended:",Space,Str "fig.\160\&2,",Space,Str "tbl.\160\&1,",Space,Cite [Citation {citationId = "unprocessedCitation", citationPrefix = [], citationSuffix = [], citationMode = NormalCitation, citationNoteNum = 0, citationHash = 0}] [Str "[@unprocessedCitation]"]] + ,Para [Str "You",Space,Str "can",Space,Str "also",Space,Str "have",Space,Str "custom",Space,Str "chapter",Space,Str "reference",Space,Str "labels,",Space,Str "like",Space,Str "sec.\160.AppACustLab"] + ,Para [Str "Subfigures",Space,Str "are",Space,Str "supported,",Space,Str "see",Space,Str "fig.\160\&6,",Space,Str "fig.\160\&6",Space,Str "(b)"] ,Header 1 ("sec:sec1",[],[]) [Str "Chapter",Space,Str "1.",Space,Str "Figures"] - ,Para [Image ("fig:figure1",[],[]) [Str "Figure",Space,Str "#",Space,Str "1.1:",Space,Str "First",Space,Str "figure"] ("img1.jpg","fig:")] - ,Para [Image ("fig:figure2",[],[]) [Str "Figure",Space,Str "#",Space,Str "1.2:",Space,Str "Second",Space,Str "figure"] ("img2.jpg","fig:")] - ,Para [Image ("fig:figure3",[],[]) [Str "Figure",Space,Str "#",Space,Str "1.3:",Space,Str "Third",Space,Str "figure"] ("img3.jpg","fig:")] - ,Para [Image ("",[],[]) [Str "Unlabelled",Space,Str "image"] ("img1.jpg","fig:")] - ,Div ("fig:subfigures",["subfigures"],[]) - [Para [Image ("",[],[]) [Str "a"] ("img1.jpg","fig:")] - ,Para [Image ("fig:subfigureB",[],[]) [Str "b"] ("img1.jpg","fig:")] - ,Para [Str "Figure",Space,Str "#",Space,Str "1.4:",Space,Str "Subfigures",Space,Str "caption.",Space,Str "a",Space,Str "\8212",Space,Str "Subfigure",Space,Str "a,",Space,Str "b",Space,Str "\8212",Space,Str "Subfigure",Space,Str "b"]] + ,Para [Image ("fig:figure1",[],[]) [Str "Figure",Space,Str "#\160\&2:",Space,Str "First",Space,Str "figure"] ("img1.jpg","fig:")] + ,Para [Image ("fig:figure2",[],[]) [Str "Figure",Space,Str "#\160\&3:",Space,Str "Second",Space,Str "figure"] ("img2.jpg","fig:")] + ,Para [Image ("fig:figure3",[],[]) [Str "Figure",Space,Str "#\160\&4:",Space,Str "Third",Space,Str "figure"] ("img3.jpg","fig:")] + ,Para [Image ("",[],[]) [Str "Figure",Space,Str "#\160\&5:",Space,Str "Unlabelled",Space,Str "image"] ("img1.jpg","fig:")] + ,Div ("fig:subfigures",["subcaption"],[]) + [Table [] [AlignCenter] [0.99] + [] + [[[Div ("",[],[]) + [Para [Image ("",[],[("width","100%")]) [Str "a"] ("img1.jpg","fig:")]]]] + ,[[Div ("",[],[]) + [Para [Image ("fig:subfigureB",[],[("width","100%")]) [Str "b"] ("img1.jpg","fig:")]]]]] + ,Para [Str "Figure",Space,Str "#\160\&6:",Space,Str "Subfigures",Space,Str "caption.",Space,Span ("",[],[]) [Str "a",Space,Str "\8211",Space,Str "Subfigure",Space,Str "a,",Space,Str "b",Space,Str "\8211",Space,Str "Subfigure",Space,Str "b"]]] ,Header 1 ("sec:sec2",[],[]) [Str "Chapter",Space,Str "2.",Space,Str "Equations"] ,Para [Str "Display",Space,Str "equations",Space,Str "are",Space,Str "labelled",Space,Str "and",Space,Str "numbered"] - ,Para [Span ("eq:eqn1",[],[]) [Math DisplayMath " P_i(x) = \\sum_i a_i x^i \\qquad(2.1)"]] - ,Para [Str "Since",Space,Str "0.1.6.0",Space,Str "those",Space,Str "can",Space,Str "also",Space,Str "appear",Space,Str "in",Space,Str "the",Space,Str "middle",Space,Str "of",Space,Str "paragraph",SoftBreak,Span ("eq:quadr",[],[]) [Math DisplayMath "a x^2 + b x^2 + c = 0\\qquad(2.2)"],Space,Str "like",Space,Str "this."] + ,Para [Span ("eq:eqn1",[],[]) [Math DisplayMath " P_i(x) = \\sum_i a_i x^i \\qquad(1)"]] + ,Para [Str "Since",Space,Str "0.1.6.0",Space,Str "those",Space,Str "can",Space,Str "also",Space,Str "appear",Space,Str "in",Space,Str "the",Space,Str "middle",Space,Str "of",Space,Str "paragraph",SoftBreak,Span ("eq:quadr",[],[]) [Math DisplayMath "a x^2 + b x^2 + c = 0\\qquad(2)"],Space,Str "like",Space,Str "this."] ,Header 1 ("sec:chapter-3.-tables",[],[]) [Str "Chapter",Space,Str "3.",Space,Str "Tables"] ,Div ("tbl:table1",[],[]) - [Table [Emph [Str "Table",Space,Str "3.1"],Str ":",Space,Str "Table",Space,Str "example"] [AlignLeft,AlignLeft] [0.0,0.0] + [Table [Emph [Str "Table",Space,Str "1"],Str ":",Space,Str "Table",Space,Str "example"] [AlignLeft,AlignLeft] [0.0,0.0] [[Plain [Str "First",Space,Str "Header"]] ,[Plain [Str "Second",Space,Str "Header"]]] [[[Plain [Str "Content",Space,Str "Cell"]] @@ -42,39 +46,41 @@ ,Header 2 ("sec:caption-attr",[],[]) [Code ("",[],[]) "caption",Space,Str "attribute"] ,Para [Code ("",[],[]) "caption",Space,Str "attribute",Space,Str "will",Space,Str "be",Space,Str "treated",Space,Str "as",Space,Str "code",Space,Str "block",Space,Str "caption.",Space,Str "If",Space,Str "code",Space,Str "block",Space,Str "has",Space,Str "both",Space,Str "id",Space,Str "and",Space,Code ("",[],[]) "caption",Space,Str "attributes,",Space,Str "it",Space,Str "will",Space,Str "be",Space,Str "treated",Space,Str "as",Space,Str "numbered",Space,Str "code",Space,Str "block."] ,Div ("lst:captionAttr",["listing","haskell"],[]) - [Para [Str "Listing",Space,Str "4.1:",Space,Str "Listing",Space,Str "caption"] + [Para [Str "Listing\160\&1:",Space,Str "Listing",Space,Str "caption"] ,CodeBlock ("",["haskell"],[]) "main :: IO ()\nmain = putStrLn \"Hello World!\""] ,RawBlock (Format "tex") "\\pagebreak" ,Header 2 ("sec:table-capts",[],[]) [Str "Table-style",Space,Str "captions"] ,Para [Str "Enabled",Space,Str "with",Space,Code ("",[],[]) "codeBlockCaptions",Space,Str "metadata",Space,Str "option.",Space,Str "If",Space,Str "code",Space,Str "block",Space,Str "is",Space,Str "immediately",SoftBreak,Str "adjacent",Space,Str "to",Space,Str "paragraph,",Space,Str "starting",Space,Str "with",Space,Code ("",[],[]) "Listing:",Space,Str "or",Space,Code ("",[],[]) ":",Str ",",Space,Str "said",Space,Str "paragraph",Space,Str "will",Space,Str "be",SoftBreak,Str "treated",Space,Str "as",Space,Str "code",Space,Str "block",Space,Str "caption."] ,Div ("lst:tableCaption",["listing","haskell"],[]) - [Para [Str "Listing",Space,Str "4.2:",Space,Str "Listing",Space,Str "caption"] + [Para [Str "Listing\160\&2:",Space,Str "Listing",Space,Str "caption"] ,CodeBlock ("",["haskell"],[]) "main :: IO ()\nmain = putStrLn \"Hello World!\""] ,Header 2 ("sec:wrapping-div",[],[]) [Str "Wrapping",Space,Str "div"] ,Para [Str "Wrapping",Space,Str "code",Space,Str "block",Space,Str "without",Space,Str "label",Space,Str "in",Space,Str "a",Space,Str "div",Space,Str "with",Space,Str "id",Space,Code ("",[],[]) "lst:...",Space,Str "and",Space,Str "class,",Space,Str "starting",Space,Str "with",Space,Code ("",[],[]) "listing",Str ",",Space,Str "and",Space,Str "adding",Space,Str "paragraph",Space,Str "before",Space,Str "code",Space,Str "block,",Space,Str "but",Space,Str "inside",Space,Str "div,",Space,Str "will",Space,Str "treat",Space,Str "said",Space,Str "paragraph",Space,Str "as",Space,Str "code",Space,Str "block",Space,Str "caption."] - ,Div ("lst:wrappingDiv",["listing","haskell"],[]) - [Para [Str "Listing",Space,Str "4.3:",Space,Str "Listing",Space,Str "caption"] + ,Div ("lst:wrappingDiv",["listing"],[]) + [Para [Str "Listing\160\&3:",Space] + ,Para [Str "Listing",Space,Str "caption"] ,CodeBlock ("",["haskell"],[]) "main :: IO ()\nmain = putStrLn \"Hello World!\""] ,Header 1 ("sec:unnumbered-chapter.",["unnumbered"],[]) [Str "Unnumbered",Space,Str "chapter."] - ,Para [Str "This",Space,Str "chapter",Space,Str "doesn\8217t",Space,Str "change",Space,Str "chapter",Space,Str "prefix",Space,Str "of",Space,Str "referenced",Space,Str "elements,",Space,Str "instead",Space,Str "keeping",Space,Str "number",Space,Str "of",Space,Str "previous",Space,Str "chapter,",Space,Str "e.g.",SoftBreak,Span ("eq:eqn2",[],[]) [Math DisplayMath " S(x) = \\int_{x_1}^{x_2} a x+b \\ \\mathrm{d}x \\qquad(4.1)"]] + ,Para [Str "This",Space,Str "chapter",Space,Str "doesn\8217t",Space,Str "change",Space,Str "chapter",Space,Str "prefix",Space,Str "of",Space,Str "referenced",Space,Str "elements,",Space,Str "instead",Space,Str "keeping",Space,Str "number",Space,Str "of",Space,Str "previous",Space,Str "chapter,",Space,Str "e.g.",SoftBreak,Span ("eq:eqn2",[],[]) [Math DisplayMath " S(x) = \\int_{x_1}^{x_2} a x+b \\ \\mathrm{d}x \\qquad(3)"]] ,Header 1 ("sec:chapter-5.-reference-lists",[],[]) [Str "Chapter",Space,Str "5.",Space,Str "Reference",Space,Str "lists"] ,Para [Str "It\8217s",Space,Str "also",Space,Str "possible",Space,Str "to",Space,Str "show",Space,Str "lists",Space,Str "of",Space,Str "figures",Space,Str "and",Space,Str "tables,",Space,Str "like",Space,Str "this:"] ,Header 2 ("list-of-figures",[],[]) [Str "List",Space,Str "of",Space,Str "Figures"] ,Div ("",["list"],[]) - [Para [Str "1",Space,Str "A",Space,Str "figure"] - ,Para [Str "1.1",Space,Str "First",Space,Str "figure"] - ,Para [Str "1.2",Space,Str "Second",Space,Str "figure"] - ,Para [Str "1.3",Space,Str "Third",Space,Str "figure"] - ,Para [Str "1.4",Space,Str "Subfigure",Space,Str "a"] - ,Para [Str "1.4",Space,Str "Subfigure",Space,Str "b"] - ,Para [Str "1.4",Space,Str "Subfigures",Space,Str "caption"]] + [Para [Str "1.",Space,Str "A",Space,Str "figure"] + ,Para [Str "2.",Space,Str "First",Space,Str "figure"] + ,Para [Str "3.",Space,Str "Second",Space,Str "figure"] + ,Para [Str "4.",Space,Str "Third",Space,Str "figure"] + ,Para [Str "5.",Space,Str "Unlabelled",Space,Str "image"] + ,Para [Str "6.",Space,Str "Subfigures",Space,Str "caption.",Space,Span ("",[],[]) []] + ,Para [Str "a.",Space,Str "Subfigure",Space,Str "a"] + ,Para [Str "b.",Space,Str "Subfigure",Space,Str "b"]] ,Header 2 ("list-of-tables",[],[]) [Str "List",Space,Str "of",Space,Str "Tables"] ,Div ("",["list"],[]) - [Para [Str "3.1",Space,Str "Table",Space,Str "example"]] + [Para [Str "1.",Space,Str "Table",Space,Str "example"]] ,Header 1 ("",[],[]) [Str "List",Space,Str "of",Space,Str "Listings"] ,Div ("",["list"],[]) - [Para [Str "4.1",Space,Str "Listing",Space,Str "caption"] - ,Para [Str "4.2",Space,Str "Listing",Space,Str "caption"] - ,Para [Str "4.3",Space,Str "Listing",Space,Str "caption"]] + [Para [Str "1.",Space,Str "Listing",Space,Str "caption"] + ,Para [Str "2.",Space,Str "Listing",Space,Str "caption"] + ,Para [Str "3.",Space]] ,Header 1 ("sec:appendix-a.-custom-labels",[],[("label","AppA")]) [Str "Appendix",Space,Str "A.",Space,Str "Custom",Space,Str "labels"] ,Header 2 ("sec:custlabs",[],[("label","CustLab")]) [Str "This",Space,Str "section",Space,Str "will",Space,Str "have",Space,Str "custom",Space,Str "label"]] diff --git a/test/demo.inc b/test/demo.inc index 9f9ad399..74f5bcf3 100644 --- a/test/demo.inc +++ b/test/demo.inc @@ -1,21 +1,25 @@ - [Para [Str "This",Space,Str "is",Space,Str "a",Space,Str "demo",Space,Str "file",Space,Str "for",Space,Str "pandoc-crossref.",Space,Str "With",Space,Str "this",Space,Str "filter,",Space,Str "you",Space,Str "can",Space,Str "cross-reference",Space,Str "figures",Space,Str "(see",Space,Str "figs.\160\&2-4),",Space,Str "display",Space,Str "equations",Space,Str "(see",Space,Str "eq.\160\&1),",Space,Str "tables",Space,Str "(see",Space,Str "tbl.\160\&1)",Space,Str "and",Space,Str "sections",Space,Str "(",Str "secs.\160\&1,",Space,Str "2,",Space,Str "4.1-4.3)"] + [Para [Str "This",Space,Str "is",Space,Str "a",Space,Str "demo",Space,Str "file",Space,Str "for",Space,Str "pandoc-crossref.",Space,Str "With",Space,Str "this",Space,Str "filter,",Space,Str "you",Space,Str "can",Space,Str "cross-reference",Space,Str "figures",Space,Str "(see",Space,Str "figs.\160\&2-4),",Space,Str "display",Space,Str "equations",Space,Str "(see",Space,Str "eq.\160\&1),",Space,Str "tables",Space,Str "(see",Space,Str "tbl.\160\&1)",Space,Str "and",Space,Str "sections",Space,Str "(",Str "secs.\160\&1,",Space,Str "2,",Space,Str "secs.\160.41-.43)"] ,Para [Str "For",Space,Str "immediate",Space,Str "example,",Space,Str "see",Space,Str "fig.\160\&1"] - ,Para [Image ("fig:figure0",[],[]) [Str "Figure",Space,Str "#",Space,Str "1:",Space,Str "A",Space,Str "figure"] ("img1.jpg","fig:")] + ,Para [Image ("fig:figure0",[],[]) [Str "Figure",Space,Str "#\160\&1:",Space,Str "A",Space,Str "figure"] ("img1.jpg","fig:")] ,Para [Str "There",Space,Str "is",Space,Str "also",Space,Str "support",Space,Str "for",Space,Str "code",Space,Str "blocks,",Space,Str "for",Space,Str "example,",Space,Str "lsts.\160\&1-3"] ,Para [Str "It\8217s",Space,Str "possible",Space,Str "to",Space,Str "capitalize",Space,Str "reference",Space,Str "prefixes,",Space,Str "like",Space,Str "this:",Space,Str "Fig.\160\&2."] ,Para [Str "In",Space,Str "case",Space,Str "of",Space,Str "multiple",Space,Str "references,",Space,Str "capitalization",Space,Str "is",Space,Str "determined",Space,Str "by",Space,Str "first",Space,Str "reference.",Space,Str "Figs.\160\&2,",Space,Str "3",Space,Str "is",Space,Str "capitalized,",Space,Str "while",Space,Str "figs.\160\&2,",Space,Str "3",Space,Str "is",Space,Str "not."] ,Para [Str "It",Space,Str "is",Space,Str "also",Space,Str "possible",Space,Str "to",Space,Str "mix",Space,Str "different",Space,Str "references,",Space,Str "like",Space,Str "fig.\160\&2,",Space,Str "tbl.\160\&1,",Space,Str "lsts.\160\&1,",Space,Str "2,",Space,Str "figs.\160\&3,",Space,Str "4,",Space,Str "which",Space,Str "will",Space,Str "be",Space,Str "grouped",Space,Str "in",Space,Str "order",Space,Str "they",Space,Str "are",Space,Str "specified.",Space,Str "You",Space,Str "can",Space,Str "even",Space,Str "intermix",Space,Str "this",Space,Str "with",Space,Str "regular",Space,Str "citations,",Space,Str "although",Space,Str "it\8217s",Space,Str "not",Space,Str "recommended:",Space,Str "fig.\160\&2,",Space,Str "tbl.\160\&1,",Space,Cite [Citation {citationId = "unprocessedCitation", citationPrefix = [], citationSuffix = [], citationMode = NormalCitation, citationNoteNum = 0, citationHash = 0}] [Str "[@unprocessedCitation]"]] - ,Para [Str "You",Space,Str "can",Space,Str "also",Space,Str "have",Space,Str "custom",Space,Str "chapter",Space,Str "reference",Space,Str "labels,",Space,Str "like",Space,Str "sec.\160AppA.CustLab"] - ,Para [Str "Subfigures",Space,Str "are",Space,Str "supported,",Space,Str "see",Space,Str "figs.\160\&5,",Space,Str "5",Space,Str "(b)"] + ,Para [Str "You",Space,Str "can",Space,Str "also",Space,Str "have",Space,Str "custom",Space,Str "chapter",Space,Str "reference",Space,Str "labels,",Space,Str "like",Space,Str "sec.\160.AppACustLab"] + ,Para [Str "Subfigures",Space,Str "are",Space,Str "supported,",Space,Str "see",Space,Str "fig.\160\&6,",Space,Str "fig.\160\&6",Space,Str "(b)"] ,Header 1 ("sec:sec1",[],[]) [Str "Chapter",Space,Str "1.",Space,Str "Figures"] - ,Para [Image ("fig:figure1",[],[]) [Str "Figure",Space,Str "#",Space,Str "2:",Space,Str "First",Space,Str "figure"] ("img1.jpg","fig:")] - ,Para [Image ("fig:figure2",[],[]) [Str "Figure",Space,Str "#",Space,Str "3:",Space,Str "Second",Space,Str "figure"] ("img2.jpg","fig:")] - ,Para [Image ("fig:figure3",[],[]) [Str "Figure",Space,Str "#",Space,Str "4:",Space,Str "Third",Space,Str "figure"] ("img3.jpg","fig:")] - ,Para [Image ("",[],[]) [Str "Unlabelled",Space,Str "image"] ("img1.jpg","fig:")] - ,Div ("fig:subfigures",["subfigures"],[]) - [Para [Image ("",[],[]) [Str "a"] ("img1.jpg","fig:")] - ,Para [Image ("fig:subfigureB",[],[]) [Str "b"] ("img1.jpg","fig:")] - ,Para [Str "Figure",Space,Str "#",Space,Str "5:",Space,Str "Subfigures",Space,Str "caption.",Space,Str "a",Space,Str "\8212",Space,Str "Subfigure",Space,Str "a,",Space,Str "b",Space,Str "\8212",Space,Str "Subfigure",Space,Str "b"]] + ,Para [Image ("fig:figure1",[],[]) [Str "Figure",Space,Str "#\160\&2:",Space,Str "First",Space,Str "figure"] ("img1.jpg","fig:")] + ,Para [Image ("fig:figure2",[],[]) [Str "Figure",Space,Str "#\160\&3:",Space,Str "Second",Space,Str "figure"] ("img2.jpg","fig:")] + ,Para [Image ("fig:figure3",[],[]) [Str "Figure",Space,Str "#\160\&4:",Space,Str "Third",Space,Str "figure"] ("img3.jpg","fig:")] + ,Para [Image ("",[],[]) [Str "Figure",Space,Str "#\160\&5:",Space,Str "Unlabelled",Space,Str "image"] ("img1.jpg","fig:")] + ,Div ("fig:subfigures",["subcaption"],[]) + [Table [] [AlignCenter] [0.99] + [] + [[[Div ("",[],[]) + [Para [Image ("",[],[("width","100%")]) [Str "a"] ("img1.jpg","fig:")]]]] + ,[[Div ("",[],[]) + [Para [Image ("fig:subfigureB",[],[("width","100%")]) [Str "b"] ("img1.jpg","fig:")]]]]] + ,Para [Str "Figure",Space,Str "#\160\&6:",Space,Str "Subfigures",Space,Str "caption.",Space,Span ("",[],[]) [Str "a",Space,Str "\8211",Space,Str "Subfigure",Space,Str "a,",Space,Str "b",Space,Str "\8211",Space,Str "Subfigure",Space,Str "b"]]] ,Header 1 ("sec:sec2",[],[]) [Str "Chapter",Space,Str "2.",Space,Str "Equations"] ,Para [Str "Display",Space,Str "equations",Space,Str "are",Space,Str "labelled",Space,Str "and",Space,Str "numbered"] ,Para [Span ("eq:eqn1",[],[]) [Math DisplayMath " P_i(x) = \\sum_i a_i x^i \\qquad(1)"]] @@ -42,39 +46,41 @@ ,Header 2 ("sec:caption-attr",[],[]) [Code ("",[],[]) "caption",Space,Str "attribute"] ,Para [Code ("",[],[]) "caption",Space,Str "attribute",Space,Str "will",Space,Str "be",Space,Str "treated",Space,Str "as",Space,Str "code",Space,Str "block",Space,Str "caption.",Space,Str "If",Space,Str "code",Space,Str "block",Space,Str "has",Space,Str "both",Space,Str "id",Space,Str "and",Space,Code ("",[],[]) "caption",Space,Str "attributes,",Space,Str "it",Space,Str "will",Space,Str "be",Space,Str "treated",Space,Str "as",Space,Str "numbered",Space,Str "code",Space,Str "block."] ,Div ("lst:captionAttr",["listing","haskell"],[]) - [Para [Str "Listing",Space,Str "1:",Space,Str "Listing",Space,Str "caption"] + [Para [Str "Listing\160\&1:",Space,Str "Listing",Space,Str "caption"] ,CodeBlock ("",["haskell"],[]) "main :: IO ()\nmain = putStrLn \"Hello World!\""] ,RawBlock (Format "tex") "\\pagebreak" ,Header 2 ("sec:table-capts",[],[]) [Str "Table-style",Space,Str "captions"] ,Para [Str "Enabled",Space,Str "with",Space,Code ("",[],[]) "codeBlockCaptions",Space,Str "metadata",Space,Str "option.",Space,Str "If",Space,Str "code",Space,Str "block",Space,Str "is",Space,Str "immediately",SoftBreak,Str "adjacent",Space,Str "to",Space,Str "paragraph,",Space,Str "starting",Space,Str "with",Space,Code ("",[],[]) "Listing:",Space,Str "or",Space,Code ("",[],[]) ":",Str ",",Space,Str "said",Space,Str "paragraph",Space,Str "will",Space,Str "be",SoftBreak,Str "treated",Space,Str "as",Space,Str "code",Space,Str "block",Space,Str "caption."] ,Div ("lst:tableCaption",["listing","haskell"],[]) - [Para [Str "Listing",Space,Str "2:",Space,Str "Listing",Space,Str "caption"] + [Para [Str "Listing\160\&2:",Space,Str "Listing",Space,Str "caption"] ,CodeBlock ("",["haskell"],[]) "main :: IO ()\nmain = putStrLn \"Hello World!\""] ,Header 2 ("sec:wrapping-div",[],[]) [Str "Wrapping",Space,Str "div"] ,Para [Str "Wrapping",Space,Str "code",Space,Str "block",Space,Str "without",Space,Str "label",Space,Str "in",Space,Str "a",Space,Str "div",Space,Str "with",Space,Str "id",Space,Code ("",[],[]) "lst:...",Space,Str "and",Space,Str "class,",Space,Str "starting",Space,Str "with",Space,Code ("",[],[]) "listing",Str ",",Space,Str "and",Space,Str "adding",Space,Str "paragraph",Space,Str "before",Space,Str "code",Space,Str "block,",Space,Str "but",Space,Str "inside",Space,Str "div,",Space,Str "will",Space,Str "treat",Space,Str "said",Space,Str "paragraph",Space,Str "as",Space,Str "code",Space,Str "block",Space,Str "caption."] - ,Div ("lst:wrappingDiv",["listing","haskell"],[]) - [Para [Str "Listing",Space,Str "3:",Space,Str "Listing",Space,Str "caption"] + ,Div ("lst:wrappingDiv",["listing"],[]) + [Para [Str "Listing\160\&3:",Space] + ,Para [Str "Listing",Space,Str "caption"] ,CodeBlock ("",["haskell"],[]) "main :: IO ()\nmain = putStrLn \"Hello World!\""] ,Header 1 ("sec:unnumbered-chapter.",["unnumbered"],[]) [Str "Unnumbered",Space,Str "chapter."] ,Para [Str "This",Space,Str "chapter",Space,Str "doesn\8217t",Space,Str "change",Space,Str "chapter",Space,Str "prefix",Space,Str "of",Space,Str "referenced",Space,Str "elements,",Space,Str "instead",Space,Str "keeping",Space,Str "number",Space,Str "of",Space,Str "previous",Space,Str "chapter,",Space,Str "e.g.",SoftBreak,Span ("eq:eqn2",[],[]) [Math DisplayMath " S(x) = \\int_{x_1}^{x_2} a x+b \\ \\mathrm{d}x \\qquad(3)"]] ,Header 1 ("sec:chapter-5.-reference-lists",[],[]) [Str "Chapter",Space,Str "5.",Space,Str "Reference",Space,Str "lists"] ,Para [Str "It\8217s",Space,Str "also",Space,Str "possible",Space,Str "to",Space,Str "show",Space,Str "lists",Space,Str "of",Space,Str "figures",Space,Str "and",Space,Str "tables,",Space,Str "like",Space,Str "this:"] ,Header 2 ("list-of-figures",[],[]) [Str "List",Space,Str "of",Space,Str "Figures"] - ,OrderedList (1,DefaultStyle,DefaultDelim) - [[Plain [Str "A",Space,Str "figure"]] - ,[Plain [Str "First",Space,Str "figure"]] - ,[Plain [Str "Second",Space,Str "figure"]] - ,[Plain [Str "Third",Space,Str "figure"]] - ,[Plain [Str "Subfigure",Space,Str "a"]] - ,[Plain [Str "Subfigure",Space,Str "b"]] - ,[Plain [Str "Subfigures",Space,Str "caption"]]] + ,Div ("",["list"],[]) + [Para [Str "1.",Space,Str "A",Space,Str "figure"] + ,Para [Str "2.",Space,Str "First",Space,Str "figure"] + ,Para [Str "3.",Space,Str "Second",Space,Str "figure"] + ,Para [Str "4.",Space,Str "Third",Space,Str "figure"] + ,Para [Str "5.",Space,Str "Unlabelled",Space,Str "image"] + ,Para [Str "6.",Space,Str "Subfigures",Space,Str "caption.",Space,Span ("",[],[]) []] + ,Para [Str "a.",Space,Str "Subfigure",Space,Str "a"] + ,Para [Str "b.",Space,Str "Subfigure",Space,Str "b"]] ,Header 2 ("list-of-tables",[],[]) [Str "List",Space,Str "of",Space,Str "Tables"] - ,OrderedList (1,DefaultStyle,DefaultDelim) - [[Plain [Str "Table",Space,Str "example"]]] + ,Div ("",["list"],[]) + [Para [Str "1.",Space,Str "Table",Space,Str "example"]] ,Header 1 ("",[],[]) [Str "List",Space,Str "of",Space,Str "Listings"] - ,OrderedList (1,DefaultStyle,DefaultDelim) - [[Plain [Str "Listing",Space,Str "caption"]] - ,[Plain [Str "Listing",Space,Str "caption"]] - ,[Plain [Str "Listing",Space,Str "caption"]]] + ,Div ("",["list"],[]) + [Para [Str "1.",Space,Str "Listing",Space,Str "caption"] + ,Para [Str "2.",Space,Str "Listing",Space,Str "caption"] + ,Para [Str "3.",Space]] ,Header 1 ("sec:appendix-a.-custom-labels",[],[("label","AppA")]) [Str "Appendix",Space,Str "A.",Space,Str "Custom",Space,Str "labels"] ,Header 2 ("sec:custlabs",[],[("label","CustLab")]) [Str "This",Space,Str "section",Space,Str "will",Space,Str "have",Space,Str "custom",Space,Str "label"]] From 6e309d65a5b6473781c4ec0effc4ea9fda675a7d Mon Sep 17 00:00:00 2001 From: Nikolay Yakimov Date: Wed, 1 May 2019 14:53:10 +0300 Subject: [PATCH 084/134] String and number literals in template variable indexed access --- lib/Text/Pandoc/CrossRef/Util/Template.hs | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/lib/Text/Pandoc/CrossRef/Util/Template.hs b/lib/Text/Pandoc/CrossRef/Util/Template.hs index a19b5080..1a19a3b9 100644 --- a/lib/Text/Pandoc/CrossRef/Util/Template.hs +++ b/lib/Text/Pandoc/CrossRef/Util/Template.hs @@ -38,14 +38,15 @@ import Text.Pandoc.CrossRef.Util.Meta import Text.Pandoc.CrossRef.Util.Template.Types import Control.Applicative hiding (many, optional) import Text.Read hiding ((<++), (+++)) -import Data.Char (isAlphaNum, isUpper, toLower) +import Data.Char (isAlphaNum, isUpper, toLower, isDigit) import Control.Monad ((<=<)) import Data.Data (Data) import Text.ParserCombinators.ReadP data PRVar = PRVar { prvName :: String - , prvIdx :: [[PRVar]] + , prvIdx :: [IdxT] } deriving Show +data IdxT = IdxVar [PRVar] | IdxStr String | IdxNum String deriving Show data ParseRes = ParseRes { prVar :: [PRVar] , prPfx :: String , prSfx :: String @@ -61,7 +62,9 @@ parse = uncurry <$> (ParseRes <$> var) <*> option ("", "") ps <* eof where var = sepBy1 (PRVar <$> varName <*> many varIdx) (char '?') varName = munch1 isVariableSym - varIdx = between (char '[') (char ']') var + varIdx = between (char '[') (char ']') (IdxVar <$> var <|> IdxStr <$> litStr <|> IdxNum <$> litNum) + litStr = between (char '"') (char '"') (many (satisfy (/='"'))) + litNum = many (satisfy isDigit) prefix = char '#' *> many (satisfy (/='%')) suffix = char '%' *> many (satisfy (/='#')) ps = (flip (,) <$> suffix <*> option "" prefix) @@ -102,11 +105,14 @@ scan = bottomUp . go idxVars -> let idxs :: Maybe [String] - idxs = mapM (Just . toString ("index variables " ++ show idxVars) <=< tryVars) idxVars + idxs = mapM (Just . toString ("index variables " ++ show idxVars) <=< tryIdxs) idxVars arr = foldr (\i a -> getObjOrList i =<< a) (vf prvName) . reverse =<< idxs getObjOrList :: String -> MetaValue -> Maybe MetaValue getObjOrList i x = getObj i x <|> (readMaybe i >>= flip getList x) in arr + tryIdxs (IdxVar vars) = tryVars vars + tryIdxs (IdxStr s) = Just $ MetaString s + tryIdxs (IdxNum n) = Just $ MetaString n tryVars = foldr ((<|>) . tryVar) Nothing in toList $ replaceVar (tryVars prVar) <> fromList xs From 422f80708f2bc10bcffec7ce9c67e861f9b02e2b Mon Sep 17 00:00:00 2001 From: Nikolay Yakimov Date: Wed, 1 May 2019 17:24:37 +0300 Subject: [PATCH 085/134] Code clean-up; more clear settings names wrt section label adjustment --- lib/Text/Pandoc/CrossRef.hs | 13 ++- lib/Text/Pandoc/CrossRef/References/Blocks.hs | 87 +++++++++++-------- lib/Text/Pandoc/CrossRef/References/List.hs | 13 +-- lib/Text/Pandoc/CrossRef/References/Refs.hs | 49 ++++++----- .../Pandoc/CrossRef/Util/Options/Types.hs | 8 +- lib/Text/Pandoc/CrossRef/Util/Settings.hs | 3 +- test/test-pandoc-crossref.hs | 7 +- 7 files changed, 95 insertions(+), 85 deletions(-) diff --git a/lib/Text/Pandoc/CrossRef.hs b/lib/Text/Pandoc/CrossRef.hs index 0a86c698..90edbfac 100644 --- a/lib/Text/Pandoc/CrossRef.hs +++ b/lib/Text/Pandoc/CrossRef.hs @@ -98,14 +98,11 @@ import Text.Pandoc.CrossRef.Util.Settings.Gen as SG Works in 'CrossRefM' monad. -} crossRefBlocks :: [Block] -> CrossRef [Block] -crossRefBlocks blocks = do - opts <- R.asks creOptions - let - doWalk = - replaceAll opts blocks - >>= bottomUpM (replaceRefs opts) - >>= bottomUpM (listOf opts) - CrossRef $ flip evalStateT def . unWS $ doWalk +crossRefBlocks blocks = CrossRef $ flip evalStateT def . unWS $ doWalk + where doWalk = + replaceAll blocks + >>= bottomUpM replaceRefs + >>= bottomUpM listOf {- | Modifies metadata for LaTeX output, adding header-includes instructions to setup custom and builtin environments. diff --git a/lib/Text/Pandoc/CrossRef/References/Blocks.hs b/lib/Text/Pandoc/CrossRef/References/Blocks.hs index 1593372f..7bab03a6 100644 --- a/lib/Text/Pandoc/CrossRef/References/Blocks.hs +++ b/lib/Text/Pandoc/CrossRef/References/Blocks.hs @@ -18,7 +18,7 @@ with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -} -{-# LANGUAGE RecordWildCards, NamedFieldPuns, TypeFamilies #-} +{-# LANGUAGE RecordWildCards, NamedFieldPuns, TupleSections #-} module Text.Pandoc.CrossRef.References.Blocks ( replaceAll ) where @@ -47,34 +47,36 @@ import Control.Arrow (second) import Data.Default (def) import Prelude -replaceAll :: Options -> [Block] -> WS [Block] -replaceAll opts = - fmap unhierarchicalize - . runReplace [] (mkRR replaceElement `extRR` replaceBlock opts `extRR` replaceInline opts) - . hierarchicalize - . everywhere (mkT $ makeSubfigures opts) - . everywhere (mkT (divBlocks opts) `extT` spanInlines opts) - . everywhere (mkT $ mkCodeBlockCaptions opts) - -replaceElement :: Scope -> Element -> WS (ReplacedResult Element) -replaceElement scope (Sec n ns (label, cls, attrs) text' body) = do - opts@Options{..} <- asks creOptions - let label' = if isNothing pfx - then maybe label (<> ":" <> label) autoSectionLabels - else label - pfx = getRefPrefix opts label - if "unnumbered" `elem` cls - then replaceRecurse scope $ Sec n ns (label', cls, attrs) text' body - else do - let pfx' = getRefPrefix opts label' - ititle = B.fromList text' - defaultSecPfx = fromMaybe defaultSectionPrefix autoSectionLabels - rec' <- case pfx' of - Just p -> replaceAttr opts scope (Right label') attrs ititle p - Nothing -> replaceAttr opts scope (Left defaultSecPfx) attrs ititle defaultSecPfx - let title' = B.toList $ refCaption rec' - replaceRecurse (newScope rec' scope) $ Sec n ns (label', cls, attrs) title' body -replaceElement scope _ = noReplaceRecurse scope +replaceAll :: [Block] -> WS [Block] +replaceAll bs = + asks creOptions >>= \opts -> + let run = + fmap unhierarchicalize + . runReplace [] (mkRR (replaceElement opts) `extRR` replaceBlock opts `extRR` replaceInline opts) + . hierarchicalize + . everywhere (mkT $ makeSubfigures opts) + . everywhere (mkT (divBlocks opts) `extT` spanInlines opts) + . everywhere (mkT $ mkCodeBlockCaptions opts) + in run bs + +replaceElement :: Options -> Scope -> Element -> WS (ReplacedResult Element) +replaceElement opts scope (Sec n ns (label, cls, attrs) text' body) + | Just (pfx, label') <- + fmap (, ExplicitLabel label) (getRefPrefix opts label) + <|> (autoSectionLabels opts >>= \asl -> return $ + if adjustSectionIdentifiers opts + then let l = asl <> ":" <> label in (asl, ExplicitLabel l) + else (asl, AutoLabel) + ) + = let newlabel = fromMaybe label $ labelToMaybe label' in + if "unnumbered" `elem` cls + then replaceRecurse scope $ Sec n ns (newlabel, cls, attrs) text' body + else do + let ititle = B.fromList text' + rec' <- replaceAttr opts scope label' attrs ititle pfx + let title' = B.toList $ refCaption rec' + replaceRecurse (newScope rec' scope) $ Sec n ns (newlabel, cls, attrs) title' body +replaceElement _ scope _ = noReplaceRecurse scope replaceBlock :: Options -> Scope -> Block -> WS (ReplacedResult Block) -- tables @@ -83,13 +85,13 @@ replaceBlock opts scope (Div divOps@(label,_,attrs) [Table title align widths he , Just pfx <- getRefPrefix opts label = do let ititle = B.fromList title - RefRec{..} <- replaceAttr opts scope (Right label) attrs ititle pfx + RefRec{..} <- replaceAttr opts scope (ExplicitLabel label) attrs ititle pfx replaceNoRecurse $ Div divOps [Table (B.toList refCaption) align widths header cells] -- code blocks replaceBlock opts scope (Div (label, [], divattrs) [CodeBlock ([],classes,cbattrs) code, Para (Str ":":Space:caption)]) | Just pfx <- getRefPrefix opts label = do - ref <- replaceAttr opts scope (Right label) divattrs (B.fromList caption) pfx + ref <- replaceAttr opts scope (ExplicitLabel label) divattrs (B.fromList caption) pfx replaceNoRecurse $ Div (label, "listing":classes, []) $ placeCaption opts ref [CodeBlock ([], classes, cbattrs) code] @@ -102,7 +104,7 @@ replaceBlock opts scope (Div ats@(label, _, attrs) content) , Para (Str ":":Space:c) <- last content = (B.fromList c, init content) | otherwise = (mempty, content) - ref <- replaceAttr opts scope (Right label) attrs caption pfx + ref <- replaceAttr opts scope (ExplicitLabel label) attrs caption pfx replaceRecurse (newScope ref scope) $ Div ats $ placeCaption opts ref content' replaceBlock _ scope _ = noReplaceRecurse scope @@ -114,10 +116,16 @@ placeCaption opts RefRec{..} body | Below <- refCaptionPosition = body <> [mkCaption opts "Caption" refCaption] -autoLabel :: String -> String -> Maybe (Either String String) +data ItemLabel = ExplicitLabel String | AutoLabel + +labelToMaybe :: ItemLabel -> Maybe String +labelToMaybe (ExplicitLabel s) = Just s +labelToMaybe AutoLabel = Nothing + +autoLabel :: String -> String -> Maybe ItemLabel autoLabel pfx label - | null label = Just $ Left pfx - | (pfx <> ":") `isPrefixOf` label = Just $ Right label + | null label = Just AutoLabel + | (pfx <> ":") `isPrefixOf` label = Just $ ExplicitLabel label | otherwise = Nothing replaceInline :: Options -> Scope -> Inline -> WS (ReplacedResult Inline) @@ -138,7 +146,7 @@ replaceInline opts scope (Image attr@(label,_,attrs) alt img@(_, tit)) replaceInline opts scope (Span (label,cls,attrs) content) | Just pfx <- getRefPrefix opts label = do - ref@RefRec{..} <- replaceAttr opts scope (Right label) attrs (B.fromList content) pfx + ref@RefRec{..} <- replaceAttr opts scope (ExplicitLabel label) attrs (B.fromList content) pfx replaceRecurse (newScope ref scope) . Span (label, cls, attrs) . B.toList $ applyTitleTemplate ref replaceInline _opts (scope@RefRec{refPfxRec=Prefix{..}}:_) (Span ("",_,attrs) []) = do @@ -194,7 +202,7 @@ spanInlines opts (math@(Math DisplayMath _eq):ils) = Span nullAttr [math]:ils spanInlines _ x = x -replaceAttr :: Options -> Scope -> Either String String -> [(String, String)] -> B.Inlines -> String -> WS RefRec +replaceAttr :: Options -> Scope -> ItemLabel -> [(String, String)] -> B.Inlines -> String -> WS RefRec replaceAttr o scope label attrs title pfx = do roptMain <- liftEither $ getPfx o pfx @@ -216,7 +224,10 @@ replaceAttr o scope label attrs title pfx }) . fromMaybe def . M.lookup pfx <$> get pfxCounter modify pfxCounter $ M.insert pfx cr let refLabel' = lookup "label" attrs - label' = either (++ ':':'\0':show i) id label + label' = + case label of + ExplicitLabel l -> l + AutoLabel -> pfx <> (':':'\0':show i) iInSc = fromJust $ M.lookup itemScope $ crIndexInScope cr i = crIndex cr customLabel = maybe (prefixNumbering ropt) diff --git a/lib/Text/Pandoc/CrossRef/References/List.hs b/lib/Text/Pandoc/CrossRef/References/List.hs index b14cf993..cedbe6f0 100644 --- a/lib/Text/Pandoc/CrossRef/References/List.hs +++ b/lib/Text/Pandoc/CrossRef/References/List.hs @@ -35,20 +35,21 @@ import Text.Pandoc.CrossRef.Util.Template import Text.Pandoc.CrossRef.Util.Prefixes.Types import Text.Pandoc.CrossRef.Util.VarFunction -listOf :: Options -> [Block] -> WS [Block] -listOf opts (RawBlock fmt cmd:xs) +listOf :: [Block] -> WS [Block] +listOf (RawBlock fmt cmd:xs) | isLaTeXRawBlockFmt fmt , Just pfxBrace <- "\\listof{" `stripPrefix` cmd , (pfx, "}") <- span (/='}') pfxBrace - = getPfxData pfx >>= fmap toList . makeList opts pfx (fromList xs) -listOf _ x = return x + = getPfxData pfx >>= fmap toList . makeList pfx (fromList xs) +listOf x = return x getPfxData :: String -> WS RefMap getPfxData pfx = M.filterWithKey (\k _ -> (pfx <> ":") `isPrefixOf` k) <$> get referenceData -makeList :: Options -> String -> Blocks -> M.Map String RefRec -> WS Blocks -makeList opts titlef xs refs +makeList :: String -> Blocks -> M.Map String RefRec -> WS Blocks +makeList titlef xs refs = do + opts <- asks creOptions title <- liftEither $ getTitleForListOf opts titlef return $ title <> divWith ("", ["list"], []) (mconcat $ map itemChap refsSorted) diff --git a/lib/Text/Pandoc/CrossRef/References/Refs.hs b/lib/Text/Pandoc/CrossRef/References/Refs.hs index 82927d62..22325cd8 100644 --- a/lib/Text/Pandoc/CrossRef/References/Refs.hs +++ b/lib/Text/Pandoc/CrossRef/References/Refs.hs @@ -53,34 +53,35 @@ groupEither (Right x:xs) = Right (x:rights ys) : groupEither zs where (ys,zs) = span isRight xs -replaceRefs :: Options -> [Inline] -> WS [Inline] -replaceRefs opts ils +replaceRefs :: [Inline] -> WS [Inline] +replaceRefs ils | Cite cits _:xs <- ils = do + opts <- asks creOptions + let + eqPred :: RefDataComplete -> RefDataComplete -> Bool + eqPred = (==) `on` liftM2 (,) rdLevel rdPrefix + intrclt = intercalate' (text ", ") + replaceRefs' (Left xs') = restoreCits' xs' + replaceRefs' (Right xs') = intrclt <$> mapM (replaceRefsOther opts) (NE.groupBy eqPred xs') + restoreCits' refs = liftM2 cite cits' il' + where + cits' = mapM getCit refs + getCit RefDataIncomplete{rdCitation, rdiLabel} + | takeWhile (/=':') rdiLabel `elem` M.keys (prefixes opts) + = tell ["Undefined cross-reference: " <> rdiLabel] >> return rdCitation + | otherwise = return rdCitation + il' = do + i <- map citationToInlines <$> cits' + return $ str "[" + <> intercalate' (text "; ") i + <> str "]" + citationToInlines c = + fromList (citationPrefix c) <> text ("@" ++ citationId c) + <> fromList (citationSuffix c) citRefData <- groupEither <$> mapM getRefData cits toList . (<> fromList xs) . intrclt <$> mapM replaceRefs' citRefData - where - eqPred :: RefDataComplete -> RefDataComplete -> Bool - eqPred = (==) `on` liftM2 (,) rdLevel rdPrefix - intrclt = intercalate' (text ", ") - replaceRefs' (Left xs) = restoreCits' xs - replaceRefs' (Right xs) = intrclt <$> mapM (replaceRefsOther opts) (NE.groupBy eqPred xs) - restoreCits' refs = liftM2 cite cits' il' - where - cits' = mapM getCit refs - getCit RefDataIncomplete{rdCitation, rdiLabel} - | takeWhile (/=':') rdiLabel `elem` M.keys (prefixes opts) - = tell ["Undefined cross-reference: " <> rdiLabel] >> return rdCitation - | otherwise = return rdCitation - il' = do - i <- map citationToInlines <$> cits' - return $ str "[" - <> intercalate' (text "; ") i - <> str "]" - citationToInlines c = - fromList (citationPrefix c) <> text ("@" ++ citationId c) - <> fromList (citationSuffix c) -replaceRefs _ x = return x +replaceRefs x = return x getRefPrefix :: Bool -> Int -> RefRec -> Inlines -> Inlines getRefPrefix capitalize num rr@RefRec{..} cit = diff --git a/lib/Text/Pandoc/CrossRef/Util/Options/Types.hs b/lib/Text/Pandoc/CrossRef/Util/Options/Types.hs index 7fca1b74..19421484 100644 --- a/lib/Text/Pandoc/CrossRef/Util/Options/Types.hs +++ b/lib/Text/Pandoc/CrossRef/Util/Options/Types.hs @@ -24,15 +24,15 @@ import Text.Pandoc.CrossRef.Util.Prefixes import Text.Pandoc.Builder data Options = Options { codeBlockCaptions :: Bool - , autoSectionLabels :: Maybe String - , defaultSectionPrefix :: String + , autoSectionLabels :: Maybe String + , autoEqnLabels :: Maybe String + , autoFigLabels :: Maybe String + , adjustSectionIdentifiers :: Bool , rangeDelim :: Inlines , pairDelim :: Inlines , lastDelim :: Inlines , refDelim :: Inlines , outFormat :: Maybe Format - , autoEqnLabels :: Maybe String - , autoFigLabels :: Maybe String , linkReferences :: Bool , nameInLink :: Bool , prefixes :: Prefixes diff --git a/lib/Text/Pandoc/CrossRef/Util/Settings.hs b/lib/Text/Pandoc/CrossRef/Util/Settings.hs index 40eca53b..71c9f595 100644 --- a/lib/Text/Pandoc/CrossRef/Util/Settings.hs +++ b/lib/Text/Pandoc/CrossRef/Util/Settings.hs @@ -60,7 +60,8 @@ readSettings fmt inMeta = do defaultMeta :: Settings defaultMeta = Settings $ codeBlockCaptions False - <> defaultSectionPrefix "sec" + <> adjustSectionIdentifiers False + <> autoSectionLabels "sec" <> titleDelim (str ":" <> space) <> listItemNumberDelim (str "." <> space) <> rangeDelim (str "-") diff --git a/test/test-pandoc-crossref.hs b/test/test-pandoc-crossref.hs index c3a40135..4bf84758 100644 --- a/test/test-pandoc-crossref.hs +++ b/test/test-pandoc-crossref.hs @@ -375,14 +375,13 @@ refRec' ref i tit cap = ) testRefs :: Blocks -> References -> Blocks -> Expectation -testRefs bs st rbs = testState (bottomUpM (References.Refs.replaceRefs defaultOptions)) st bs (rbs, id) +testRefs bs st rbs = testState (bottomUpM References.Refs.replaceRefs) st bs (rbs, id) testRefs' :: String -> [Int] -> [Int] -> Accessor References (M.Map String RefRec) -> String -> Expectation testRefs' p l1 l2 prop res = testRefs (para $ citeGen p l1) (setVal prop (refGen p l1 l2) def) (para $ text res) testAll :: Many Block -> (Many Block, References -> References) -> Expectation -testAll = testState f def - where f = References.Blocks.replaceAll defaultOptions +testAll = testState References.Blocks.replaceAll def evalCrossRefM :: CrossRefM c -> c evalCrossRefM = evalCrossRefRes . runCrossRef (unSettings defaultMeta) Nothing . CrossRef @@ -412,7 +411,7 @@ testCBCaptions :: Blocks -> Blocks -> Expectation testCBCaptions bs res = bottomUp (Util.CodeBlockCaptions.mkCodeBlockCaptions defaultOptions{Text.Pandoc.CrossRef.Util.Options.codeBlockCaptions=True}) (toList bs) `shouldBe` toList res testList :: Blocks -> (References -> References) -> Blocks -> Expectation -testList bs st res = testState (bottomUpM (References.List.listOf defaultOptions)) (st def) bs (res, st) +testList bs st res = testState (bottomUpM References.List.listOf) (st def) bs (res, st) figure :: String -> String -> String -> String -> Blocks figure = (((para .) .) .) . figure' "fig:" From 5e2f815eaa9b91b1db2249997dd263b84f9cba2d Mon Sep 17 00:00:00 2001 From: Nikolay Yakimov Date: Wed, 1 May 2019 19:33:35 +0300 Subject: [PATCH 086/134] Add crossrefOutputFormat variable --- lib/Text/Pandoc/CrossRef/Util/Prefixes.hs | 11 ++++++++--- lib/Text/Pandoc/CrossRef/Util/Settings/Template.hs | 7 ++++--- test/test-pandoc-crossref.hs | 2 +- 3 files changed, 13 insertions(+), 7 deletions(-) diff --git a/lib/Text/Pandoc/CrossRef/Util/Prefixes.hs b/lib/Text/Pandoc/CrossRef/Util/Prefixes.hs index 07c175a5..d877649b 100644 --- a/lib/Text/Pandoc/CrossRef/Util/Prefixes.hs +++ b/lib/Text/Pandoc/CrossRef/Util/Prefixes.hs @@ -32,8 +32,8 @@ import Text.Pandoc.CrossRef.Util.CustomLabels import qualified Data.Map as M import Data.Maybe -getPrefixes :: String -> Settings -> Prefixes -getPrefixes varN dtv +getPrefixes :: Maybe Format -> String -> Settings -> Prefixes +getPrefixes fmt varN dtv | Just (MetaMap m) <- lookupSettings varN dtv = let m2p k (MetaMap kv') = Prefix { @@ -60,7 +60,12 @@ getPrefixes varN dtv , prefixSub = m2p k . (`merge` MetaMap kv') <$> lookupSettings "sub" (Settings (Meta kv') <> from) , prefixDef = (`lookupSettings` kv) } - where kv = Settings (Meta kv') <> from <> dtv + where kv = Settings (Meta kv') + <> from + <> dtv + <> Settings (Meta fmtm) + fmtm | Just (Format fmt') <- fmt = M.singleton "crossrefOutputFormat" $ MetaString fmt' + | otherwise = M.empty from | Just fromRef <- M.lookup "from" kv' , Just (MetaMap kv'') <- M.lookup (toString "from" fromRef) m = Settings (Meta kv'') diff --git a/lib/Text/Pandoc/CrossRef/Util/Settings/Template.hs b/lib/Text/Pandoc/CrossRef/Util/Settings/Template.hs index d65a135e..8138c9cb 100644 --- a/lib/Text/Pandoc/CrossRef/Util/Settings/Template.hs +++ b/lib/Text/Pandoc/CrossRef/Util/Settings/Template.hs @@ -78,15 +78,16 @@ makeCon' t accName = do strT <- [t|$(conT t) -> String|] mstT <- [t|$(conT t) -> Maybe String|] let varName | Name (OccName n) _ <- accName = liftString n - let dtv = return $ VarE $ mkName "dtv" + dtv = return $ VarE $ mkName "dtv" + fmt = return $ VarE $ mkName "fmt" body <- if | t' == boolT -> [|getMetaBool $(varName) $(dtv)|] | t' == intT -> [|read $ getMetaString $(varName) $(dtv)|] | t' == inlT -> [|getMetaInlines $(varName) $(dtv)|] | t' == blkT -> [|getMetaBlock $(varName) $(dtv)|] - | t' == fmtT -> return $ VarE $ mkName "fmt" - | t' == pfxT -> [|getPrefixes $(varName) $(dtv)|] + | t' == fmtT -> fmt + | t' == pfxT -> [|getPrefixes $(fmt) $(varName) $(dtv)|] | t' == strT -> [|getMetaString $(varName) $(dtv)|] | t' == mstT -> [|getMetaStringMaybe $(varName) $(dtv)|] | otherwise -> fail $ show t' diff --git a/test/test-pandoc-crossref.hs b/test/test-pandoc-crossref.hs index 4bf84758..2b9458e8 100644 --- a/test/test-pandoc-crossref.hs +++ b/test/test-pandoc-crossref.hs @@ -478,4 +478,4 @@ infixr 0 =: a =: b = a ^= b defaultPrefixes :: Prefixes -defaultPrefixes = getPrefixes "prefixes" defaultMeta +defaultPrefixes = getPrefixes Nothing "prefixes" defaultMeta From bc57538d1763d577417ed365d488f471e3b05bed Mon Sep 17 00:00:00 2001 From: Nikolay Yakimov Date: Wed, 1 May 2019 21:24:50 +0300 Subject: [PATCH 087/134] Added a way to suppress default settings; more flexible default settings; setting name disambiguation via optional scoping under `crossref` object (concept) --- lib/Text/Pandoc/CrossRef.hs | 23 +++--- lib/Text/Pandoc/CrossRef/Util/ModifyMeta.hs | 15 ++-- lib/Text/Pandoc/CrossRef/Util/Settings.hs | 77 +++++++++++++++++++-- test/test-integrative.hs | 2 +- test/test-pandoc-crossref.hs | 7 +- 5 files changed, 97 insertions(+), 27 deletions(-) diff --git a/lib/Text/Pandoc/CrossRef.hs b/lib/Text/Pandoc/CrossRef.hs index 90edbfac..4837dc88 100644 --- a/lib/Text/Pandoc/CrossRef.hs +++ b/lib/Text/Pandoc/CrossRef.hs @@ -79,6 +79,7 @@ module Text.Pandoc.CrossRef ( , CrossRef , CrossRefEnv(..) , WSException(..) + , Settings(..) ) where import Control.Monad.State @@ -105,30 +106,32 @@ crossRefBlocks blocks = CrossRef $ flip evalStateT def . unWS $ doWalk >>= bottomUpM listOf {- | Modifies metadata for LaTeX output, adding header-includes instructions -to setup custom and builtin environments. +to setup custom and builtin environments, and adds current pandoc-crossref +settings to metadata. -Note, that if output format is not "latex", this function does nothing. +Note, that if output format is not "latex", this function not modify +header-includes. Works in 'CrossRefM' monad. -} -crossRefMeta :: CrossRef Meta +crossRefMeta :: Meta -> CrossRef Meta crossRefMeta = modifyMeta {- | Combines 'crossRefMeta' and 'crossRefBlocks' Works in 'CrossRefM' monad. -} defaultCrossRefAction :: Pandoc -> CrossRef Pandoc -defaultCrossRefAction (Pandoc _ bs) = do - meta' <- crossRefMeta +defaultCrossRefAction (Pandoc meta bs) = do + meta' <- crossRefMeta meta bs' <- crossRefBlocks bs return $ Pandoc meta' bs' {- | Run an action in 'CrossRefM' monad with argument, and return pure result. This is primary function to work with 'CrossRefM' -} -runCrossRef :: forall b. Meta -> Maybe Format -> CrossRef b -> (Either WSException b, [String]) -runCrossRef meta fmt = flip runReader env . runWriterT . runExceptT . unCrossRef +runCrossRef :: forall b. Settings -> Maybe Format -> CrossRef b -> (Either WSException b, [String]) +runCrossRef metaset fmt = flip runReader env . runWriterT . runExceptT . unCrossRef where - settings = Settings meta <> defaultMeta + settings = metaset <> defaultMeta metaset env = CrossRefEnv { creSettings = settings , creOptions = getOptions settings fmt @@ -140,7 +143,7 @@ This function will attempt to read pandoc-crossref settings from settings file specified by crossrefYaml metadata field. -} runCrossRefIO :: forall b. Meta -> Maybe Format -> CrossRef b -> IO b runCrossRefIO meta fmt action = do - Settings meta' <- readSettings fmt meta - let (res, lg) = runCrossRef meta' fmt action + metaset <- readSettings fmt meta + let (res, lg) = runCrossRef metaset fmt action mapM_ (hPutStrLn stderr) lg return $ either (error . pretty) id res diff --git a/lib/Text/Pandoc/CrossRef/Util/ModifyMeta.hs b/lib/Text/Pandoc/CrossRef/Util/ModifyMeta.hs index 49968d2f..5c4fc153 100644 --- a/lib/Text/Pandoc/CrossRef/Util/ModifyMeta.hs +++ b/lib/Text/Pandoc/CrossRef/Util/ModifyMeta.hs @@ -32,10 +32,10 @@ import Text.Pandoc.CrossRef.References.Types import Text.Pandoc.CrossRef.Util.Settings.Types import Text.Pandoc.CrossRef.Util.Util -modifyMeta :: CrossRef Meta -modifyMeta = do +modifyMeta :: Meta -> CrossRef Meta +modifyMeta meta = do Options{..} <- asks creOptions - settings <- asks creSettings + Settings (Meta settingskv) <- asks creSettings let headerInc :: Maybe MetaValue -> MetaValue headerInc Nothing = incList @@ -46,8 +46,11 @@ modifyMeta = do tell [ "\\@ifpackageloaded{caption}{\\captionsetup{labelformat=empty}}{\\usepackage[labelformat=empty]{caption}}" ] tell [ "\\newenvironment{pandoccrossrefsubcaption}{\\renewcommand{\\toprule}{}\\renewcommand{\\bottomrule}{}}{}" ] tell [ "\\makeatother" ] + tweakedMeta + | Just _ <- lookupMeta "crossref" meta = setMeta "crossref" (MetaMap settingskv) meta + | otherwise = Meta settingskv return $ if isLatexFormat outFormat then setMeta "header-includes" - (headerInc $ lookupSettings "header-includes" settings) - $ unSettings settings - else unSettings settings + (headerInc $ lookupMeta "header-includes" meta) + tweakedMeta + else tweakedMeta diff --git a/lib/Text/Pandoc/CrossRef/Util/Settings.hs b/lib/Text/Pandoc/CrossRef/Util/Settings.hs index 71c9f595..78e7b50b 100644 --- a/lib/Text/Pandoc/CrossRef/Util/Settings.hs +++ b/lib/Text/Pandoc/CrossRef/Util/Settings.hs @@ -36,8 +36,12 @@ import qualified Data.Map as M readSettings :: Maybe Format -> Meta -> IO Settings readSettings fmt inMeta = do - let meta = Settings inMeta - dirConfig <- readConfig (getMetaString "crossrefYaml" (meta <> defaultMeta)) + let meta = + case inMeta of + Meta m | Just (MetaMap cm) <- M.lookup "crossref" m + -> Settings (Meta cm) + _ -> Settings inMeta + dirConfig <- readConfig (getMetaString "crossrefYaml" (meta <> defaultMeta meta)) home <- getHomeDirectory globalConfig <- readConfig (home ".pandoc-crossref" "config.yaml") formatConfig <- maybe (return mempty) (readFmtConfig home) fmt @@ -57,8 +61,60 @@ readSettings fmt inMeta = do fmtStr (Format fmtstr) = fmtstr -defaultMeta :: Settings -defaultMeta = Settings $ +defaultMeta :: Settings -> Settings +defaultMeta userSettings + | null option = basicMeta + | option == ["none"] = mempty + | otherwise = mconcat . reverse $ basicMeta : map name2set option + where + option = getMetaStringList "defaultOption" userSettings + name2set "chapters" = chaptersMeta + name2set "subfigures" = subfiguresMeta + name2set "numberSections" = numberSectionsMeta + name2set x = error $ "Unknown defaultOption value: " <> x + +chaptersMeta :: Settings +chaptersMeta = Settings $ + captionIndexTemplate (var "s.i%." <> var "ri") + <> customMeta [ "scope" .= "sec" ] + <> prefixes' [ + "sec" .: [ + "title" .= "Chapter", + "sub" .: [ + "title" .= "Section", + "referenceIndexTemplate" .= var "i" <> var "suf" + ] + ] + ] + +numberSectionsMeta :: Settings +numberSectionsMeta = Settings $ + prefixes' [ + "sec" .: [ + "captionTemplate" .= var "title" <> space <> var "i" + <> str "." <> space <> var "t" + ] + ] + +subfiguresMeta :: Settings +subfiguresMeta = Settings $ + prefixes' [ + "fig" .: [ + "subcaptions" .= True, + "sub" .: [ + "numbering" .= "alpha a", + "referenceIndexTemplate" .= si, + "listItemTemplate" .= (si <> var "listItemNumberDelim" <> var "t"), + "captionTemplate" .= var "i", + "scope" .= ["fig"], + "captionIndexTemplate" .= var "ri" + ] + ] + ] + where si = var "s.i" <> str "(" <> var "i" <> str ")" + +basicMeta :: Settings +basicMeta = Settings $ codeBlockCaptions False <> adjustSectionIdentifiers False <> autoSectionLabels "sec" @@ -104,14 +160,23 @@ defaultMeta = Settings $ "sec" .: [ "ref" .= map str ["sec.", "secs."], "title" .= text "Section", - "captionTemplate" .= var "t" + "captionTemplate" .= var "t", + "scope" .= ["sec"], + "sub" .: [ + "referenceIndexTemplate" .= var "s.i%." <> var "i" <> var "suf" + ] ] ] - where var = displayMath + +var :: String -> Inlines +var = displayMath prefixes' :: [(String, MetaValue)] -> Meta prefixes' = prefixes . MetaMap . M.fromList +customMeta :: [(String, MetaValue)] -> Meta +customMeta = Meta . M.fromList + infixr 0 .: (.:) :: String -> [(String, MetaValue)] -> (String, MetaValue) key .: val = (key, MetaMap $ M.fromList val) diff --git a/test/test-integrative.hs b/test/test-integrative.hs index 6a0c7c97..d45ba688 100644 --- a/test/test-integrative.hs +++ b/test/test-integrative.hs @@ -40,7 +40,7 @@ m2m dir let ro = def { readerExtensions = pandocExtensions } wo = def { writerExtensions = pandocExtensions, writerHighlightStyle=Just pygments } p@(Pandoc meta _) <- runIO $ either (error . show) id <$> P.runIO (readMarkdown ro $ T.pack input) - let actual_md = either (fail . show) T.unpack $ runPure $ writeMarkdown wo . evalCrossRefRes . runCrossRef meta (Just $ Format "markdown") $ defaultCrossRefAction p + let actual_md = either (fail . show) T.unpack $ runPure $ writeMarkdown wo . evalCrossRefRes . runCrossRef (Settings meta) (Just $ Format "markdown") $ defaultCrossRefAction p it "Markdown" $ do zipWithM_ shouldBe (lines' actual_md) (lines' expect_md) length' (lines' actual_md) `shouldBe` length' (lines' expect_md) diff --git a/test/test-pandoc-crossref.hs b/test/test-pandoc-crossref.hs index 2b9458e8..97b7ff96 100644 --- a/test/test-pandoc-crossref.hs +++ b/test/test-pandoc-crossref.hs @@ -37,7 +37,6 @@ import Text.Pandoc.CrossRef.Util.Prefixes import Text.Pandoc.CrossRef.Util.Util import Text.Pandoc.CrossRef.References.Types import Text.Pandoc.CrossRef.Util.Template.Types -import Text.Pandoc.CrossRef.Util.Settings.Types import Data.Accessor hiding ((=:)) import qualified Text.Pandoc.CrossRef.References.Blocks as References.Blocks import qualified Text.Pandoc.CrossRef.References.Refs as References.Refs @@ -335,14 +334,14 @@ main = hspec $ do it "demo.md matches demo.native" $ do demomd <- readFile =<< getDataFileName "docs/demo/demo.md" Pandoc m b <- handleError $ runPure $ readMarkdown def {readerExtensions = pandocExtensions} $ T.pack demomd - let (res, _warn) = runCrossRef m Nothing $ crossRefBlocks b + let (res, _warn) = runCrossRef (Settings m) Nothing $ crossRefBlocks b res `shouldBe` Right Native.demo it "demo.md with chapters matches demo-chapters.native" $ do demomd <- readFile =<< getDataFileName "docs/demo/demo.md" Pandoc m b <- handleError $ runPure $ readMarkdown def {readerExtensions = pandocExtensions} $ T.pack demomd let m' = setMeta "chapters" True m - let (res, _warn) = runCrossRef m' Nothing $ crossRefBlocks b + let (res, _warn) = runCrossRef (Settings m') Nothing $ crossRefBlocks b res `shouldBe` Right Native.demochapters #endif @@ -384,7 +383,7 @@ testAll :: Many Block -> (Many Block, References -> References) -> Expectation testAll = testState References.Blocks.replaceAll def evalCrossRefM :: CrossRefM c -> c -evalCrossRefM = evalCrossRefRes . runCrossRef (unSettings defaultMeta) Nothing . CrossRef +evalCrossRefM = evalCrossRefRes . runCrossRef defaultMeta Nothing . CrossRef evalCrossRefRes :: (Either WSException c, b) -> c evalCrossRefRes = either (error . show) id . fst From 5669c99d112fe42d715d15b4a0b3afd2f5737a2b Mon Sep 17 00:00:00 2001 From: Nikolay Yakimov Date: Wed, 1 May 2019 21:25:25 +0300 Subject: [PATCH 088/134] Clean-up demo.md --- docs/demo/demo.md | 46 ++++++++++++++-------------------------------- 1 file changed, 14 insertions(+), 32 deletions(-) diff --git a/docs/demo/demo.md b/docs/demo/demo.md index e560d388..3b49a70a 100644 --- a/docs/demo/demo.md +++ b/docs/demo/demo.md @@ -1,29 +1,11 @@ --- codeBlockCaptions: True +adjustSectionIdentifiers: True autoFigLabels: fig -prefixes: - fig: - title: | - Figure # - listOfTitle: | - ## List of Figures - subcaptions: true - sub: - numbering: alpha a - referenceIndexTemplate: $$s.i$$ ($$i$$) - captionTemplate: $$i$$ - scope: "fig" - tbl: - listOfTitle: | - ## List of Tables - captionTemplate: | - *$$title$$ $$i$$*$$titleDelim$$ $$t$$ - sec: - scope: sec - sub: - referenceIndexTemplate: $$s.i%.$$$$i$$ - captionTemplate: $$i$$. $$t$$ -autoSectionLabels: sec +defaultOption: + - numberSections + - chapters + - subfigures title: pandoc-crossref demo document --- @@ -45,7 +27,7 @@ You can also have custom chapter reference labels, like @sec:custlabs Subfigures are supported, see [@fig:subfigures; @fig:subfigureB] -# Chapter 1. Figures {#sec:sec1} +# Figures {#sec:sec1} ![First figure](img1.jpg){#fig:figure1} @@ -63,7 +45,7 @@ Subfigures are supported, see [@fig:subfigures; @fig:subfigureB] \: Subfigures caption. []{} -# Chapter 2. Equations {#sec:sec2} +# Equations {#sec:sec2} Display equations are labelled and numbered @@ -72,7 +54,7 @@ $$ P_i(x) = \sum_i a_i x^i $$ {#eq:eqn1} Since 0.1.6.0 those can also appear in the middle of paragraph $$a x^2 + b x^2 + c = 0$${#eq:quadr} like this. -# Chapter 3. Tables +# Tables | First Header | Second Header | |:-------------|:--------------| @@ -88,7 +70,7 @@ Table without caption: | Content Cell | Content Cell | | Content Cell | Content Cell | -# Chapter 4. Code blocks +# Code blocks There are a couple options for code block labels. Those work only if code block id starts with `lst:`, e.g. `{#lst:label}` @@ -118,14 +100,14 @@ main = putStrLn "Hello World!" ## Wrapping div -Wrapping code block without label in a div with id `lst:...` and class, starting with `listing`, and adding paragraph before code block, but inside div, will treat said paragraph as code block caption. +Wrapping code block without label in a div with id `lst:...` and class, starting with `listing`, and adding paragraph after code block, but inside div, starting with `:` will treat said paragraph as code block caption.
-Listing caption ```{.haskell} main :: IO () main = putStrLn "Hello World!" ``` +: Listing caption
# Unnumbered chapter. {-} @@ -133,7 +115,7 @@ main = putStrLn "Hello World!" This chapter doesn't change chapter prefix of referenced elements, instead keeping number of previous chapter, e.g. $$ S(x) = \int_{x_1}^{x_2} a x+b \ \mathrm{d}x $$ {#eq:eqn2} -# Chapter 5. Reference lists +# Reference lists It's also possible to show lists of figures and tables, like this: @@ -143,6 +125,6 @@ It's also possible to show lists of figures and tables, like this: \listof{lst} -# Appendix A. Custom labels {label=AppA} +# Custom labels {label=A title=Appendix} -## This section will have custom label {#sec:custlabs label=CustLab} +## This section will have custom label {#sec:custlabs label=I} From a9e5954f1a7884d6dc3eb2ad5a9665f0977198de Mon Sep 17 00:00:00 2001 From: Nikolay Yakimov Date: Wed, 1 May 2019 21:27:13 +0300 Subject: [PATCH 089/134] Remove demo-chapters test as currently obsolete --- test/demo-chapters.inc | 86 ------------------------------------ test/demo.inc | 85 ++++++++++++++++++----------------- test/test-pandoc-crossref.hs | 7 --- 3 files changed, 42 insertions(+), 136 deletions(-) delete mode 100644 test/demo-chapters.inc diff --git a/test/demo-chapters.inc b/test/demo-chapters.inc deleted file mode 100644 index 74f5bcf3..00000000 --- a/test/demo-chapters.inc +++ /dev/null @@ -1,86 +0,0 @@ - [Para [Str "This",Space,Str "is",Space,Str "a",Space,Str "demo",Space,Str "file",Space,Str "for",Space,Str "pandoc-crossref.",Space,Str "With",Space,Str "this",Space,Str "filter,",Space,Str "you",Space,Str "can",Space,Str "cross-reference",Space,Str "figures",Space,Str "(see",Space,Str "figs.\160\&2-4),",Space,Str "display",Space,Str "equations",Space,Str "(see",Space,Str "eq.\160\&1),",Space,Str "tables",Space,Str "(see",Space,Str "tbl.\160\&1)",Space,Str "and",Space,Str "sections",Space,Str "(",Str "secs.\160\&1,",Space,Str "2,",Space,Str "secs.\160.41-.43)"] - ,Para [Str "For",Space,Str "immediate",Space,Str "example,",Space,Str "see",Space,Str "fig.\160\&1"] - ,Para [Image ("fig:figure0",[],[]) [Str "Figure",Space,Str "#\160\&1:",Space,Str "A",Space,Str "figure"] ("img1.jpg","fig:")] - ,Para [Str "There",Space,Str "is",Space,Str "also",Space,Str "support",Space,Str "for",Space,Str "code",Space,Str "blocks,",Space,Str "for",Space,Str "example,",Space,Str "lsts.\160\&1-3"] - ,Para [Str "It\8217s",Space,Str "possible",Space,Str "to",Space,Str "capitalize",Space,Str "reference",Space,Str "prefixes,",Space,Str "like",Space,Str "this:",Space,Str "Fig.\160\&2."] - ,Para [Str "In",Space,Str "case",Space,Str "of",Space,Str "multiple",Space,Str "references,",Space,Str "capitalization",Space,Str "is",Space,Str "determined",Space,Str "by",Space,Str "first",Space,Str "reference.",Space,Str "Figs.\160\&2,",Space,Str "3",Space,Str "is",Space,Str "capitalized,",Space,Str "while",Space,Str "figs.\160\&2,",Space,Str "3",Space,Str "is",Space,Str "not."] - ,Para [Str "It",Space,Str "is",Space,Str "also",Space,Str "possible",Space,Str "to",Space,Str "mix",Space,Str "different",Space,Str "references,",Space,Str "like",Space,Str "fig.\160\&2,",Space,Str "tbl.\160\&1,",Space,Str "lsts.\160\&1,",Space,Str "2,",Space,Str "figs.\160\&3,",Space,Str "4,",Space,Str "which",Space,Str "will",Space,Str "be",Space,Str "grouped",Space,Str "in",Space,Str "order",Space,Str "they",Space,Str "are",Space,Str "specified.",Space,Str "You",Space,Str "can",Space,Str "even",Space,Str "intermix",Space,Str "this",Space,Str "with",Space,Str "regular",Space,Str "citations,",Space,Str "although",Space,Str "it\8217s",Space,Str "not",Space,Str "recommended:",Space,Str "fig.\160\&2,",Space,Str "tbl.\160\&1,",Space,Cite [Citation {citationId = "unprocessedCitation", citationPrefix = [], citationSuffix = [], citationMode = NormalCitation, citationNoteNum = 0, citationHash = 0}] [Str "[@unprocessedCitation]"]] - ,Para [Str "You",Space,Str "can",Space,Str "also",Space,Str "have",Space,Str "custom",Space,Str "chapter",Space,Str "reference",Space,Str "labels,",Space,Str "like",Space,Str "sec.\160.AppACustLab"] - ,Para [Str "Subfigures",Space,Str "are",Space,Str "supported,",Space,Str "see",Space,Str "fig.\160\&6,",Space,Str "fig.\160\&6",Space,Str "(b)"] - ,Header 1 ("sec:sec1",[],[]) [Str "Chapter",Space,Str "1.",Space,Str "Figures"] - ,Para [Image ("fig:figure1",[],[]) [Str "Figure",Space,Str "#\160\&2:",Space,Str "First",Space,Str "figure"] ("img1.jpg","fig:")] - ,Para [Image ("fig:figure2",[],[]) [Str "Figure",Space,Str "#\160\&3:",Space,Str "Second",Space,Str "figure"] ("img2.jpg","fig:")] - ,Para [Image ("fig:figure3",[],[]) [Str "Figure",Space,Str "#\160\&4:",Space,Str "Third",Space,Str "figure"] ("img3.jpg","fig:")] - ,Para [Image ("",[],[]) [Str "Figure",Space,Str "#\160\&5:",Space,Str "Unlabelled",Space,Str "image"] ("img1.jpg","fig:")] - ,Div ("fig:subfigures",["subcaption"],[]) - [Table [] [AlignCenter] [0.99] - [] - [[[Div ("",[],[]) - [Para [Image ("",[],[("width","100%")]) [Str "a"] ("img1.jpg","fig:")]]]] - ,[[Div ("",[],[]) - [Para [Image ("fig:subfigureB",[],[("width","100%")]) [Str "b"] ("img1.jpg","fig:")]]]]] - ,Para [Str "Figure",Space,Str "#\160\&6:",Space,Str "Subfigures",Space,Str "caption.",Space,Span ("",[],[]) [Str "a",Space,Str "\8211",Space,Str "Subfigure",Space,Str "a,",Space,Str "b",Space,Str "\8211",Space,Str "Subfigure",Space,Str "b"]]] - ,Header 1 ("sec:sec2",[],[]) [Str "Chapter",Space,Str "2.",Space,Str "Equations"] - ,Para [Str "Display",Space,Str "equations",Space,Str "are",Space,Str "labelled",Space,Str "and",Space,Str "numbered"] - ,Para [Span ("eq:eqn1",[],[]) [Math DisplayMath " P_i(x) = \\sum_i a_i x^i \\qquad(1)"]] - ,Para [Str "Since",Space,Str "0.1.6.0",Space,Str "those",Space,Str "can",Space,Str "also",Space,Str "appear",Space,Str "in",Space,Str "the",Space,Str "middle",Space,Str "of",Space,Str "paragraph",SoftBreak,Span ("eq:quadr",[],[]) [Math DisplayMath "a x^2 + b x^2 + c = 0\\qquad(2)"],Space,Str "like",Space,Str "this."] - ,Header 1 ("sec:chapter-3.-tables",[],[]) [Str "Chapter",Space,Str "3.",Space,Str "Tables"] - ,Div ("tbl:table1",[],[]) - [Table [Emph [Str "Table",Space,Str "1"],Str ":",Space,Str "Table",Space,Str "example"] [AlignLeft,AlignLeft] [0.0,0.0] - [[Plain [Str "First",Space,Str "Header"]] - ,[Plain [Str "Second",Space,Str "Header"]]] - [[[Plain [Str "Content",Space,Str "Cell"]] - ,[Plain [Str "Content",Space,Str "Cell"]]] - ,[[Plain [Str "Content",Space,Str "Cell"]] - ,[Plain [Str "Content",Space,Str "Cell"]]]]] - ,Para [Str "Table",Space,Str "without",Space,Str "caption:"] - ,Table [] [AlignLeft,AlignLeft] [0.0,0.0] - [[Plain [Str "First",Space,Str "Header"]] - ,[Plain [Str "Second",Space,Str "Header"]]] - [[[Plain [Str "Content",Space,Str "Cell"]] - ,[Plain [Str "Content",Space,Str "Cell"]]] - ,[[Plain [Str "Content",Space,Str "Cell"]] - ,[Plain [Str "Content",Space,Str "Cell"]]]] - ,Header 1 ("sec:chapter-4.-code-blocks",[],[]) [Str "Chapter",Space,Str "4.",Space,Str "Code",Space,Str "blocks"] - ,Para [Str "There",Space,Str "are",Space,Str "a",Space,Str "couple",Space,Str "options",Space,Str "for",Space,Str "code",Space,Str "block",Space,Str "labels.",Space,Str "Those",Space,Str "work",Space,Str "only",Space,Str "if",Space,Str "code",Space,Str "block",Space,Str "id",Space,Str "starts",Space,Str "with",Space,Code ("",[],[]) "lst:",Str ",",Space,Str "e.g.\160",Code ("",[],[]) "{#lst:label}"] - ,Header 2 ("sec:caption-attr",[],[]) [Code ("",[],[]) "caption",Space,Str "attribute"] - ,Para [Code ("",[],[]) "caption",Space,Str "attribute",Space,Str "will",Space,Str "be",Space,Str "treated",Space,Str "as",Space,Str "code",Space,Str "block",Space,Str "caption.",Space,Str "If",Space,Str "code",Space,Str "block",Space,Str "has",Space,Str "both",Space,Str "id",Space,Str "and",Space,Code ("",[],[]) "caption",Space,Str "attributes,",Space,Str "it",Space,Str "will",Space,Str "be",Space,Str "treated",Space,Str "as",Space,Str "numbered",Space,Str "code",Space,Str "block."] - ,Div ("lst:captionAttr",["listing","haskell"],[]) - [Para [Str "Listing\160\&1:",Space,Str "Listing",Space,Str "caption"] - ,CodeBlock ("",["haskell"],[]) "main :: IO ()\nmain = putStrLn \"Hello World!\""] - ,RawBlock (Format "tex") "\\pagebreak" - ,Header 2 ("sec:table-capts",[],[]) [Str "Table-style",Space,Str "captions"] - ,Para [Str "Enabled",Space,Str "with",Space,Code ("",[],[]) "codeBlockCaptions",Space,Str "metadata",Space,Str "option.",Space,Str "If",Space,Str "code",Space,Str "block",Space,Str "is",Space,Str "immediately",SoftBreak,Str "adjacent",Space,Str "to",Space,Str "paragraph,",Space,Str "starting",Space,Str "with",Space,Code ("",[],[]) "Listing:",Space,Str "or",Space,Code ("",[],[]) ":",Str ",",Space,Str "said",Space,Str "paragraph",Space,Str "will",Space,Str "be",SoftBreak,Str "treated",Space,Str "as",Space,Str "code",Space,Str "block",Space,Str "caption."] - ,Div ("lst:tableCaption",["listing","haskell"],[]) - [Para [Str "Listing\160\&2:",Space,Str "Listing",Space,Str "caption"] - ,CodeBlock ("",["haskell"],[]) "main :: IO ()\nmain = putStrLn \"Hello World!\""] - ,Header 2 ("sec:wrapping-div",[],[]) [Str "Wrapping",Space,Str "div"] - ,Para [Str "Wrapping",Space,Str "code",Space,Str "block",Space,Str "without",Space,Str "label",Space,Str "in",Space,Str "a",Space,Str "div",Space,Str "with",Space,Str "id",Space,Code ("",[],[]) "lst:...",Space,Str "and",Space,Str "class,",Space,Str "starting",Space,Str "with",Space,Code ("",[],[]) "listing",Str ",",Space,Str "and",Space,Str "adding",Space,Str "paragraph",Space,Str "before",Space,Str "code",Space,Str "block,",Space,Str "but",Space,Str "inside",Space,Str "div,",Space,Str "will",Space,Str "treat",Space,Str "said",Space,Str "paragraph",Space,Str "as",Space,Str "code",Space,Str "block",Space,Str "caption."] - ,Div ("lst:wrappingDiv",["listing"],[]) - [Para [Str "Listing\160\&3:",Space] - ,Para [Str "Listing",Space,Str "caption"] - ,CodeBlock ("",["haskell"],[]) "main :: IO ()\nmain = putStrLn \"Hello World!\""] - ,Header 1 ("sec:unnumbered-chapter.",["unnumbered"],[]) [Str "Unnumbered",Space,Str "chapter."] - ,Para [Str "This",Space,Str "chapter",Space,Str "doesn\8217t",Space,Str "change",Space,Str "chapter",Space,Str "prefix",Space,Str "of",Space,Str "referenced",Space,Str "elements,",Space,Str "instead",Space,Str "keeping",Space,Str "number",Space,Str "of",Space,Str "previous",Space,Str "chapter,",Space,Str "e.g.",SoftBreak,Span ("eq:eqn2",[],[]) [Math DisplayMath " S(x) = \\int_{x_1}^{x_2} a x+b \\ \\mathrm{d}x \\qquad(3)"]] - ,Header 1 ("sec:chapter-5.-reference-lists",[],[]) [Str "Chapter",Space,Str "5.",Space,Str "Reference",Space,Str "lists"] - ,Para [Str "It\8217s",Space,Str "also",Space,Str "possible",Space,Str "to",Space,Str "show",Space,Str "lists",Space,Str "of",Space,Str "figures",Space,Str "and",Space,Str "tables,",Space,Str "like",Space,Str "this:"] - ,Header 2 ("list-of-figures",[],[]) [Str "List",Space,Str "of",Space,Str "Figures"] - ,Div ("",["list"],[]) - [Para [Str "1.",Space,Str "A",Space,Str "figure"] - ,Para [Str "2.",Space,Str "First",Space,Str "figure"] - ,Para [Str "3.",Space,Str "Second",Space,Str "figure"] - ,Para [Str "4.",Space,Str "Third",Space,Str "figure"] - ,Para [Str "5.",Space,Str "Unlabelled",Space,Str "image"] - ,Para [Str "6.",Space,Str "Subfigures",Space,Str "caption.",Space,Span ("",[],[]) []] - ,Para [Str "a.",Space,Str "Subfigure",Space,Str "a"] - ,Para [Str "b.",Space,Str "Subfigure",Space,Str "b"]] - ,Header 2 ("list-of-tables",[],[]) [Str "List",Space,Str "of",Space,Str "Tables"] - ,Div ("",["list"],[]) - [Para [Str "1.",Space,Str "Table",Space,Str "example"]] - ,Header 1 ("",[],[]) [Str "List",Space,Str "of",Space,Str "Listings"] - ,Div ("",["list"],[]) - [Para [Str "1.",Space,Str "Listing",Space,Str "caption"] - ,Para [Str "2.",Space,Str "Listing",Space,Str "caption"] - ,Para [Str "3.",Space]] - ,Header 1 ("sec:appendix-a.-custom-labels",[],[("label","AppA")]) [Str "Appendix",Space,Str "A.",Space,Str "Custom",Space,Str "labels"] - ,Header 2 ("sec:custlabs",[],[("label","CustLab")]) [Str "This",Space,Str "section",Space,Str "will",Space,Str "have",Space,Str "custom",Space,Str "label"]] diff --git a/test/demo.inc b/test/demo.inc index 74f5bcf3..cde126ef 100644 --- a/test/demo.inc +++ b/test/demo.inc @@ -1,17 +1,17 @@ - [Para [Str "This",Space,Str "is",Space,Str "a",Space,Str "demo",Space,Str "file",Space,Str "for",Space,Str "pandoc-crossref.",Space,Str "With",Space,Str "this",Space,Str "filter,",Space,Str "you",Space,Str "can",Space,Str "cross-reference",Space,Str "figures",Space,Str "(see",Space,Str "figs.\160\&2-4),",Space,Str "display",Space,Str "equations",Space,Str "(see",Space,Str "eq.\160\&1),",Space,Str "tables",Space,Str "(see",Space,Str "tbl.\160\&1)",Space,Str "and",Space,Str "sections",Space,Str "(",Str "secs.\160\&1,",Space,Str "2,",Space,Str "secs.\160.41-.43)"] + [Para [Str "This",Space,Str "is",Space,Str "a",Space,Str "demo",Space,Str "file",Space,Str "for",Space,Str "pandoc-crossref.",Space,Str "With",Space,Str "this",Space,Str "filter,",Space,Str "you",Space,Str "can",Space,Str "cross-reference",Space,Str "figures",Space,Str "(see",Space,Str "figs.\160\&1.1-1.3),",Space,Str "display",Space,Str "equations",Space,Str "(see",Space,Str "eq.\160\&2.1),",Space,Str "tables",Space,Str "(see",Space,Str "tbl.\160\&3.1)",Space,Str "and",Space,Str "sections",Space,Str "(",Str "secs.\160\&1,",Space,Str "2,",Space,Str "secs.\160\&4.1-4.3)"] ,Para [Str "For",Space,Str "immediate",Space,Str "example,",Space,Str "see",Space,Str "fig.\160\&1"] - ,Para [Image ("fig:figure0",[],[]) [Str "Figure",Space,Str "#\160\&1:",Space,Str "A",Space,Str "figure"] ("img1.jpg","fig:")] - ,Para [Str "There",Space,Str "is",Space,Str "also",Space,Str "support",Space,Str "for",Space,Str "code",Space,Str "blocks,",Space,Str "for",Space,Str "example,",Space,Str "lsts.\160\&1-3"] - ,Para [Str "It\8217s",Space,Str "possible",Space,Str "to",Space,Str "capitalize",Space,Str "reference",Space,Str "prefixes,",Space,Str "like",Space,Str "this:",Space,Str "Fig.\160\&2."] - ,Para [Str "In",Space,Str "case",Space,Str "of",Space,Str "multiple",Space,Str "references,",Space,Str "capitalization",Space,Str "is",Space,Str "determined",Space,Str "by",Space,Str "first",Space,Str "reference.",Space,Str "Figs.\160\&2,",Space,Str "3",Space,Str "is",Space,Str "capitalized,",Space,Str "while",Space,Str "figs.\160\&2,",Space,Str "3",Space,Str "is",Space,Str "not."] - ,Para [Str "It",Space,Str "is",Space,Str "also",Space,Str "possible",Space,Str "to",Space,Str "mix",Space,Str "different",Space,Str "references,",Space,Str "like",Space,Str "fig.\160\&2,",Space,Str "tbl.\160\&1,",Space,Str "lsts.\160\&1,",Space,Str "2,",Space,Str "figs.\160\&3,",Space,Str "4,",Space,Str "which",Space,Str "will",Space,Str "be",Space,Str "grouped",Space,Str "in",Space,Str "order",Space,Str "they",Space,Str "are",Space,Str "specified.",Space,Str "You",Space,Str "can",Space,Str "even",Space,Str "intermix",Space,Str "this",Space,Str "with",Space,Str "regular",Space,Str "citations,",Space,Str "although",Space,Str "it\8217s",Space,Str "not",Space,Str "recommended:",Space,Str "fig.\160\&2,",Space,Str "tbl.\160\&1,",Space,Cite [Citation {citationId = "unprocessedCitation", citationPrefix = [], citationSuffix = [], citationMode = NormalCitation, citationNoteNum = 0, citationHash = 0}] [Str "[@unprocessedCitation]"]] - ,Para [Str "You",Space,Str "can",Space,Str "also",Space,Str "have",Space,Str "custom",Space,Str "chapter",Space,Str "reference",Space,Str "labels,",Space,Str "like",Space,Str "sec.\160.AppACustLab"] - ,Para [Str "Subfigures",Space,Str "are",Space,Str "supported,",Space,Str "see",Space,Str "fig.\160\&6,",Space,Str "fig.\160\&6",Space,Str "(b)"] + ,Para [Image ("fig:figure0",[],[]) [Str "Figure\160\&1:",Space,Str "A",Space,Str "figure"] ("img1.jpg","fig:")] + ,Para [Str "There",Space,Str "is",Space,Str "also",Space,Str "support",Space,Str "for",Space,Str "code",Space,Str "blocks,",Space,Str "for",Space,Str "example,",Space,Str "lsts.\160\&4.1.1,",Space,Str "4.2.1,",Space,Str "4.3.1"] + ,Para [Str "It\8217s",Space,Str "possible",Space,Str "to",Space,Str "capitalize",Space,Str "reference",Space,Str "prefixes,",Space,Str "like",Space,Str "this:",Space,Str "Fig.\160\&1.1."] + ,Para [Str "In",Space,Str "case",Space,Str "of",Space,Str "multiple",Space,Str "references,",Space,Str "capitalization",Space,Str "is",Space,Str "determined",Space,Str "by",Space,Str "first",Space,Str "reference.",Space,Str "Figs.\160\&1.1,",Space,Str "1.2",Space,Str "is",Space,Str "capitalized,",Space,Str "while",Space,Str "figs.\160\&1.1,",Space,Str "1.2",Space,Str "is",Space,Str "not."] + ,Para [Str "It",Space,Str "is",Space,Str "also",Space,Str "possible",Space,Str "to",Space,Str "mix",Space,Str "different",Space,Str "references,",Space,Str "like",Space,Str "fig.\160\&1.1,",Space,Str "tbl.\160\&3.1,",Space,Str "lsts.\160\&4.1.1,",Space,Str "4.2.1,",Space,Str "figs.\160\&1.2,",Space,Str "1.3,",Space,Str "which",Space,Str "will",Space,Str "be",Space,Str "grouped",Space,Str "in",Space,Str "order",Space,Str "they",Space,Str "are",Space,Str "specified.",Space,Str "You",Space,Str "can",Space,Str "even",Space,Str "intermix",Space,Str "this",Space,Str "with",Space,Str "regular",Space,Str "citations,",Space,Str "although",Space,Str "it\8217s",Space,Str "not",Space,Str "recommended:",Space,Str "fig.\160\&1.1,",Space,Str "tbl.\160\&3.1,",Space,Cite [Citation {citationId = "unprocessedCitation", citationPrefix = [], citationSuffix = [], citationMode = NormalCitation, citationNoteNum = 0, citationHash = 0}] [Str "[@unprocessedCitation]"]] + ,Para [Str "You",Space,Str "can",Space,Str "also",Space,Str "have",Space,Str "custom",Space,Str "chapter",Space,Str "reference",Space,Str "labels,",Space,Str "like",Space,Str "sec.\160A.I"] + ,Para [Str "Subfigures",Space,Str "are",Space,Str "supported,",Space,Str "see",Space,Str "fig.\160\&1.5,",Space,Str "fig.\160\&1.5(b)"] ,Header 1 ("sec:sec1",[],[]) [Str "Chapter",Space,Str "1.",Space,Str "Figures"] - ,Para [Image ("fig:figure1",[],[]) [Str "Figure",Space,Str "#\160\&2:",Space,Str "First",Space,Str "figure"] ("img1.jpg","fig:")] - ,Para [Image ("fig:figure2",[],[]) [Str "Figure",Space,Str "#\160\&3:",Space,Str "Second",Space,Str "figure"] ("img2.jpg","fig:")] - ,Para [Image ("fig:figure3",[],[]) [Str "Figure",Space,Str "#\160\&4:",Space,Str "Third",Space,Str "figure"] ("img3.jpg","fig:")] - ,Para [Image ("",[],[]) [Str "Figure",Space,Str "#\160\&5:",Space,Str "Unlabelled",Space,Str "image"] ("img1.jpg","fig:")] + ,Para [Image ("fig:figure1",[],[]) [Str "Figure\160\&1.1:",Space,Str "First",Space,Str "figure"] ("img1.jpg","fig:")] + ,Para [Image ("fig:figure2",[],[]) [Str "Figure\160\&1.2:",Space,Str "Second",Space,Str "figure"] ("img2.jpg","fig:")] + ,Para [Image ("fig:figure3",[],[]) [Str "Figure\160\&1.3:",Space,Str "Third",Space,Str "figure"] ("img3.jpg","fig:")] + ,Para [Image ("",[],[]) [Str "Figure\160\&1.4:",Space,Str "Unlabelled",Space,Str "image"] ("img1.jpg","fig:")] ,Div ("fig:subfigures",["subcaption"],[]) [Table [] [AlignCenter] [0.99] [] @@ -19,14 +19,14 @@ [Para [Image ("",[],[("width","100%")]) [Str "a"] ("img1.jpg","fig:")]]]] ,[[Div ("",[],[]) [Para [Image ("fig:subfigureB",[],[("width","100%")]) [Str "b"] ("img1.jpg","fig:")]]]]] - ,Para [Str "Figure",Space,Str "#\160\&6:",Space,Str "Subfigures",Space,Str "caption.",Space,Span ("",[],[]) [Str "a",Space,Str "\8211",Space,Str "Subfigure",Space,Str "a,",Space,Str "b",Space,Str "\8211",Space,Str "Subfigure",Space,Str "b"]]] + ,Para [Str "Figure\160\&1.5:",Space,Str "Subfigures",Space,Str "caption.",Space,Span ("",[],[]) [Str "a",Space,Str "\8211",Space,Str "Subfigure",Space,Str "a,",Space,Str "b",Space,Str "\8211",Space,Str "Subfigure",Space,Str "b"]]] ,Header 1 ("sec:sec2",[],[]) [Str "Chapter",Space,Str "2.",Space,Str "Equations"] ,Para [Str "Display",Space,Str "equations",Space,Str "are",Space,Str "labelled",Space,Str "and",Space,Str "numbered"] - ,Para [Span ("eq:eqn1",[],[]) [Math DisplayMath " P_i(x) = \\sum_i a_i x^i \\qquad(1)"]] - ,Para [Str "Since",Space,Str "0.1.6.0",Space,Str "those",Space,Str "can",Space,Str "also",Space,Str "appear",Space,Str "in",Space,Str "the",Space,Str "middle",Space,Str "of",Space,Str "paragraph",SoftBreak,Span ("eq:quadr",[],[]) [Math DisplayMath "a x^2 + b x^2 + c = 0\\qquad(2)"],Space,Str "like",Space,Str "this."] - ,Header 1 ("sec:chapter-3.-tables",[],[]) [Str "Chapter",Space,Str "3.",Space,Str "Tables"] + ,Para [Span ("eq:eqn1",[],[]) [Math DisplayMath " P_i(x) = \\sum_i a_i x^i \\qquad(2.1)"]] + ,Para [Str "Since",Space,Str "0.1.6.0",Space,Str "those",Space,Str "can",Space,Str "also",Space,Str "appear",Space,Str "in",Space,Str "the",Space,Str "middle",Space,Str "of",Space,Str "paragraph",SoftBreak,Span ("eq:quadr",[],[]) [Math DisplayMath "a x^2 + b x^2 + c = 0\\qquad(2.2)"],Space,Str "like",Space,Str "this."] + ,Header 1 ("sec:tables",[],[]) [Str "Chapter",Space,Str "3.",Space,Str "Tables"] ,Div ("tbl:table1",[],[]) - [Table [Emph [Str "Table",Space,Str "1"],Str ":",Space,Str "Table",Space,Str "example"] [AlignLeft,AlignLeft] [0.0,0.0] + [Table [Str "Table\160\&3.1:",Space,Str "Table",Space,Str "example"] [AlignLeft,AlignLeft] [0.0,0.0] [[Plain [Str "First",Space,Str "Header"]] ,[Plain [Str "Second",Space,Str "Header"]]] [[[Plain [Str "Content",Space,Str "Cell"]] @@ -41,46 +41,45 @@ ,[Plain [Str "Content",Space,Str "Cell"]]] ,[[Plain [Str "Content",Space,Str "Cell"]] ,[Plain [Str "Content",Space,Str "Cell"]]]] - ,Header 1 ("sec:chapter-4.-code-blocks",[],[]) [Str "Chapter",Space,Str "4.",Space,Str "Code",Space,Str "blocks"] + ,Header 1 ("sec:code-blocks",[],[]) [Str "Chapter",Space,Str "4.",Space,Str "Code",Space,Str "blocks"] ,Para [Str "There",Space,Str "are",Space,Str "a",Space,Str "couple",Space,Str "options",Space,Str "for",Space,Str "code",Space,Str "block",Space,Str "labels.",Space,Str "Those",Space,Str "work",Space,Str "only",Space,Str "if",Space,Str "code",Space,Str "block",Space,Str "id",Space,Str "starts",Space,Str "with",Space,Code ("",[],[]) "lst:",Str ",",Space,Str "e.g.\160",Code ("",[],[]) "{#lst:label}"] - ,Header 2 ("sec:caption-attr",[],[]) [Code ("",[],[]) "caption",Space,Str "attribute"] + ,Header 2 ("sec:caption-attr",[],[]) [Str "Section",Space,Str "4.1.",Space,Code ("",[],[]) "caption",Space,Str "attribute"] ,Para [Code ("",[],[]) "caption",Space,Str "attribute",Space,Str "will",Space,Str "be",Space,Str "treated",Space,Str "as",Space,Str "code",Space,Str "block",Space,Str "caption.",Space,Str "If",Space,Str "code",Space,Str "block",Space,Str "has",Space,Str "both",Space,Str "id",Space,Str "and",Space,Code ("",[],[]) "caption",Space,Str "attributes,",Space,Str "it",Space,Str "will",Space,Str "be",Space,Str "treated",Space,Str "as",Space,Str "numbered",Space,Str "code",Space,Str "block."] ,Div ("lst:captionAttr",["listing","haskell"],[]) - [Para [Str "Listing\160\&1:",Space,Str "Listing",Space,Str "caption"] + [Para [Str "Listing\160\&4.1.1:",Space,Str "Listing",Space,Str "caption"] ,CodeBlock ("",["haskell"],[]) "main :: IO ()\nmain = putStrLn \"Hello World!\""] ,RawBlock (Format "tex") "\\pagebreak" - ,Header 2 ("sec:table-capts",[],[]) [Str "Table-style",Space,Str "captions"] + ,Header 2 ("sec:table-capts",[],[]) [Str "Section",Space,Str "4.2.",Space,Str "Table-style",Space,Str "captions"] ,Para [Str "Enabled",Space,Str "with",Space,Code ("",[],[]) "codeBlockCaptions",Space,Str "metadata",Space,Str "option.",Space,Str "If",Space,Str "code",Space,Str "block",Space,Str "is",Space,Str "immediately",SoftBreak,Str "adjacent",Space,Str "to",Space,Str "paragraph,",Space,Str "starting",Space,Str "with",Space,Code ("",[],[]) "Listing:",Space,Str "or",Space,Code ("",[],[]) ":",Str ",",Space,Str "said",Space,Str "paragraph",Space,Str "will",Space,Str "be",SoftBreak,Str "treated",Space,Str "as",Space,Str "code",Space,Str "block",Space,Str "caption."] ,Div ("lst:tableCaption",["listing","haskell"],[]) - [Para [Str "Listing\160\&2:",Space,Str "Listing",Space,Str "caption"] + [Para [Str "Listing\160\&4.2.1:",Space,Str "Listing",Space,Str "caption"] ,CodeBlock ("",["haskell"],[]) "main :: IO ()\nmain = putStrLn \"Hello World!\""] - ,Header 2 ("sec:wrapping-div",[],[]) [Str "Wrapping",Space,Str "div"] - ,Para [Str "Wrapping",Space,Str "code",Space,Str "block",Space,Str "without",Space,Str "label",Space,Str "in",Space,Str "a",Space,Str "div",Space,Str "with",Space,Str "id",Space,Code ("",[],[]) "lst:...",Space,Str "and",Space,Str "class,",Space,Str "starting",Space,Str "with",Space,Code ("",[],[]) "listing",Str ",",Space,Str "and",Space,Str "adding",Space,Str "paragraph",Space,Str "before",Space,Str "code",Space,Str "block,",Space,Str "but",Space,Str "inside",Space,Str "div,",Space,Str "will",Space,Str "treat",Space,Str "said",Space,Str "paragraph",Space,Str "as",Space,Str "code",Space,Str "block",Space,Str "caption."] + ,Header 2 ("sec:wrapping-div",[],[]) [Str "Section",Space,Str "4.3.",Space,Str "Wrapping",Space,Str "div"] + ,Para [Str "Wrapping",Space,Str "code",Space,Str "block",Space,Str "without",Space,Str "label",Space,Str "in",Space,Str "a",Space,Str "div",Space,Str "with",Space,Str "id",Space,Code ("",[],[]) "lst:...",Space,Str "and",Space,Str "class,",Space,Str "starting",Space,Str "with",Space,Code ("",[],[]) "listing",Str ",",Space,Str "and",Space,Str "adding",Space,Str "paragraph",Space,Str "after",Space,Str "code",Space,Str "block,",Space,Str "but",Space,Str "inside",Space,Str "div,",Space,Str "starting",Space,Str "with",Space,Code ("",[],[]) ":",Space,Str "will",Space,Str "treat",Space,Str "said",Space,Str "paragraph",Space,Str "as",Space,Str "code",Space,Str "block",Space,Str "caption."] ,Div ("lst:wrappingDiv",["listing"],[]) - [Para [Str "Listing\160\&3:",Space] - ,Para [Str "Listing",Space,Str "caption"] + [Para [Str "Listing\160\&4.3.1:",Space,Str "Listing",Space,Str "caption"] ,CodeBlock ("",["haskell"],[]) "main :: IO ()\nmain = putStrLn \"Hello World!\""] ,Header 1 ("sec:unnumbered-chapter.",["unnumbered"],[]) [Str "Unnumbered",Space,Str "chapter."] - ,Para [Str "This",Space,Str "chapter",Space,Str "doesn\8217t",Space,Str "change",Space,Str "chapter",Space,Str "prefix",Space,Str "of",Space,Str "referenced",Space,Str "elements,",Space,Str "instead",Space,Str "keeping",Space,Str "number",Space,Str "of",Space,Str "previous",Space,Str "chapter,",Space,Str "e.g.",SoftBreak,Span ("eq:eqn2",[],[]) [Math DisplayMath " S(x) = \\int_{x_1}^{x_2} a x+b \\ \\mathrm{d}x \\qquad(3)"]] - ,Header 1 ("sec:chapter-5.-reference-lists",[],[]) [Str "Chapter",Space,Str "5.",Space,Str "Reference",Space,Str "lists"] + ,Para [Str "This",Space,Str "chapter",Space,Str "doesn\8217t",Space,Str "change",Space,Str "chapter",Space,Str "prefix",Space,Str "of",Space,Str "referenced",Space,Str "elements,",Space,Str "instead",Space,Str "keeping",Space,Str "number",Space,Str "of",Space,Str "previous",Space,Str "chapter,",Space,Str "e.g.",SoftBreak,Span ("eq:eqn2",[],[]) [Math DisplayMath " S(x) = \\int_{x_1}^{x_2} a x+b \\ \\mathrm{d}x \\qquad(1)"]] + ,Header 1 ("sec:reference-lists",[],[]) [Str "Chapter",Space,Str "5.",Space,Str "Reference",Space,Str "lists"] ,Para [Str "It\8217s",Space,Str "also",Space,Str "possible",Space,Str "to",Space,Str "show",Space,Str "lists",Space,Str "of",Space,Str "figures",Space,Str "and",Space,Str "tables,",Space,Str "like",Space,Str "this:"] - ,Header 2 ("list-of-figures",[],[]) [Str "List",Space,Str "of",Space,Str "Figures"] + ,Header 1 ("",[],[]) [Str "List",Space,Str "of",Space,Str "Figures"] ,Div ("",["list"],[]) [Para [Str "1.",Space,Str "A",Space,Str "figure"] - ,Para [Str "2.",Space,Str "First",Space,Str "figure"] - ,Para [Str "3.",Space,Str "Second",Space,Str "figure"] - ,Para [Str "4.",Space,Str "Third",Space,Str "figure"] - ,Para [Str "5.",Space,Str "Unlabelled",Space,Str "image"] - ,Para [Str "6.",Space,Str "Subfigures",Space,Str "caption.",Space,Span ("",[],[]) []] - ,Para [Str "a.",Space,Str "Subfigure",Space,Str "a"] - ,Para [Str "b.",Space,Str "Subfigure",Space,Str "b"]] - ,Header 2 ("list-of-tables",[],[]) [Str "List",Space,Str "of",Space,Str "Tables"] + ,Para [Str "1.1.",Space,Str "First",Space,Str "figure"] + ,Para [Str "1.2.",Space,Str "Second",Space,Str "figure"] + ,Para [Str "1.3.",Space,Str "Third",Space,Str "figure"] + ,Para [Str "1.4.",Space,Str "Unlabelled",Space,Str "image"] + ,Para [Str "1.5.",Space,Str "Subfigures",Space,Str "caption.",Space,Span ("",[],[]) []] + ,Para [Str "1.5(a).",Space,Str "Subfigure",Space,Str "a"] + ,Para [Str "1.5(b).",Space,Str "Subfigure",Space,Str "b"]] + ,Header 1 ("",[],[]) [Str "List",Space,Str "of",Space,Str "Tables"] ,Div ("",["list"],[]) - [Para [Str "1.",Space,Str "Table",Space,Str "example"]] + [Para [Str "3.1.",Space,Str "Table",Space,Str "example"]] ,Header 1 ("",[],[]) [Str "List",Space,Str "of",Space,Str "Listings"] ,Div ("",["list"],[]) - [Para [Str "1.",Space,Str "Listing",Space,Str "caption"] - ,Para [Str "2.",Space,Str "Listing",Space,Str "caption"] - ,Para [Str "3.",Space]] - ,Header 1 ("sec:appendix-a.-custom-labels",[],[("label","AppA")]) [Str "Appendix",Space,Str "A.",Space,Str "Custom",Space,Str "labels"] - ,Header 2 ("sec:custlabs",[],[("label","CustLab")]) [Str "This",Space,Str "section",Space,Str "will",Space,Str "have",Space,Str "custom",Space,Str "label"]] + [Para [Str "4.1.1.",Space,Str "Listing",Space,Str "caption"] + ,Para [Str "4.2.1.",Space,Str "Listing",Space,Str "caption"] + ,Para [Str "4.3.1.",Space,Str "Listing",Space,Str "caption"]] + ,Header 1 ("sec:custom-labels",[],[("label","A"),("title","Appendix")]) [Str "Appendix",Space,Str "A.",Space,Str "Custom",Space,Str "labels"] + ,Header 2 ("sec:custlabs",[],[("label","I")]) [Str "Section",Space,Str "A.I.",Space,Str "This",Space,Str "section",Space,Str "will",Space,Str "have",Space,Str "custom",Space,Str "label"]] diff --git a/test/test-pandoc-crossref.hs b/test/test-pandoc-crossref.hs index 97b7ff96..9f6dd7d7 100644 --- a/test/test-pandoc-crossref.hs +++ b/test/test-pandoc-crossref.hs @@ -336,13 +336,6 @@ main = hspec $ do Pandoc m b <- handleError $ runPure $ readMarkdown def {readerExtensions = pandocExtensions} $ T.pack demomd let (res, _warn) = runCrossRef (Settings m) Nothing $ crossRefBlocks b res `shouldBe` Right Native.demo - - it "demo.md with chapters matches demo-chapters.native" $ do - demomd <- readFile =<< getDataFileName "docs/demo/demo.md" - Pandoc m b <- handleError $ runPure $ readMarkdown def {readerExtensions = pandocExtensions} $ T.pack demomd - let m' = setMeta "chapters" True m - let (res, _warn) = runCrossRef (Settings m') Nothing $ crossRefBlocks b - res `shouldBe` Right Native.demochapters #endif citeGen :: String -> [Int] -> Inlines From 3e2fbdea0c070705ae435d405e4029bc29772119 Mon Sep 17 00:00:00 2001 From: Nikolay Yakimov Date: Wed, 1 May 2019 21:31:01 +0300 Subject: [PATCH 090/134] Fix test --- test/test-pandoc-crossref.hs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/test/test-pandoc-crossref.hs b/test/test-pandoc-crossref.hs index 9f6dd7d7..74c009e2 100644 --- a/test/test-pandoc-crossref.hs +++ b/test/test-pandoc-crossref.hs @@ -376,7 +376,7 @@ testAll :: Many Block -> (Many Block, References -> References) -> Expectation testAll = testState References.Blocks.replaceAll def evalCrossRefM :: CrossRefM c -> c -evalCrossRefM = evalCrossRefRes . runCrossRef defaultMeta Nothing . CrossRef +evalCrossRefM = evalCrossRefRes . runCrossRef (defaultMeta mempty) Nothing . CrossRef evalCrossRefRes :: (Either WSException c, b) -> c evalCrossRefRes = either (error . show) id . fst @@ -451,7 +451,7 @@ ref' p n | null n = mempty | otherwise = space <> str ("{#"++p++":"++n++"}") defaultOptions :: Options -defaultOptions = getOptions defaultMeta Nothing +defaultOptions = getOptions (defaultMeta mempty) Nothing defCit :: Citation defCit = Citation{citationId = "" @@ -470,4 +470,4 @@ infixr 0 =: a =: b = a ^= b defaultPrefixes :: Prefixes -defaultPrefixes = getPrefixes Nothing "prefixes" defaultMeta +defaultPrefixes = getPrefixes Nothing "prefixes" (defaultMeta mempty) From 5a0d02b4f9ba8d8df93879413904842575cf803a Mon Sep 17 00:00:00 2001 From: Nikolay Yakimov Date: Wed, 1 May 2019 21:31:01 +0300 Subject: [PATCH 091/134] Fix test --- pandoc-crossref.cabal | 3 +-- test/test-pandoc-crossref.hs | 6 +++--- 2 files changed, 4 insertions(+), 5 deletions(-) diff --git a/pandoc-crossref.cabal b/pandoc-crossref.cabal index a1672184..c0a7342d 100644 --- a/pandoc-crossref.cabal +++ b/pandoc-crossref.cabal @@ -4,7 +4,7 @@ cabal-version: 1.12 -- -- see: https://github.com/sol/hpack -- --- hash: 29a16982bbf4d0374a7ea424d1f675afda7029727f410eadca021ecf8636ee26 +-- hash: e350c271ccc68235166df64b7a25b7e408f3b33f487064958bc2936eaf58d672 name: pandoc-crossref version: 0.4.0.0 @@ -19,7 +19,6 @@ license: GPL-2 license-file: LICENSE build-type: Simple extra-source-files: - test/demo-chapters.inc test/demo.inc CHANGELOG.md data-files: diff --git a/test/test-pandoc-crossref.hs b/test/test-pandoc-crossref.hs index 9f6dd7d7..74c009e2 100644 --- a/test/test-pandoc-crossref.hs +++ b/test/test-pandoc-crossref.hs @@ -376,7 +376,7 @@ testAll :: Many Block -> (Many Block, References -> References) -> Expectation testAll = testState References.Blocks.replaceAll def evalCrossRefM :: CrossRefM c -> c -evalCrossRefM = evalCrossRefRes . runCrossRef defaultMeta Nothing . CrossRef +evalCrossRefM = evalCrossRefRes . runCrossRef (defaultMeta mempty) Nothing . CrossRef evalCrossRefRes :: (Either WSException c, b) -> c evalCrossRefRes = either (error . show) id . fst @@ -451,7 +451,7 @@ ref' p n | null n = mempty | otherwise = space <> str ("{#"++p++":"++n++"}") defaultOptions :: Options -defaultOptions = getOptions defaultMeta Nothing +defaultOptions = getOptions (defaultMeta mempty) Nothing defCit :: Citation defCit = Citation{citationId = "" @@ -470,4 +470,4 @@ infixr 0 =: a =: b = a ^= b defaultPrefixes :: Prefixes -defaultPrefixes = getPrefixes Nothing "prefixes" defaultMeta +defaultPrefixes = getPrefixes Nothing "prefixes" (defaultMeta mempty) From da66f554d9050665865adf8939805b276dea4315 Mon Sep 17 00:00:00 2001 From: Nikolay Yakimov Date: Sun, 4 Aug 2019 22:06:58 +0300 Subject: [PATCH 092/134] Pin Pandoc version to 2.7.3 --- .travis.yml | 4 ++-- appveyor.yml | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/.travis.yml b/.travis.yml index dfbbf002..6477f254 100644 --- a/.travis.yml +++ b/.travis.yml @@ -17,8 +17,8 @@ env: global: - RUN_UPX: yes - DOCKER_IMAGE_VERSION: latest - - PANDOC_VERSION: 2.7 - - CABAL_OPTS="--constraint pandoc==$PANDOC_VERSION.*" + - PANDOC_VERSION: 2.7.3 + - CABAL_OPTS="--constraint pandoc==$PANDOC_VERSION" services: - docker diff --git a/appveyor.yml b/appveyor.yml index 8e132be4..b3f4a0c6 100644 --- a/appveyor.yml +++ b/appveyor.yml @@ -13,12 +13,12 @@ environment: GHC_MINOR_VERSION: "8.4.4" GHC: "C:\\ProgramData\\chocolatey\\lib\\ghc\\tools\\ghc-%GHC_MINOR_VERSION%\\bin\\ghc.exe" CABAL_VERSION: "2.4.1.0" - CABAL_OPTS: "--constraint pandoc==%PANDOC_VERSION%.* --enable-executable-stripping --enable-split-sections" + CABAL_OPTS: "--constraint pandoc==%PANDOC_VERSION% --enable-executable-stripping --enable-split-sections" GHC_OPTS: "" ARCH: "x64" CHOCO_OPTS: "" matrix: - - PANDOC_VERSION: "2.7" + - PANDOC_VERSION: "2.7.3" skip_commits: files: From bb1fe27fa800d3232d30c8fc63d3b9705289b17c Mon Sep 17 00:00:00 2001 From: Nikolay Yakimov Date: Mon, 5 Aug 2019 01:17:14 +0300 Subject: [PATCH 093/134] Use xcode10.2 for OSX Travis builds --- .travis.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.travis.yml b/.travis.yml index 6477f254..04cfc26f 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,5 +1,6 @@ language: c sudo: true +osx_image: xcode10.2 cache: directories: From 027c33be21e20fbee44211629e77c322568e8ea6 Mon Sep 17 00:00:00 2001 From: Nikolay Yakimov Date: Sat, 5 Oct 2019 13:56:08 +0300 Subject: [PATCH 094/134] Clean up test code; enable flaky tests in cabal-v2 builds --- cabal.project | 4 ++++ test/Native.hs | 4 +--- test/test-pandoc-crossref.hs | 4 +++- 3 files changed, 8 insertions(+), 4 deletions(-) create mode 100644 cabal.project diff --git a/cabal.project b/cabal.project new file mode 100644 index 00000000..593134c9 --- /dev/null +++ b/cabal.project @@ -0,0 +1,4 @@ +packages: pandoc-crossref.cabal +optimization: 2 +package pandoc-crossref + flags: +enable_flaky_tests diff --git a/test/Native.hs b/test/Native.hs index 13c6d318..db388dff 100644 --- a/test/Native.hs +++ b/test/Native.hs @@ -23,9 +23,7 @@ module Native where import Text.Pandoc.Definition -demo, demochapters :: [Block] +demo :: [Block] demo = #include "demo.inc" -demochapters = -#include "demo-chapters.inc" diff --git a/test/test-pandoc-crossref.hs b/test/test-pandoc-crossref.hs index 74c009e2..fb900bb4 100644 --- a/test/test-pandoc-crossref.hs +++ b/test/test-pandoc-crossref.hs @@ -29,7 +29,6 @@ import Data.List import Data.Maybe import Control.Arrow import qualified Data.Map as M -import qualified Data.Text as T import Text.Pandoc.CrossRef import Text.Pandoc.CrossRef.Util.Options @@ -44,8 +43,11 @@ import qualified Text.Pandoc.CrossRef.References.List as References.List import qualified Text.Pandoc.CrossRef.Util.Template as Util.Template import qualified Text.Pandoc.CrossRef.Util.CodeBlockCaptions as Util.CodeBlockCaptions +#ifdef FLAKY +import qualified Data.Text as T import qualified Native import Paths_pandoc_crossref +#endif import Data.String import Prelude From 6e73e2bdd18bfd6fec07282b688a97b07beb8f10 Mon Sep 17 00:00:00 2001 From: Nikolay Yakimov Date: Sun, 24 Nov 2019 02:59:39 +0300 Subject: [PATCH 095/134] Move default `referenceIndexTemplate` for sections to upper level --- lib/Text/Pandoc/CrossRef/Util/Settings.hs | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/lib/Text/Pandoc/CrossRef/Util/Settings.hs b/lib/Text/Pandoc/CrossRef/Util/Settings.hs index 7fd60789..48746fd1 100644 --- a/lib/Text/Pandoc/CrossRef/Util/Settings.hs +++ b/lib/Text/Pandoc/CrossRef/Util/Settings.hs @@ -163,9 +163,7 @@ basicMeta = Settings $ "title" .= text "Section", "captionTemplate" .= var "t", "scope" .= ["sec" :: T.Text], - "sub" .: [ - "referenceIndexTemplate" .= var "s.i%." <> var "i" <> var "suf" - ] + "referenceIndexTemplate" .= var "s.i%." <> var "i" <> var "suf" ] ] From 75743f4b4319cbba52debe15a5a60eaa27d01c58 Mon Sep 17 00:00:00 2001 From: Nikolay Yakimov Date: Sun, 24 Nov 2019 02:59:57 +0300 Subject: [PATCH 096/134] Update test expectations --- test/m2m/list-of/expect.md | 4 ++++ test/m2m/subfigures-grid/expect.md | 12 ++++++------ 2 files changed, 10 insertions(+), 6 deletions(-) diff --git a/test/m2m/list-of/expect.md b/test/m2m/list-of/expect.md index 73002e44..c38a32ee 100644 --- a/test/m2m/list-of/expect.md +++ b/test/m2m/list-of/expect.md @@ -64,5 +64,9 @@ List of Tables 3\. Table 3 ::: +```{=tex} \listoffigures +``` +```{=tex} \listoftables +``` diff --git a/test/m2m/subfigures-grid/expect.md b/test/m2m/subfigures-grid/expect.md index 5b58c24c..951bab35 100644 --- a/test/m2m/subfigures-grid/expect.md +++ b/test/m2m/subfigures-grid/expect.md @@ -4,24 +4,24 @@ You can define subfigures: +:------------------:+:------------------:+:------------------:+ |
|
|
| | | | | -| ![a](fig1.png){#fi | ![b](fig2.png){#fi | ![c](fig3.png){wid | -| g:subfig1 | g:subfig2 | th="100%"} | +| ![a](fig1 | ![b](fig2 | ![c](fig3. | +| .png){#fig:subfig1 | .png){#fig:subfig2 | png){width="100%"} | | width="100%"} | width="100%"} | | | | |
| |
|
| | +--------------------+--------------------+--------------------+ |
|
|
| | | | | -| ![d](fig4.png){#fi | ![e](fig5.png){wid | ![f](fig6.png){#fi | -| g:subfig4 | th="100%"} | g:subfig6 | +| ![d](fig4 | ![e](fig5. | ![f](fig6 | +| .png){#fig:subfig4 | png){width="100%"} | .png){#fig:subfig6 | | width="100%"} | | width="100%"} | | |
| | |
| |
| +--------------------+--------------------+--------------------+ |
|
|
| | | | | -| ![g](fig7.png){#fi | ![h](fig8.png){wid | ![i](fig9.png){#fi | -| g:subfig7 | th="100%"} | g:subfig9 | +| ![g](fig7 | ![h](fig8. | ![i](fig9 | +| .png){#fig:subfig7 | png){width="100%"} | .png){#fig:subfig9 | | width="100%"} | | width="100%"} | | |
| | |
| |
| From 034b0432dd15d7dfe6fdfa2e82b72531e4859406 Mon Sep 17 00:00:00 2001 From: Nikolay Yakimov Date: Sun, 24 Nov 2019 03:00:25 +0300 Subject: [PATCH 097/134] Update test inputs --- test/m2m/numbering-parts/input.md | 1 + test/m2m/template-objects/input.md | 2 +- test/m2m/template-options/input.md | 2 +- 3 files changed, 3 insertions(+), 2 deletions(-) diff --git a/test/m2m/numbering-parts/input.md b/test/m2m/numbering-parts/input.md index 2f6e4a93..02191d13 100644 --- a/test/m2m/numbering-parts/input.md +++ b/test/m2m/numbering-parts/input.md @@ -19,6 +19,7 @@ prefixes: ref: ["sec.", "secs."] # We also want to show parent scope number in reference and title captionIndexTemplate: '$$s.i$$.$$ri$$' + referenceIndexTemplate: '$$s.i$$.$$ri$$' ... # First part {#prt:prt1} diff --git a/test/m2m/template-objects/input.md b/test/m2m/template-objects/input.md index b5d06be9..6eacc7ac 100644 --- a/test/m2m/template-objects/input.md +++ b/test/m2m/template-objects/input.md @@ -1,7 +1,7 @@ --- prefixes: sec: - listItemTemplate: '$$i$$$$listItemNumberDelim$$$$sectionType[type]%: $$$$t$$' + listItemTemplate: '$$idx$$$$listItemNumberDelim$$$$sectionType[type]%: $$$$t$$' sectionType: cha: "Chapter" sec: "Section" diff --git a/test/m2m/template-options/input.md b/test/m2m/template-options/input.md index 2882a2cc..a5dcac21 100644 --- a/test/m2m/template-options/input.md +++ b/test/m2m/template-options/input.md @@ -1,7 +1,7 @@ --- prefixes: sec: - listItemTemplate: '$$i$$$$listItemNumberDelim$$$$shortCaption?shortCaption2?t$$' + listItemTemplate: '$$idx$$$$listItemNumberDelim$$$$shortCaption?shortCaption2?t$$' ... # Section 1 {#sec:1} From 7e7f575af3d07a6a0090fcf99c6a837e167aa7f4 Mon Sep 17 00:00:00 2001 From: Nikolay Yakimov Date: Sun, 24 Nov 2019 03:02:24 +0300 Subject: [PATCH 098/134] Fix CI configs --- .travis.yml | 4 ++-- appveyor.yml | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/.travis.yml b/.travis.yml index bafe7f07..0b3b8b72 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,5 +1,3 @@ - - DOCKER_IMAGE_VERSION: b5789c3d3b0e6286d5b7d08d30981680043d0bc4 - - PANDOC_VERSION: "2.8" language: c sudo: true osx_image: xcode10.2 @@ -16,6 +14,8 @@ addons: env: global: - RUN_UPX: yes + - DOCKER_IMAGE_VERSION: b5789c3d3b0e6286d5b7d08d30981680043d0bc4 + - PANDOC_VERSION: "2.8" - CABAL_OPTS="--constraint pandoc==$PANDOC_VERSION" services: diff --git a/appveyor.yml b/appveyor.yml index 0ca5e9b8..cf59afe9 100644 --- a/appveyor.yml +++ b/appveyor.yml @@ -1,4 +1,3 @@ - - PANDOC_VERSION: "2.8" image: Visual Studio 2013 clone_folder: "c:\\pandoc-crossref" environment: @@ -19,6 +18,7 @@ environment: ARCH: "x64" CHOCO_OPTS: "" matrix: + - PANDOC_VERSION: "2.8" matrix: fast_finish: true From b27a909f8921d7ec6dc2d9d46823dc521f920c7b Mon Sep 17 00:00:00 2001 From: Nikolay Yakimov Date: Sun, 24 Nov 2019 03:08:02 +0300 Subject: [PATCH 099/134] Remove extraneous dependency on extra --- package.yaml | 1 - pandoc-crossref.cabal | 6 +----- 2 files changed, 1 insertion(+), 6 deletions(-) diff --git a/package.yaml b/package.yaml index 857df785..95a1dfe3 100644 --- a/package.yaml +++ b/package.yaml @@ -32,7 +32,6 @@ dependencies: - directory >=1 && <1.4 - filepath >=1.1 && <1.5 - text >=1.2.2 && <1.3 -- extra >= 1.6 && <1.7 library: source-dirs: lib ghc-options: -Wall diff --git a/pandoc-crossref.cabal b/pandoc-crossref.cabal index cdba6b12..669162a6 100644 --- a/pandoc-crossref.cabal +++ b/pandoc-crossref.cabal @@ -4,7 +4,7 @@ cabal-version: 1.12 -- -- see: https://github.com/sol/hpack -- --- hash: a0fa3be4220203fe0ffae15f44dd0df4c949beaa4d4c8feca9e2d1032b63431e +-- hash: 8b64baf60291a34afcbb3a1d8d890e2bf27578bd1808f86e9d3a352d827773ce name: pandoc-crossref version: 0.4.0.0 @@ -117,7 +117,6 @@ library , data-accessor-template >=0.2.1.12 && <0.3.0.0 , data-default >=0.4 && <0.8 , directory >=1 && <1.4 - , extra >=1.6 && <1.7 , filepath >=1.1 && <1.5 , mtl >=1.1 && <2.3 , pandoc >=2.8 && <2.9 @@ -145,7 +144,6 @@ executable pandoc-crossref , data-default >=0.4 && <0.8 , deepseq >=1.4 && <1.5 , directory >=1 && <1.4 - , extra >=1.6 && <1.7 , filepath >=1.1 && <1.5 , gitrev >=1.3.1 && <1.4 , mtl >=1.1 && <2.3 @@ -175,7 +173,6 @@ test-suite test-integrative , data-accessor-template >=0.2.1.12 && <0.3.0.0 , data-default >=0.4 && <0.8 , directory >=1 && <1.4 - , extra >=1.6 && <1.7 , filepath >=1.1 && <1.5 , hspec >=2.4.4 && <3 , mtl >=1.1 && <2.3 @@ -234,7 +231,6 @@ test-suite test-pandoc-crossref , data-accessor-template >=0.2.1.12 && <0.3.0.0 , data-default >=0.4 && <0.8 , directory >=1 && <1.4 - , extra >=1.6 && <1.7 , filepath >=1.1 && <1.5 , hspec >=2.4.4 && <3 , mtl >=1.1 && <2.3 From 95c2037a111e0d343566afa72b8f4c9734f989f5 Mon Sep 17 00:00:00 2001 From: Nikolay Yakimov Date: Sun, 24 Nov 2019 03:11:46 +0300 Subject: [PATCH 100/134] Fix unnumbered headings --- lib/Text/Pandoc/CrossRef/References/Blocks.hs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/Text/Pandoc/CrossRef/References/Blocks.hs b/lib/Text/Pandoc/CrossRef/References/Blocks.hs index 4a874128..589d2258 100644 --- a/lib/Text/Pandoc/CrossRef/References/Blocks.hs +++ b/lib/Text/Pandoc/CrossRef/References/Blocks.hs @@ -75,7 +75,7 @@ replaceBlock opts scope (Div (ident, "section":cls, attr) (Header lvl (hident, h | T.null hident = (newlabel, hident) | otherwise = (ident, newlabel) result title = Div (newident, "section":cls, attr) (Header lvl (newhident, hcls, hattr) title : body) - in if "unnumbered" `elem` cls + in if "unnumbered" `elem` hcls then replaceRecurse scope $ result text' else do let ititle = B.fromList text' From 31ee6e8ae27e6c7d06ec5a4df1d86b2e6f120ffd Mon Sep 17 00:00:00 2001 From: Nikolay Yakimov Date: Sun, 24 Nov 2019 03:16:33 +0300 Subject: [PATCH 101/134] Remove redundant import --- lib/Text/Pandoc/CrossRef/Util/Template.hs | 1 - 1 file changed, 1 deletion(-) diff --git a/lib/Text/Pandoc/CrossRef/Util/Template.hs b/lib/Text/Pandoc/CrossRef/Util/Template.hs index bb263b7d..619a292f 100644 --- a/lib/Text/Pandoc/CrossRef/Util/Template.hs +++ b/lib/Text/Pandoc/CrossRef/Util/Template.hs @@ -37,7 +37,6 @@ import Text.Pandoc.Generic import Text.Pandoc.CrossRef.Util.Meta import Text.Pandoc.CrossRef.Util.Template.Types import Control.Applicative hiding (many, optional) -import Text.Read hiding ((<++), (+++)) import Data.Char (isAlphaNum, isUpper, toLower, isDigit) import Control.Monad ((<=<)) import Data.Data (Data) From cd8d9743eaf27b0d3197989310e8da2e5bdc9c6b Mon Sep 17 00:00:00 2001 From: Nikolay Yakimov Date: Sun, 24 Nov 2019 12:54:22 +0300 Subject: [PATCH 102/134] Add GitHub CI builds for macos and windows [ci skip] --- .github/workflows/haskell.yml | 94 +++++++++++++++++++++++++++++++---- 1 file changed, 85 insertions(+), 9 deletions(-) diff --git a/.github/workflows/haskell.yml b/.github/workflows/haskell.yml index 04499a6e..30f9f867 100644 --- a/.github/workflows/haskell.yml +++ b/.github/workflows/haskell.yml @@ -3,31 +3,107 @@ name: Haskell CI on: [push] jobs: - build: - + linux: runs-on: ubuntu-latest container: - image: lierdakil/pandoc-crossref-build:latest - + image: lierdakil/pandoc-crossref-build:b5789c3d3b0e6286d5b7d08d30981680043d0bc4 + strategy: + matrix: + pandocver: ["2.8"] steps: - uses: actions/checkout@v1 - name: Copy build config from image run: | cp -r /root/.cabal "$HOME" cp /root/cabal.project.local ./ + - name: Build + run: cabal v2-build --constraint pandoc==${{matrix.pandocver}} + - name: Run tests + run: cabal v2-test --constraint pandoc==${{matrix.pandocver}} + - name: Find artifact + run: find dist-newstyle -type f -perm +100 -name pandoc-crossref -exec cp {} ./ \; + - name: Package artifact + run: xz pandoc-crossref + - uses: actions/upload-artifact@v1 + with: + name: pandoc-crossref-${{ runner.os }}-${{matrix.pandocver}}.xz + path: ./pandoc-crossref.xz + + macos: + runs-on: macos-latest + strategy: + matrix: + pandocver: ["2.8"] + steps: + - uses: actions/checkout@v1 + - name: Setup GHC + run: | + brew bundle --file=osx/Brewfile + - uses: actions/cache@v1 + id: cache + with: + path: .cabal-store + key: ${{ runner.os }}-${{matrix.pandocver}}-${{ hashFiles('pandoc-crossref.cabal') }} - name: Install dependencies + if: steps.cache.outputs.cache-hit != 'true' run: | - cabal v2-update - cabal v2-build --only-dependencies --enable-tests + export PATH="/usr/local/opt/ghc@8.6/bin:$PATH" + cabal --store-dir=".cabal-store" v2-update + cabal --store-dir=".cabal-store" v2-build --only-dependencies --enable-tests - name: Build - run: cabal v2-build + run: | + export PATH="/usr/local/opt/ghc@8.6/bin:$PATH" + cabal --store-dir=".cabal-store" v2-build - name: Run tests - run: cabal v2-test + run: | + export PATH="/usr/local/opt/ghc@8.6/bin:$PATH" + cabal --store-dir=".cabal-store" v2-test - name: Find artifact + shell: bash run: find dist-newstyle -type f -perm +100 -name pandoc-crossref -exec cp {} ./ \; - name: Package artifact + shell: bash run: xz pandoc-crossref - uses: actions/upload-artifact@v1 with: - name: pandoc-crossref.xz + name: pandoc-crossref-${{ runner.os }}-${{matrix.pandocver}}.xz path: ./pandoc-crossref.xz + + windows: + runs-on: windows-latest + strategy: + matrix: + pandocver: ["2.8"] + cabalver: ["3.0"] + ghcver: ["8.6.5"] + env: + GHC: "C:\\ProgramData\\chocolatey\\lib\\ghc\\tools\\ghc-${{matrix.ghcver}}\\bin\\ghc.exe" + steps: + - uses: actions/checkout@v1 + - name: Setup GHC + run: | + choco install ghc --version ${{matrix.ghcver}} --ignore-dependencies + choco install cabal --version ${{matrix.cabalver}} --ignore-dependencies + - uses: actions/cache@v1 + id: cache + with: + path: .cabal-store + key: ${{ runner.os }}-${{matrix.pandocver}}-${{ hashFiles('pandoc-crossref.cabal') }} + - name: Install dependencies + if: steps.cache.outputs.cache-hit != 'true' + run: | + cabal --store-dir=".cabal-store" v2-update + cabal --store-dir=".cabal-store" v2-build -w "$Env:ghc" --only-dependencies --enable-tests + - name: Build + run: cabal --store-dir=".cabal-store" v2-build -w "$Env:ghc" + - name: Run tests + run: cabal --store-dir=".cabal-store" v2-test -w "$Env:ghc" + - name: Find artifact + shell: bash + run: find dist-newstyle -type f -name pandoc-crossref.exe -exec cp {} ./ \; + - name: Package artifact + run: 7z a "pandoc-crossref.zip" pandoc-crossref.exe + - uses: actions/upload-artifact@v1 + with: + name: pandoc-crossref-${{ runner.os }}-${{matrix.pandocver}}.zip + path: ./pandoc-crossref.zip From 4b434947646c51bc59fe08619c10be2aa136d47c Mon Sep 17 00:00:00 2001 From: Nikolay Yakimov Date: Sun, 24 Nov 2019 17:41:31 +0300 Subject: [PATCH 103/134] Disable other CI for now --- .gitlab-ci.yml | 54 -------------------------------------- .travis.yml | 57 ---------------------------------------- appveyor.yml | 70 -------------------------------------------------- 3 files changed, 181 deletions(-) delete mode 100644 .gitlab-ci.yml delete mode 100644 .travis.yml delete mode 100644 appveyor.yml diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml deleted file mode 100644 index 35170a56..00000000 --- a/.gitlab-ci.yml +++ /dev/null @@ -1,54 +0,0 @@ -variables: - STACK_ROOT: $CI_PROJECT_DIR/.stack - -cache: - key: "$CI_BUILD_NAME/$CI_BUILD_REF_NAME" - paths: - - .stack/ - - .stack-work/ - - .cabal-sandbox/ - -stages: - - build - -.job_template: &common_script - script: - - stack upgrade - - stack $RESOLVER build $GHCVERSION - - stack $RESOLVER test $GHCVERSION - -.job_template_cabal: &cabal_script - script: - - cabal update - - cabal sandbox init - - cabal install --only-dependencies --enable-tests - - cabal configure --enable-tests - - cabal build - - cabal test - -job-saved-lts: - image: haskell:8.0.2 - stage: build - variables: - STACK_YAML: stack.yaml - GHCVERSION: --system-ghc - <<: *common_script - -job-current-lts: - image: haskell:8.0.2 - stage: build - variables: - STACK_YAML: stack.yaml - RESOLVER: --resolver lts - GHCVERSION: --system-ghc - <<: *common_script - -job-hackage-ghc802: - image: haskell:8.0.2 - stage: build - <<: *cabal_script - -job-hackage-ghc82x: - image: haskell:8.2 - stage: build - <<: *cabal_script diff --git a/.travis.yml b/.travis.yml deleted file mode 100644 index 0b3b8b72..00000000 --- a/.travis.yml +++ /dev/null @@ -1,57 +0,0 @@ -language: c -sudo: true -osx_image: xcode10.2 - -cache: - directories: - - $HOME/.cabal/ - - $HOME/.ghc/ - -addons: - homebrew: - brewfile: osx/Brewfile - -env: - global: - - RUN_UPX: yes - - DOCKER_IMAGE_VERSION: b5789c3d3b0e6286d5b7d08d30981680043d0bc4 - - PANDOC_VERSION: "2.8" - - CABAL_OPTS="--constraint pandoc==$PANDOC_VERSION" - -services: - - docker - -os: - - linux - - osx - -script: -- export -f travis_retry -# Output something every 9 minutes (540 seconds) or Travis kills the job -- while sleep 540; do echo "=====[ $SECONDS seconds still running ]====="; done & -- "${TRAVIS_OS_NAME}/build.sh" -# Kill the sleep loop -- kill %1 -# Print built version string -- ./pandoc-crossref -v -- mkdir "$TRAVIS_BUILD_DIR/upload" -- RELEASE_FN=( *-pandoc_*.tar.gz ) -- cp "$TRAVIS_BUILD_DIR/$RELEASE_FN" "$TRAVIS_BUILD_DIR/upload/build-$(date -u +%FT%T)-$TRAVIS_BRANCH-$(git rev-parse --short HEAD)-$RELEASE_FN" -deploy: - - provider: releases - api_key: - secure: HgG0wburBoUnULjqK3I86k9ZNVLks4/WXPicd7rn2z8HbFpFv/QVN6882hYbsWQd3xhe+Q+hTfXMSL2lbZpiEKAB3UgQclJMP84A42DyvS6RE5a+kwl/wVVNXQh4sNlzuApTSzjYZZkYvroyakqsucCRg7u56eN4NM2VvrDUuJw= - file: $TRAVIS_BUILD_DIR/*-pandoc_*.tar.gz - file_glob: true - skip_cleanup: true - overwrite: true - on: - tags: true - - provider: bintray - file: "bintray.json" - user: "lierdakil" - key: - secure: "bGGfZk2d/IJr7wYrkIkQVJhp+UIA8q6hsn8vmVbLUt3p919mW/bQXDy+tmSBQo3wn/CUsjlWhxNebiR3+PZcWc5NG4jCV/r5sqfVrOupfqMGJ55RN5sbftToSDK5X0mwxhQzU/G4bRF6aZztfN5qWU9lESdUe0UtjJ0n8DW9+uA=" - skip_cleanup: true - on: - all_branches: true diff --git a/appveyor.yml b/appveyor.yml deleted file mode 100644 index cf59afe9..00000000 --- a/appveyor.yml +++ /dev/null @@ -1,70 +0,0 @@ -image: Visual Studio 2013 -clone_folder: "c:\\pandoc-crossref" -environment: - global: - CABAL_STORE: "C:\\cs" - CABAL_PACKAGE_DB: "%CABAL_STORE%\\ghc-%GHC_MINOR_VERSION%\\package.db" - # Override the temp directory to avoid sed escaping issues - # See https://github.com/haskell/cabal/issues/5386 - TMP: "c:\\tmp" - # see #4201, https://github.com/haskell-tools/haskell-tools/issues/277 - OSARCH: "windows-x86_64" - GHC_VERSION: "8.6.5" - GHC_MINOR_VERSION: "8.6.5" - GHC: "C:\\ProgramData\\chocolatey\\lib\\ghc\\tools\\ghc-%GHC_MINOR_VERSION%\\bin\\ghc.exe" - CABAL_VERSION: "2.4.1.0" - CABAL_OPTS: "--constraint pandoc==%PANDOC_VERSION% --enable-executable-stripping --enable-split-sections" - GHC_OPTS: "" - ARCH: "x64" - CHOCO_OPTS: "" - matrix: - - PANDOC_VERSION: "2.8" - -matrix: - fast_finish: true - -cache: - - '%CABAL_STORE%' - -# Note: to reset build cache, do the following in JavaScript -# console on appveyor: -# $.ajax({ url: 'https://ci.appveyor.com/api/projects/jgm/pandoc/buildcache', type: 'DELETE'}) - -# We don't do a normal C build, but build in test_script -build: off - -install: - - choco install ghc --version %GHC_VERSION% --ignore-dependencies %CHOCO_OPTS% - - choco install cabal --version %CABAL_VERSION% --ignore-dependencies %CHOCO_OPTS% - -# before_test: - -test_script: - - echo %CABAL_OPTS% - # Note: we manually create cabal store, because of a cabal bug: - # see https://github.com/haskell/cabal/issues/5516 - - if not exist "%CABAL_PACKAGE_DB%" ( mkdir "%CABAL_PACKAGE_DB%" ) - - cabal --store-dir="%CABAL_STORE%" --version - - cabal --store-dir="%CABAL_STORE%" new-update - - cabal --store-dir="%CABAL_STORE%" new-build -w %GHC% %CABAL_OPTS% --ghc-options="%GHC_OPTS%" . - - forfiles /P .\dist-newstyle /M pandoc-crossref.exe /S /C "cmd /C copy @path C:\pandoc-crossref" - -after_test: - # print built version string - - .\pandoc-crossref.exe -v - # create zip artifacts - - 7z a "%OSARCH%-pandoc_%PANDOC_VERSION%.zip" pandoc-crossref.exe - -artifacts: - - path: '%OSARCH%-pandoc_%PANDOC_VERSION%.zip' - name: exe - -deploy: - description: 'Description' - provider: GitHub - auth_token: - secure: mYPFGSbgJZ0H2bp6I9vMWvJdgVNUKplWpiPCV3W4sbUwte0jRK56L/8Rts6trCQ7 - artifact: /.*/ - draft: true - on: - appveyor_repo_tag: true # deploy on tag push only From 6db814268c3a1693285a713ea2efd4b750aff9e7 Mon Sep 17 00:00:00 2001 From: Nikolay Yakimov Date: Sun, 24 Nov 2019 17:47:18 +0300 Subject: [PATCH 104/134] Always run cabal update --- .github/workflows/haskell.yml | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/.github/workflows/haskell.yml b/.github/workflows/haskell.yml index 30f9f867..1b654f88 100644 --- a/.github/workflows/haskell.yml +++ b/.github/workflows/haskell.yml @@ -44,11 +44,14 @@ jobs: with: path: .cabal-store key: ${{ runner.os }}-${{matrix.pandocver}}-${{ hashFiles('pandoc-crossref.cabal') }} + - name: Cabal update + run: | + export PATH="/usr/local/opt/ghc@8.6/bin:$PATH" + cabal --store-dir=".cabal-store" v2-update - name: Install dependencies if: steps.cache.outputs.cache-hit != 'true' run: | export PATH="/usr/local/opt/ghc@8.6/bin:$PATH" - cabal --store-dir=".cabal-store" v2-update cabal --store-dir=".cabal-store" v2-build --only-dependencies --enable-tests - name: Build run: | @@ -89,10 +92,12 @@ jobs: with: path: .cabal-store key: ${{ runner.os }}-${{matrix.pandocver}}-${{ hashFiles('pandoc-crossref.cabal') }} + - name: Cabal update + run: | + cabal --store-dir=".cabal-store" v2-update - name: Install dependencies if: steps.cache.outputs.cache-hit != 'true' run: | - cabal --store-dir=".cabal-store" v2-update cabal --store-dir=".cabal-store" v2-build -w "$Env:ghc" --only-dependencies --enable-tests - name: Build run: cabal --store-dir=".cabal-store" v2-build -w "$Env:ghc" From 070d47dbcc77828a854da9f61063def57be68652 Mon Sep 17 00:00:00 2001 From: Nikolay Yakimov Date: Mon, 25 Nov 2019 12:46:12 +0300 Subject: [PATCH 105/134] Add make release workflow --- .github/workflows/release.yml | 166 ++++++++++++++++++++++++++++++++++ 1 file changed, 166 insertions(+) create mode 100644 .github/workflows/release.yml diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 00000000..9e40e176 --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,166 @@ +on: + push: + tags: + - 'v*' + +name: Make Release + +jobs: + linux: + runs-on: ubuntu-latest + container: + image: lierdakil/pandoc-crossref-build:b5789c3d3b0e6286d5b7d08d30981680043d0bc4 + strategy: + matrix: + pandocver: ["2.8"] + steps: + - uses: actions/checkout@v1 + - name: Copy build config from image + run: | + cp -r /root/.cabal "$HOME" + cp /root/cabal.project.local ./ + - name: Build + run: cabal v2-build --constraint pandoc==${{matrix.pandocver}} + - name: Run tests + run: cabal v2-test --constraint pandoc==${{matrix.pandocver}} + - name: Find artifact + run: find dist-newstyle -type f -perm +100 -name pandoc-crossref -exec cp {} ./ \; + - name: Package artifact + run: xz pandoc-crossref + - name: Create Release + id: create_release + uses: actions/create-release@v1.0.0 + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + with: + tag_name: ${{ github.ref }} + release_name: ${{ github.ref }} + draft: false + prerelease: true + - name: Upload Release Asset + id: upload-release-asset + uses: actions/upload-release-asset@v1.0.1 + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + with: + upload_url: ${{ steps.create_release.outputs.upload_url }} + asset_path: ./pandoc-crossref.xz + asset_name: pandoc-crossref-${{ runner.os }}-${{matrix.pandocver}}.xz + asset_content_type: application/x-xz + + macos: + runs-on: macos-latest + strategy: + matrix: + pandocver: ["2.8"] + steps: + - uses: actions/checkout@v1 + - name: Setup GHC + run: | + brew bundle --file=osx/Brewfile + - uses: actions/cache@v1 + id: cache + with: + path: .cabal-store + key: ${{ runner.os }}-${{matrix.pandocver}}-${{ hashFiles('pandoc-crossref.cabal') }} + - name: Cabal update + run: | + export PATH="/usr/local/opt/ghc@8.6/bin:$PATH" + cabal --store-dir=".cabal-store" v2-update + - name: Install dependencies + if: steps.cache.outputs.cache-hit != 'true' + run: | + export PATH="/usr/local/opt/ghc@8.6/bin:$PATH" + cabal --store-dir=".cabal-store" v2-build --only-dependencies --enable-tests + - name: Build + run: | + export PATH="/usr/local/opt/ghc@8.6/bin:$PATH" + cabal --store-dir=".cabal-store" v2-build + - name: Run tests + run: | + export PATH="/usr/local/opt/ghc@8.6/bin:$PATH" + cabal --store-dir=".cabal-store" v2-test + - name: Find artifact + shell: bash + run: find dist-newstyle -type f -perm +100 -name pandoc-crossref -exec cp {} ./ \; + - name: Package artifact + shell: bash + run: xz pandoc-crossref + - name: Create Release + id: create_release + uses: actions/create-release@v1.0.0 + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + with: + tag_name: ${{ github.ref }} + release_name: ${{ github.ref }} + draft: false + prerelease: true + - name: Upload Release Asset + id: upload-release-asset + uses: actions/upload-release-asset@v1.0.1 + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + with: + upload_url: ${{ steps.create_release.outputs.upload_url }} + asset_path: ./pandoc-crossref.xz + asset_name: pandoc-crossref-${{ runner.os }}-${{matrix.pandocver}}.xz + asset_content_type: application/x-xz + + + windows: + runs-on: windows-latest + strategy: + matrix: + pandocver: ["2.8"] + cabalver: ["3.0"] + ghcver: ["8.6.5"] + env: + GHC: "C:\\ProgramData\\chocolatey\\lib\\ghc\\tools\\ghc-${{matrix.ghcver}}\\bin\\ghc.exe" + steps: + - uses: actions/checkout@v1 + - name: Setup GHC + run: | + choco install ghc --version ${{matrix.ghcver}} --ignore-dependencies + choco install cabal --version ${{matrix.cabalver}} --ignore-dependencies + - uses: actions/cache@v1 + id: cache + with: + path: .cabal-store + key: ${{ runner.os }}-${{matrix.pandocver}}-${{ hashFiles('pandoc-crossref.cabal') }} + - name: Cabal update + run: | + cabal --store-dir=".cabal-store" v2-update + - name: Install dependencies + if: steps.cache.outputs.cache-hit != 'true' + run: | + cabal --store-dir=".cabal-store" v2-build -w "$Env:ghc" --only-dependencies --enable-tests + - name: Build + run: cabal --store-dir=".cabal-store" v2-build -w "$Env:ghc" + - name: Run tests + run: cabal --store-dir=".cabal-store" v2-test -w "$Env:ghc" + - name: Find artifact + shell: bash + run: find dist-newstyle -type f -name pandoc-crossref.exe -exec cp {} ./ \; + - name: Package artifact + run: 7z a "pandoc-crossref.zip" pandoc-crossref.exe + - name: Create Release + id: create_release + uses: actions/create-release@v1.0.0 + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + with: + tag_name: ${{ github.ref }} + release_name: ${{ github.ref }} + draft: false + prerelease: true + - name: Upload Release Asset + id: upload-release-asset + uses: actions/upload-release-asset@v1.0.1 + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + with: + upload_url: ${{ steps.create_release.outputs.upload_url }} + asset_path: ./pandoc-crossref.zip + asset_name: pandoc-crossref-${{ runner.os }}-${{matrix.pandocver}}.zip + asset_content_type: application/zip From 9f00ac35790305450c5d6016b88bcefcbeebd4b6 Mon Sep 17 00:00:00 2001 From: Nikolay Yakimov Date: Mon, 25 Nov 2019 15:24:19 +0300 Subject: [PATCH 106/134] Fix release --- .github/workflows/haskell.yml | 60 ++++++++++++ .github/workflows/release.yml | 166 ---------------------------------- 2 files changed, 60 insertions(+), 166 deletions(-) delete mode 100644 .github/workflows/release.yml diff --git a/.github/workflows/haskell.yml b/.github/workflows/haskell.yml index 1b654f88..4e0a1e56 100644 --- a/.github/workflows/haskell.yml +++ b/.github/workflows/haskell.yml @@ -21,8 +21,10 @@ jobs: - name: Run tests run: cabal v2-test --constraint pandoc==${{matrix.pandocver}} - name: Find artifact + shell: bash run: find dist-newstyle -type f -perm +100 -name pandoc-crossref -exec cp {} ./ \; - name: Package artifact + shell: bash run: xz pandoc-crossref - uses: actions/upload-artifact@v1 with: @@ -112,3 +114,61 @@ jobs: with: name: pandoc-crossref-${{ runner.os }}-${{matrix.pandocver}}.zip path: ./pandoc-crossref.zip + + release: + if: contains(github.ref, 'tags/v') + needs: [linux, windows, macos] + runs-on: ubuntu-latest + strategy: + matrix: + pandocver: ["2.8"] + steps: + - uses: actions/download-artifact@v1 + with: + name: pandoc-crossref-Linux-${{matrix.pandocver}}.xz + path: ./pandoc-crossref-Linux-${{matrix.pandocver}}.xz + - uses: actions/download-artifact@v1 + with: + name: pandoc-crossref-macOS-${{matrix.pandocver}}.xz + path: ./pandoc-crossref-macOS-${{matrix.pandocver}}.xz + - uses: actions/download-artifact@v1 + with: + name: pandoc-crossref-Windows-${{matrix.pandocver}}.zip + path: ./pandoc-crossref-Windows-${{matrix.pandocver}}.zip + - name: Create Release + id: create_release + uses: actions/create-release@v1.0.0 + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + with: + tag_name: ${{ github.ref }} + release_name: ${{ github.ref }} + draft: false + prerelease: true + - name: Upload Release Asset Linux + uses: actions/upload-release-asset@v1.0.1 + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + with: + upload_url: ${{ steps.create_release.outputs.upload_url }} + asset_path: ./pandoc-crossref-Linux-${{matrix.pandocver}}.xz + asset_name: pandoc-crossref-Linux-${{matrix.pandocver}}.xz + asset_content_type: application/x-xz + - name: Upload Release Asset macOS + uses: actions/upload-release-asset@v1.0.1 + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + with: + upload_url: ${{ steps.create_release.outputs.upload_url }} + asset_path: ./pandoc-crossref-macOS-${{matrix.pandocver}}.xz + asset_name: pandoc-crossref-macOS-${{matrix.pandocver}}.xz + asset_content_type: application/x-xz + - name: Upload Release Asset Windows + uses: actions/upload-release-asset@v1.0.1 + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + with: + upload_url: ${{ steps.create_release.outputs.upload_url }} + asset_path: ./pandoc-crossref-Windows-${{matrix.pandocver}}.zip + asset_name: pandoc-crossref-Windows-${{matrix.pandocver}}.zip + asset_content_type: application/zip diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml deleted file mode 100644 index 9e40e176..00000000 --- a/.github/workflows/release.yml +++ /dev/null @@ -1,166 +0,0 @@ -on: - push: - tags: - - 'v*' - -name: Make Release - -jobs: - linux: - runs-on: ubuntu-latest - container: - image: lierdakil/pandoc-crossref-build:b5789c3d3b0e6286d5b7d08d30981680043d0bc4 - strategy: - matrix: - pandocver: ["2.8"] - steps: - - uses: actions/checkout@v1 - - name: Copy build config from image - run: | - cp -r /root/.cabal "$HOME" - cp /root/cabal.project.local ./ - - name: Build - run: cabal v2-build --constraint pandoc==${{matrix.pandocver}} - - name: Run tests - run: cabal v2-test --constraint pandoc==${{matrix.pandocver}} - - name: Find artifact - run: find dist-newstyle -type f -perm +100 -name pandoc-crossref -exec cp {} ./ \; - - name: Package artifact - run: xz pandoc-crossref - - name: Create Release - id: create_release - uses: actions/create-release@v1.0.0 - env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - with: - tag_name: ${{ github.ref }} - release_name: ${{ github.ref }} - draft: false - prerelease: true - - name: Upload Release Asset - id: upload-release-asset - uses: actions/upload-release-asset@v1.0.1 - env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - with: - upload_url: ${{ steps.create_release.outputs.upload_url }} - asset_path: ./pandoc-crossref.xz - asset_name: pandoc-crossref-${{ runner.os }}-${{matrix.pandocver}}.xz - asset_content_type: application/x-xz - - macos: - runs-on: macos-latest - strategy: - matrix: - pandocver: ["2.8"] - steps: - - uses: actions/checkout@v1 - - name: Setup GHC - run: | - brew bundle --file=osx/Brewfile - - uses: actions/cache@v1 - id: cache - with: - path: .cabal-store - key: ${{ runner.os }}-${{matrix.pandocver}}-${{ hashFiles('pandoc-crossref.cabal') }} - - name: Cabal update - run: | - export PATH="/usr/local/opt/ghc@8.6/bin:$PATH" - cabal --store-dir=".cabal-store" v2-update - - name: Install dependencies - if: steps.cache.outputs.cache-hit != 'true' - run: | - export PATH="/usr/local/opt/ghc@8.6/bin:$PATH" - cabal --store-dir=".cabal-store" v2-build --only-dependencies --enable-tests - - name: Build - run: | - export PATH="/usr/local/opt/ghc@8.6/bin:$PATH" - cabal --store-dir=".cabal-store" v2-build - - name: Run tests - run: | - export PATH="/usr/local/opt/ghc@8.6/bin:$PATH" - cabal --store-dir=".cabal-store" v2-test - - name: Find artifact - shell: bash - run: find dist-newstyle -type f -perm +100 -name pandoc-crossref -exec cp {} ./ \; - - name: Package artifact - shell: bash - run: xz pandoc-crossref - - name: Create Release - id: create_release - uses: actions/create-release@v1.0.0 - env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - with: - tag_name: ${{ github.ref }} - release_name: ${{ github.ref }} - draft: false - prerelease: true - - name: Upload Release Asset - id: upload-release-asset - uses: actions/upload-release-asset@v1.0.1 - env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - with: - upload_url: ${{ steps.create_release.outputs.upload_url }} - asset_path: ./pandoc-crossref.xz - asset_name: pandoc-crossref-${{ runner.os }}-${{matrix.pandocver}}.xz - asset_content_type: application/x-xz - - - windows: - runs-on: windows-latest - strategy: - matrix: - pandocver: ["2.8"] - cabalver: ["3.0"] - ghcver: ["8.6.5"] - env: - GHC: "C:\\ProgramData\\chocolatey\\lib\\ghc\\tools\\ghc-${{matrix.ghcver}}\\bin\\ghc.exe" - steps: - - uses: actions/checkout@v1 - - name: Setup GHC - run: | - choco install ghc --version ${{matrix.ghcver}} --ignore-dependencies - choco install cabal --version ${{matrix.cabalver}} --ignore-dependencies - - uses: actions/cache@v1 - id: cache - with: - path: .cabal-store - key: ${{ runner.os }}-${{matrix.pandocver}}-${{ hashFiles('pandoc-crossref.cabal') }} - - name: Cabal update - run: | - cabal --store-dir=".cabal-store" v2-update - - name: Install dependencies - if: steps.cache.outputs.cache-hit != 'true' - run: | - cabal --store-dir=".cabal-store" v2-build -w "$Env:ghc" --only-dependencies --enable-tests - - name: Build - run: cabal --store-dir=".cabal-store" v2-build -w "$Env:ghc" - - name: Run tests - run: cabal --store-dir=".cabal-store" v2-test -w "$Env:ghc" - - name: Find artifact - shell: bash - run: find dist-newstyle -type f -name pandoc-crossref.exe -exec cp {} ./ \; - - name: Package artifact - run: 7z a "pandoc-crossref.zip" pandoc-crossref.exe - - name: Create Release - id: create_release - uses: actions/create-release@v1.0.0 - env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - with: - tag_name: ${{ github.ref }} - release_name: ${{ github.ref }} - draft: false - prerelease: true - - name: Upload Release Asset - id: upload-release-asset - uses: actions/upload-release-asset@v1.0.1 - env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - with: - upload_url: ${{ steps.create_release.outputs.upload_url }} - asset_path: ./pandoc-crossref.zip - asset_name: pandoc-crossref-${{ runner.os }}-${{matrix.pandocver}}.zip - asset_content_type: application/zip From 726c41fb546be3615cfd588fce975c0449df776b Mon Sep 17 00:00:00 2001 From: Nikolay Yakimov Date: Thu, 28 Nov 2019 00:06:54 +0300 Subject: [PATCH 107/134] Bump pandoc version --- .github/workflows/haskell.yml | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/.github/workflows/haskell.yml b/.github/workflows/haskell.yml index 4e0a1e56..7001ff52 100644 --- a/.github/workflows/haskell.yml +++ b/.github/workflows/haskell.yml @@ -6,10 +6,10 @@ jobs: linux: runs-on: ubuntu-latest container: - image: lierdakil/pandoc-crossref-build:b5789c3d3b0e6286d5b7d08d30981680043d0bc4 + image: lierdakil/pandoc-crossref-build:60c6e7bd6cb98968047fe297119f35f0477ba45d strategy: matrix: - pandocver: ["2.8"] + pandocver: ["2.8.0.1"] steps: - uses: actions/checkout@v1 - name: Copy build config from image @@ -35,7 +35,7 @@ jobs: runs-on: macos-latest strategy: matrix: - pandocver: ["2.8"] + pandocver: ["2.8.0.1"] steps: - uses: actions/checkout@v1 - name: Setup GHC @@ -78,7 +78,7 @@ jobs: runs-on: windows-latest strategy: matrix: - pandocver: ["2.8"] + pandocver: ["2.8.0.1"] cabalver: ["3.0"] ghcver: ["8.6.5"] env: @@ -121,7 +121,7 @@ jobs: runs-on: ubuntu-latest strategy: matrix: - pandocver: ["2.8"] + pandocver: ["2.8.0.1"] steps: - uses: actions/download-artifact@v1 with: From cef54809c7d7d626a295fc395a8b9e24d72d7feb Mon Sep 17 00:00:00 2001 From: Nikolay Yakimov Date: Thu, 28 Nov 2019 00:58:48 +0300 Subject: [PATCH 108/134] Fix download-artifact --- .github/workflows/haskell.yml | 3 --- 1 file changed, 3 deletions(-) diff --git a/.github/workflows/haskell.yml b/.github/workflows/haskell.yml index 7001ff52..b6699506 100644 --- a/.github/workflows/haskell.yml +++ b/.github/workflows/haskell.yml @@ -126,15 +126,12 @@ jobs: - uses: actions/download-artifact@v1 with: name: pandoc-crossref-Linux-${{matrix.pandocver}}.xz - path: ./pandoc-crossref-Linux-${{matrix.pandocver}}.xz - uses: actions/download-artifact@v1 with: name: pandoc-crossref-macOS-${{matrix.pandocver}}.xz - path: ./pandoc-crossref-macOS-${{matrix.pandocver}}.xz - uses: actions/download-artifact@v1 with: name: pandoc-crossref-Windows-${{matrix.pandocver}}.zip - path: ./pandoc-crossref-Windows-${{matrix.pandocver}}.zip - name: Create Release id: create_release uses: actions/create-release@v1.0.0 From 13d144e74903c38c02a84dc6c270d1f7843cc230 Mon Sep 17 00:00:00 2001 From: Nikolay Yakimov Date: Fri, 6 Dec 2019 20:16:52 +0300 Subject: [PATCH 109/134] Build for pandoc 2.8.1 --- .github/workflows/haskell.yml | 77 +++++++++++++++++++++++------------ 1 file changed, 52 insertions(+), 25 deletions(-) diff --git a/.github/workflows/haskell.yml b/.github/workflows/haskell.yml index b6699506..28e662b9 100644 --- a/.github/workflows/haskell.yml +++ b/.github/workflows/haskell.yml @@ -6,10 +6,10 @@ jobs: linux: runs-on: ubuntu-latest container: - image: lierdakil/pandoc-crossref-build:60c6e7bd6cb98968047fe297119f35f0477ba45d + image: lierdakil/pandoc-crossref-build:3f80546797a6829e03fd8c78b1bf83b43b549203 strategy: matrix: - pandocver: ["2.8.0.1"] + pandocver: ["2.8.1"] steps: - uses: actions/checkout@v1 - name: Copy build config from image @@ -25,17 +25,20 @@ jobs: run: find dist-newstyle -type f -perm +100 -name pandoc-crossref -exec cp {} ./ \; - name: Package artifact shell: bash - run: xz pandoc-crossref + run: | + xz pandoc-crossref + mkdir pandoc-crossref-linux + mv pandoc-crossref.xz pandoc-crossref-linux - uses: actions/upload-artifact@v1 with: - name: pandoc-crossref-${{ runner.os }}-${{matrix.pandocver}}.xz - path: ./pandoc-crossref.xz + name: linux-build + path: pandoc-crossref-linux macos: runs-on: macos-latest strategy: matrix: - pandocver: ["2.8.0.1"] + pandocver: ["2.8.1"] steps: - uses: actions/checkout@v1 - name: Setup GHC @@ -68,17 +71,20 @@ jobs: run: find dist-newstyle -type f -perm +100 -name pandoc-crossref -exec cp {} ./ \; - name: Package artifact shell: bash - run: xz pandoc-crossref + run: | + xz pandoc-crossref + mkdir pandoc-crossref-macos + mv pandoc-crossref.xz pandoc-crossref-macos - uses: actions/upload-artifact@v1 with: - name: pandoc-crossref-${{ runner.os }}-${{matrix.pandocver}}.xz - path: ./pandoc-crossref.xz + name: macos-build + path: pandoc-crossref-macos windows: runs-on: windows-latest strategy: matrix: - pandocver: ["2.8.0.1"] + pandocver: ["2.8.1"] cabalver: ["3.0"] ghcver: ["8.6.5"] env: @@ -109,11 +115,15 @@ jobs: shell: bash run: find dist-newstyle -type f -name pandoc-crossref.exe -exec cp {} ./ \; - name: Package artifact - run: 7z a "pandoc-crossref.zip" pandoc-crossref.exe + shell: bash + run: | + 7z a "pandoc-crossref.exe.xz" pandoc-crossref.exe + mkdir pandoc-crossref-windows + mv pandoc-crossref.exe.xz pandoc-crossref-windows - uses: actions/upload-artifact@v1 with: - name: pandoc-crossref-${{ runner.os }}-${{matrix.pandocver}}.zip - path: ./pandoc-crossref.zip + name: windows-build + path: ./pandoc-crossref-windows release: if: contains(github.ref, 'tags/v') @@ -121,20 +131,35 @@ jobs: runs-on: ubuntu-latest strategy: matrix: - pandocver: ["2.8.0.1"] + pandocver: ["2.8.1"] steps: - uses: actions/download-artifact@v1 with: - name: pandoc-crossref-Linux-${{matrix.pandocver}}.xz + name: linux-build - uses: actions/download-artifact@v1 with: - name: pandoc-crossref-macOS-${{matrix.pandocver}}.xz + name: macos-build - uses: actions/download-artifact@v1 with: - name: pandoc-crossref-Windows-${{matrix.pandocver}}.zip + name: windows-build + - name: Get Version + id: get_version + run: | + xzcat linux-build/pandoc-crossref.xz > ./pandoc-crossref + chmod +x ./pandoc-crossref + VERSION="$(./pandoc-crossref --version)" + echo ::set-output name=version::"$VERSION" + - name: Repackage assets + run: | + unxz linux-build/pandoc-crossref.xz + unxz macos-build/pandoc-crossref.xz + unxz windows-build/pandoc-crossref.exe.xz + tar cJf linux-build.tar.xz -C linux-build pandoc-crossref + tar cJf macos-build.tar.xz -C macos-build pandoc-crossref + zip -j windows-build.zip windows-build/pandoc-crossref.exe - name: Create Release id: create_release - uses: actions/create-release@v1.0.0 + uses: actions/create-release@v1 env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} with: @@ -142,30 +167,32 @@ jobs: release_name: ${{ github.ref }} draft: false prerelease: true + body: | + ${{ steps.get_version.outputs.version }} - name: Upload Release Asset Linux uses: actions/upload-release-asset@v1.0.1 env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} with: upload_url: ${{ steps.create_release.outputs.upload_url }} - asset_path: ./pandoc-crossref-Linux-${{matrix.pandocver}}.xz - asset_name: pandoc-crossref-Linux-${{matrix.pandocver}}.xz - asset_content_type: application/x-xz + asset_path: ./linux-build.tar.xz + asset_name: pandoc-crossref-Linux-${{matrix.pandocver}}.tar.xz + asset_content_type: application/x-xz-compressed-tar - name: Upload Release Asset macOS uses: actions/upload-release-asset@v1.0.1 env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} with: upload_url: ${{ steps.create_release.outputs.upload_url }} - asset_path: ./pandoc-crossref-macOS-${{matrix.pandocver}}.xz - asset_name: pandoc-crossref-macOS-${{matrix.pandocver}}.xz - asset_content_type: application/x-xz + asset_path: ./macos-build.tar.xz + asset_name: pandoc-crossref-macOS-${{matrix.pandocver}}.tar.xz + asset_content_type: application/x-xz-compressed-tar - name: Upload Release Asset Windows uses: actions/upload-release-asset@v1.0.1 env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} with: upload_url: ${{ steps.create_release.outputs.upload_url }} - asset_path: ./pandoc-crossref-Windows-${{matrix.pandocver}}.zip + asset_path: ./windows-build.zip asset_name: pandoc-crossref-Windows-${{matrix.pandocver}}.zip asset_content_type: application/zip From 903e59a35acda288e3ec6d69da1dbbaae1f496c5 Mon Sep 17 00:00:00 2001 From: Nikolay Yakimov Date: Thu, 12 Dec 2019 13:44:45 +0300 Subject: [PATCH 110/134] Bump version constraints --- package.yaml | 2 +- pandoc-crossref.cabal | 10 +++++----- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/package.yaml b/package.yaml index 95a1dfe3..25739164 100644 --- a/package.yaml +++ b/package.yaml @@ -18,7 +18,7 @@ data-files: - test/m2m/*/* dependencies: - base >=4.11 && <5 -- pandoc >=2.8 && < 2.9 +- pandoc >=2.9 && < 2.10 - pandoc-types >=1.20 && < 1.21 - mtl >=1.1 && <2.3 - containers >=0.1 && <0.7 diff --git a/pandoc-crossref.cabal b/pandoc-crossref.cabal index 669162a6..0f49a746 100644 --- a/pandoc-crossref.cabal +++ b/pandoc-crossref.cabal @@ -4,7 +4,7 @@ cabal-version: 1.12 -- -- see: https://github.com/sol/hpack -- --- hash: 8b64baf60291a34afcbb3a1d8d890e2bf27578bd1808f86e9d3a352d827773ce +-- hash: e597582e02f2e6e9aaef63cf79bb014f5f2d595ae7da852d08ecc34f14067f35 name: pandoc-crossref version: 0.4.0.0 @@ -119,7 +119,7 @@ library , directory >=1 && <1.4 , filepath >=1.1 && <1.5 , mtl >=1.1 && <2.3 - , pandoc >=2.8 && <2.9 + , pandoc >=2.9 && <2.10 , pandoc-types >=1.20 && <1.21 , roman-numerals ==0.5.* , syb >=0.4 && <0.8 @@ -149,7 +149,7 @@ executable pandoc-crossref , mtl >=1.1 && <2.3 , open-browser >=0.2 && <0.3 , optparse-applicative >=0.13 && <0.16 - , pandoc >=2.8 && <2.9 + , pandoc >=2.9 && <2.10 , pandoc-crossref , pandoc-types >=1.20 && <1.21 , roman-numerals ==0.5.* @@ -176,7 +176,7 @@ test-suite test-integrative , filepath >=1.1 && <1.5 , hspec >=2.4.4 && <3 , mtl >=1.1 && <2.3 - , pandoc >=2.8 && <2.9 + , pandoc >=2.9 && <2.10 , pandoc-crossref , pandoc-types >=1.20 && <1.21 , roman-numerals ==0.5.* @@ -234,7 +234,7 @@ test-suite test-pandoc-crossref , filepath >=1.1 && <1.5 , hspec >=2.4.4 && <3 , mtl >=1.1 && <2.3 - , pandoc >=2.8 && <2.9 + , pandoc >=2.9 && <2.10 , pandoc-types >=1.20 && <1.21 , roman-numerals ==0.5.* , syb >=0.4 && <0.8 From 371ddbd132562e36dde65e240df5afd7705f6f2f Mon Sep 17 00:00:00 2001 From: Nikolay Yakimov Date: Thu, 12 Dec 2019 13:24:42 +0300 Subject: [PATCH 111/134] Fix ManData --- src/ManData.hs | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/src/ManData.hs b/src/ManData.hs index 0737e6f1..112f81a5 100644 --- a/src/ManData.hs +++ b/src/ManData.hs @@ -25,7 +25,6 @@ import Language.Haskell.TH.Syntax import qualified Data.Text as T import System.IO import qualified Text.Pandoc as P -import qualified Text.Pandoc.Templates as PT import Control.DeepSeq import Data.String import Text.Pandoc.Highlighting (pygments) @@ -60,8 +59,7 @@ embedManualText = embedManual $ P.writePlain P.def embedManualHtml :: Q Exp embedManualHtml = do tt <- fmap (either (error . show) id) . runIO . P.runIO - $ P.getDefaultTemplate "html5" - >>= fmap (either (error . show) id) . PT.compileTemplate "" + $ P.compileDefaultTemplate "html5" embedManual $ P.writeHtml5String P.def{ P.writerTemplate = Just tt , P.writerHighlightStyle = Just pygments From a22c55dff3ec40c17afbea16200cfe7ed311c602 Mon Sep 17 00:00:00 2001 From: Nikolay Yakimov Date: Thu, 12 Dec 2019 13:47:43 +0300 Subject: [PATCH 112/134] [CI] Update pandoc version --- .github/workflows/haskell.yml | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/.github/workflows/haskell.yml b/.github/workflows/haskell.yml index 28e662b9..4ff1cd0a 100644 --- a/.github/workflows/haskell.yml +++ b/.github/workflows/haskell.yml @@ -6,10 +6,10 @@ jobs: linux: runs-on: ubuntu-latest container: - image: lierdakil/pandoc-crossref-build:3f80546797a6829e03fd8c78b1bf83b43b549203 + image: lierdakil/pandoc-crossref-build:2e439295a861055d29b0e8f7bc344e609728830d strategy: matrix: - pandocver: ["2.8.1"] + pandocver: ["2.9"] steps: - uses: actions/checkout@v1 - name: Copy build config from image @@ -38,7 +38,7 @@ jobs: runs-on: macos-latest strategy: matrix: - pandocver: ["2.8.1"] + pandocver: ["2.9"] steps: - uses: actions/checkout@v1 - name: Setup GHC @@ -84,7 +84,7 @@ jobs: runs-on: windows-latest strategy: matrix: - pandocver: ["2.8.1"] + pandocver: ["2.9"] cabalver: ["3.0"] ghcver: ["8.6.5"] env: @@ -131,7 +131,7 @@ jobs: runs-on: ubuntu-latest strategy: matrix: - pandocver: ["2.8.1"] + pandocver: ["2.9"] steps: - uses: actions/download-artifact@v1 with: From 0d0dca23de0ed96bbeefacf4bb16527b621a2c74 Mon Sep 17 00:00:00 2001 From: Nikolay Yakimov Date: Sat, 14 Dec 2019 10:05:33 +0300 Subject: [PATCH 113/134] Update unhierarchicalize to pandoc 2.9 --- lib/Text/Pandoc/CrossRef/Util/Util.hs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/Text/Pandoc/CrossRef/Util/Util.hs b/lib/Text/Pandoc/CrossRef/Util/Util.hs index 1112619a..6470d77e 100644 --- a/lib/Text/Pandoc/CrossRef/Util/Util.hs +++ b/lib/Text/Pandoc/CrossRef/Util/Util.hs @@ -87,7 +87,7 @@ safeHead x = Just $ head x unhierarchicalize :: [Block] -> [Block] unhierarchicalize (Div (dident, "section":dcls, dkvs) (Header level (hident,hcls,hkvs) ils : xs) : ys) - | T.null hident, null dkvs, null dcls = Header level (dident, hcls, hkvs) ils : unhierarchicalize xs <> unhierarchicalize ys + | T.null hident, dkvs == hkvs, dcls == hcls = Header level (dident, hcls, hkvs) ils : unhierarchicalize xs <> unhierarchicalize ys unhierarchicalize (x:xs) = x : unhierarchicalize xs unhierarchicalize [] = [] From a9126a9c208053c33e2fd1977646936ea0ad7707 Mon Sep 17 00:00:00 2001 From: Nikolay Yakimov Date: Sun, 8 Mar 2020 17:27:55 +0300 Subject: [PATCH 114/134] Readme badge branch --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index f4dea6a9..13e8d0a8 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# pandoc-crossref filter ![Build status](https://github.com/lierdakil/pandoc-crossref/workflows/Haskell%20CI/badge.svg) +# pandoc-crossref filter ![Build status](https://github.com/lierdakil/pandoc-crossref/workflows/Haskell%20CI/badge.svg?branch=any-prefix) pandoc-crossref is a pandoc filter for numbering figures, equations, tables and cross-references to them. From abaa1dab65f586c2d82b716b6c56a950e03bb06d Mon Sep 17 00:00:00 2001 From: Nikolay Yakimov Date: Sun, 8 Mar 2020 18:10:13 +0300 Subject: [PATCH 115/134] [CI][Bintray] add commit sha to filenames --- .github/workflows/haskell.yml | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/.github/workflows/haskell.yml b/.github/workflows/haskell.yml index b656e1ac..bd6e7214 100644 --- a/.github/workflows/haskell.yml +++ b/.github/workflows/haskell.yml @@ -156,9 +156,9 @@ jobs: - name: Repack assets run: | mkdir assets - tar cJf assets/pandoc-crossref-linux.tar.xz -C linux-build pandoc-crossref pandoc-crossref.1 - tar cJf assets/pandoc-crossref-macos.tar.xz -C macos-build pandoc-crossref - zip -j assets/pandoc-crossref-windows.zip windows-build/pandoc-crossref.exe + tar cJf assets/pandoc-crossref-linux-${{github.sha}}.tar.xz -C linux-build pandoc-crossref pandoc-crossref.1 + tar cJf assets/pandoc-crossref-macos-${{github.sha}}.tar.xz -C macos-build pandoc-crossref + zip -j assets/pandoc-crossref-windows-${{github.sha}}.zip windows-build/pandoc-crossref.exe - name: Create Release if: contains(github.ref, 'tags/v') id: create_release @@ -179,7 +179,7 @@ jobs: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} with: upload_url: ${{ steps.create_release.outputs.upload_url }} - asset_path: ./assets/pandoc-crossref-linux.tar.xz + asset_path: ./assets/pandoc-crossref-linux-${{github.sha}}.tar.xz asset_name: pandoc-crossref-Linux-${{matrix.pandocver}}.tar.xz asset_content_type: application/x-xz-compressed-tar - name: Upload Release Asset macOS @@ -189,7 +189,7 @@ jobs: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} with: upload_url: ${{ steps.create_release.outputs.upload_url }} - asset_path: ./assets/pandoc-crossref-macos.tar.xz + asset_path: ./assets/pandoc-crossref-macos-${{github.sha}}.tar.xz asset_name: pandoc-crossref-macOS-${{matrix.pandocver}}.tar.xz asset_content_type: application/x-xz-compressed-tar - name: Upload Release Asset Windows @@ -199,7 +199,7 @@ jobs: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} with: upload_url: ${{ steps.create_release.outputs.upload_url }} - asset_path: ./assets/pandoc-crossref-windows.zip + asset_path: ./assets/pandoc-crossref-windows-${{github.sha}}.zip asset_name: pandoc-crossref-Windows-${{matrix.pandocver}}.zip asset_content_type: application/zip - name: Extract branch name From db434cf81782e4451c770dca460707d356d8e1fb Mon Sep 17 00:00:00 2001 From: Nikolay Yakimov Date: Thu, 12 Mar 2020 12:29:05 +0300 Subject: [PATCH 116/134] [CI] Pack Windows assets with 7zip --- .github/workflows/haskell.yml | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/.github/workflows/haskell.yml b/.github/workflows/haskell.yml index bd6e7214..e1164f8c 100644 --- a/.github/workflows/haskell.yml +++ b/.github/workflows/haskell.yml @@ -158,7 +158,7 @@ jobs: mkdir assets tar cJf assets/pandoc-crossref-linux-${{github.sha}}.tar.xz -C linux-build pandoc-crossref pandoc-crossref.1 tar cJf assets/pandoc-crossref-macos-${{github.sha}}.tar.xz -C macos-build pandoc-crossref - zip -j assets/pandoc-crossref-windows-${{github.sha}}.zip windows-build/pandoc-crossref.exe + 7z a assets/pandoc-crossref-windows-${{github.sha}}.7z windows-build/pandoc-crossref.exe - name: Create Release if: contains(github.ref, 'tags/v') id: create_release @@ -199,9 +199,9 @@ jobs: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} with: upload_url: ${{ steps.create_release.outputs.upload_url }} - asset_path: ./assets/pandoc-crossref-windows-${{github.sha}}.zip - asset_name: pandoc-crossref-Windows-${{matrix.pandocver}}.zip - asset_content_type: application/zip + asset_path: ./assets/pandoc-crossref-windows-${{github.sha}}.7z + asset_name: pandoc-crossref-Windows-${{matrix.pandocver}}.7z + asset_content_type: application/x-7z-compressed - name: Extract branch name shell: bash run: echo "##[set-output name=branch;]$(echo ${GITHUB_REF#refs/heads/})" From e59dba5f0c99bf2ba9dab87e8320d356c98e9a9b Mon Sep 17 00:00:00 2001 From: Nikolay Yakimov Date: Thu, 12 Mar 2020 12:53:23 +0300 Subject: [PATCH 117/134] [CI][Bintray] Try a more sophisticated upload to Bintray --- .github/workflows/haskell.yml | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/.github/workflows/haskell.yml b/.github/workflows/haskell.yml index e1164f8c..660287c0 100644 --- a/.github/workflows/haskell.yml +++ b/.github/workflows/haskell.yml @@ -207,14 +207,18 @@ jobs: run: echo "##[set-output name=branch;]$(echo ${GITHUB_REF#refs/heads/})" id: extract_branch - name: Upload to Bintray - uses: hpcsc/upload-bintray-docker-action@v1 + uses: lierdakil/action-bintray-upload@master with: + username: lierdakil + apiKey: ${{secrets.BINTRAY_API_KEY}} + subject: lierdakil repository: pandoc-crossref package: ${{steps.extract_branch.outputs.branch}} version: ${{github.sha}} - sourcePath: ./assets/* - username: lierdakil - apiKey: ${{secrets.BINTRAY_API_KEY}} + filesGlob: ./assets/* + createPkg: true + versionDescription: ${{ steps.get_version.outputs.version }} + licenses: 'GPL-2.0,GPL-3.0-or-later' build-stack: runs-on: ubuntu-latest From 0ff85c041c1d07db3055545134b5a48088715002 Mon Sep 17 00:00:00 2001 From: Nikolay Yakimov Date: Thu, 12 Mar 2020 18:33:29 +0300 Subject: [PATCH 118/134] [README] Remove AppVeyor link --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 13e8d0a8..03d55751 100644 --- a/README.md +++ b/README.md @@ -54,7 +54,7 @@ version of pandoc available, for which there are no pandoc-crossref builds. **NOTE:** Linux and MacOS binaries are packed with `upx`. If you don't like the overhead, and don't mind 40-megabyte binaries, you can unpack those manually with `upx -d pandoc-crossref`. Also please notice that upx-packed binaries can break in some exotic environments, like empty chroot with no access to `/proc`, etc. -Also, for those feeling adventurous, the automatic builds for the latest commits are available. Latest Windows builds can be found on [AppVeyor build history page](https://ci.appveyor.com/project/lierdakil/pandoc-crossref/history) (select a build and go to Artifacts). Latest Linux and MacOS builds can be found on [BinTray](https://bintray.com/lierdakil/pandoc-crossref/). +Also, for those feeling adventurous, the automatic builds for the latest commits are available. Latest builds can be found on [BinTray](https://bintray.com/lierdakil/pandoc-crossref/). If you don't trust random binaries downloaded off the Internet (which is completely reasonable), you're welcome to build from source. You have two From 80080744cec5c9d0696d4e4be77bec5fc1cc2375 Mon Sep 17 00:00:00 2001 From: Nikolay Yakimov Date: Thu, 9 Apr 2020 12:43:42 +0300 Subject: [PATCH 119/134] [CI] Bump pandoc --- .github/workflows/haskell.yml | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/.github/workflows/haskell.yml b/.github/workflows/haskell.yml index 660287c0..7e646846 100644 --- a/.github/workflows/haskell.yml +++ b/.github/workflows/haskell.yml @@ -6,10 +6,10 @@ jobs: linux: runs-on: ubuntu-latest container: - image: lierdakil/pandoc-crossref-build:054e0d2dd7816e7fba86e6a26fc6e2edc54e51c8 + image: lierdakil/pandoc-crossref-build:68a7211cc9067ae17a44746860fc685d204897fa strategy: matrix: - pandocver: ["2.9.2"] + pandocver: ["2.9.2.1"] steps: - uses: actions/checkout@v2 - name: Copy build config from image @@ -42,7 +42,7 @@ jobs: runs-on: macos-latest strategy: matrix: - pandocver: ["2.9.2"] + pandocver: ["2.9.2.1"] ghcver: ["8.8"] steps: - uses: actions/checkout@v2 @@ -89,7 +89,7 @@ jobs: runs-on: windows-latest strategy: matrix: - pandocver: ["2.9.2"] + pandocver: ["2.9.2.1"] cabalver: ["3.0"] ghcver: ["8.6.5"] env: @@ -133,7 +133,7 @@ jobs: runs-on: ubuntu-latest strategy: matrix: - pandocver: ["2.9.2"] + pandocver: ["2.9.2.1"] steps: - uses: actions/download-artifact@v1 with: From 14da0b7f44a50a02f656e56ac0c930df6c55a271 Mon Sep 17 00:00:00 2001 From: Nikolay Yakimov Date: Mon, 20 Apr 2020 14:14:23 +0300 Subject: [PATCH 120/134] Fix tests --- test/test-pandoc-crossref.hs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/test-pandoc-crossref.hs b/test/test-pandoc-crossref.hs index 2f826649..eacda4f6 100644 --- a/test/test-pandoc-crossref.hs +++ b/test/test-pandoc-crossref.hs @@ -42,9 +42,9 @@ import qualified Text.Pandoc.CrossRef.References.Refs as References.Refs import qualified Text.Pandoc.CrossRef.References.List as References.List import qualified Text.Pandoc.CrossRef.Util.Template as Util.Template import qualified Text.Pandoc.CrossRef.Util.CodeBlockCaptions as Util.CodeBlockCaptions +import qualified Data.Text as T #ifdef FLAKY -import qualified Data.Text as T import qualified Native import Paths_pandoc_crossref #endif From 7931586bfca9f35c112c2af824e6df7c739face9 Mon Sep 17 00:00:00 2001 From: Nikolay Yakimov Date: Sat, 20 Jun 2020 09:27:56 +0300 Subject: [PATCH 121/134] [CI] Mark as prerelease --- .github/workflows/haskell.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/haskell.yml b/.github/workflows/haskell.yml index 2a655452..e292dc8b 100644 --- a/.github/workflows/haskell.yml +++ b/.github/workflows/haskell.yml @@ -206,7 +206,7 @@ jobs: tag_name: ${{ github.ref }} release_name: ${{ github.ref }} draft: false - prerelease: false + prerelease: true body: | Linux: ${{ needs.linux.outputs.version }} macOS: ${{ needs.macos.outputs.version }} From fab05d77556540f32e16966c30e98313babe6fb3 Mon Sep 17 00:00:00 2001 From: Nikolay Yakimov Date: Sat, 20 Jun 2020 10:48:55 +0300 Subject: [PATCH 122/134] [CI] Force cabal config init --- .github/workflows/haskell.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/haskell.yml b/.github/workflows/haskell.yml index e292dc8b..8da641fb 100644 --- a/.github/workflows/haskell.yml +++ b/.github/workflows/haskell.yml @@ -70,7 +70,7 @@ jobs: # key: ${{ runner.os }}-${{matrix.pandocver}}-${{ hashFiles('pandoc-crossref.cabal') }} - name: Cabal init/update run: | - cabal user-config init --augment="store-dir: $PWD/.cabal-store" + cabal user-config init --force --augment="store-dir: $PWD/.cabal-store" cabal v2-update - name: Install dependencies # if: steps.cache.outputs.cache-hit != 'true' @@ -131,7 +131,7 @@ jobs: - name: Cabal init/update run: | $store = Join-Path $pwd ".cabal-store" - cabal user-config init --augment="store-dir: $store" --augment="jobs: 1" + cabal user-config init --force --augment="store-dir: $store" --augment="jobs: 1" cabal v2-update - name: Install dependencies if: steps.cache.outputs.cache-hit != 'true' From 40a8b12efce01cf46ff385875cf2d49e3cae6a91 Mon Sep 17 00:00:00 2001 From: Nikolay Yakimov Date: Fri, 4 Sep 2020 13:49:33 +0300 Subject: [PATCH 123/134] [CI] Fix BinTray descriptions --- .github/workflows/haskell.yml | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/.github/workflows/haskell.yml b/.github/workflows/haskell.yml index 7e8adcc8..4dfec388 100644 --- a/.github/workflows/haskell.yml +++ b/.github/workflows/haskell.yml @@ -132,7 +132,7 @@ jobs: with: name: release-assets path: assets - - name: Generate description + - name: Generate description.md if: startsWith(github.ref, 'refs/tags/v') shell: bash run: | @@ -141,14 +141,12 @@ jobs: os="${i%-build}" desc="$(cat $i/version.txt)" echo "${os}: ${desc}" >> description.md - echo ::set-output name=${os}::${desc} done ver="${GITHUB_REF##*/v}" echo "### Changelog" >> description.md sed -rn '/^## *'"${ver}"'/,/^##/ p' CHANGELOG.md | head -n-1 | tail -n+2 >> description.md echo "description.md" cat description.md - id: description - name: Rename assets for release if: startsWith(github.ref, 'refs/tags/v') shell: bash @@ -172,6 +170,16 @@ jobs: shell: bash run: echo "::set-output name=branch::${GITHUB_REF#refs/heads/}" id: extract_branch + - name: Generate description outputs + if: "!startsWith(github.ref, 'refs/tags/v')" + shell: bash + run: | + for i in *-build; do + os="${i%-build}" + desc="$(cat $i/version.txt)" + echo ::set-output name=${os}::${desc} + done + id: description - name: Upload to Bintray if: "!startsWith(github.ref, 'refs/tags/v')" uses: lierdakil/action-bintray-upload@master From 73fddcf69eee052a9414b57bd57166e3e7e4275e Mon Sep 17 00:00:00 2001 From: Nikolay Yakimov Date: Sat, 26 Sep 2020 19:34:56 +0300 Subject: [PATCH 124/134] Add scope reference index variable `s.refi` to referenceIndexTemplate --- lib/Text/Pandoc/CrossRef/References/Refs.hs | 1 + 1 file changed, 1 insertion(+) diff --git a/lib/Text/Pandoc/CrossRef/References/Refs.hs b/lib/Text/Pandoc/CrossRef/References/Refs.hs index 8d336e6c..ef3cd897 100644 --- a/lib/Text/Pandoc/CrossRef/References/Refs.hs +++ b/lib/Text/Pandoc/CrossRef/References/Refs.hs @@ -207,6 +207,7 @@ applyIndexTemplate :: Inlines -> RefRec -> Inlines applyIndexTemplate suf rr = let varsSc rr' "ref" = Just $ inlines False rr' varsSc rr' "Ref" = Just $ inlines True rr' + varsSc rr' "refi" = Just . MetaInlines . toList $ applyIndexTemplate mempty rr' varsSc rr' x = defaultVarFunc varsSc rr' x vars _ "suf" = Just $ MetaInlines $ toList suf vars rr' x = defaultVarFunc varsSc rr' x From f188b9aa37006ca518997e38a978c9dafd2cbdb8 Mon Sep 17 00:00:00 2001 From: Nikolay Yakimov Date: Sat, 26 Sep 2020 19:36:28 +0300 Subject: [PATCH 125/134] Use reference index in default sec referenceIndexTemplate --- lib/Text/Pandoc/CrossRef/Util/Settings.hs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/Text/Pandoc/CrossRef/Util/Settings.hs b/lib/Text/Pandoc/CrossRef/Util/Settings.hs index 48746fd1..5575b394 100644 --- a/lib/Text/Pandoc/CrossRef/Util/Settings.hs +++ b/lib/Text/Pandoc/CrossRef/Util/Settings.hs @@ -163,7 +163,7 @@ basicMeta = Settings $ "title" .= text "Section", "captionTemplate" .= var "t", "scope" .= ["sec" :: T.Text], - "referenceIndexTemplate" .= var "s.i%." <> var "i" <> var "suf" + "referenceIndexTemplate" .= var "s.refi%." <> var "i" <> var "suf" ] ] From 592cbfe69660519a7bbe1518c6fbed6286a4fd6c Mon Sep 17 00:00:00 2001 From: Nikolay Yakimov Date: Thu, 10 Dec 2020 10:51:26 +0300 Subject: [PATCH 126/134] Hierarchical section numbering for numberSections --- lib/Text/Pandoc/CrossRef/Util/Settings.hs | 1 + 1 file changed, 1 insertion(+) diff --git a/lib/Text/Pandoc/CrossRef/Util/Settings.hs b/lib/Text/Pandoc/CrossRef/Util/Settings.hs index 5575b394..97821d06 100644 --- a/lib/Text/Pandoc/CrossRef/Util/Settings.hs +++ b/lib/Text/Pandoc/CrossRef/Util/Settings.hs @@ -92,6 +92,7 @@ numberSectionsMeta :: Settings numberSectionsMeta = Settings $ prefixes' [ "sec" .: [ + "captionIndexTemplate" .= var "s.i%." <> var "ri", "captionTemplate" .= var "title" <> space <> var "i" <> str "." <> space <> var "t" ] From 48049b0ed4e00bee6111df4c94fe2d8e782db3c7 Mon Sep 17 00:00:00 2001 From: Nikolay Yakimov Date: Thu, 10 Dec 2020 10:53:15 +0300 Subject: [PATCH 127/134] Fix demo test --- test/demo.inc | 114 ++++++++++++++++++++++++++++---------------------- 1 file changed, 65 insertions(+), 49 deletions(-) diff --git a/test/demo.inc b/test/demo.inc index 9fea08b4..84110fb2 100644 --- a/test/demo.inc +++ b/test/demo.inc @@ -1,29 +1,44 @@ - [Para [Str "This",Space,Str "is",Space,Str "a",Space,Str "demo",Space,Str "file",Space,Str "for",Space,Str "pandoc-crossref.",Space,Str "With",Space,Str "this",Space,Str "filter,",Space,Str "you",Space,Str "can",Space,Str "cross-reference",Space,Str "figures",Space,Str "(see",Space,Str "figs.\160\&2-4),",Space,Str "display",Space,Str "equations",Space,Str "(see",Space,Str "eq.\160\&1),",Space,Str "tables",Space,Str "(see",Space,Str "tbl.\160\&1)",Space,Str "and",Space,Str "sections",Space,Str "(",Str "secs.\160\&1,",Space,Str "2,",Space,Str "4.1-4.3)"] + [Para [Str "This",Space,Str "is",Space,Str "a",Space,Str "demo",Space,Str "file",Space,Str "for",Space,Str "pandoc-crossref.",Space,Str "With",Space,Str "this",Space,Str "filter,",Space,Str "you",Space,Str "can",Space,Str "cross-reference",Space,Str "figures",Space,Str "(see",Space,Str "figs.\160\&1.1-1.3),",Space,Str "display",Space,Str "equations",Space,Str "(see",Space,Str "eq.\160\&2.1),",Space,Str "tables",Space,Str "(see",Space,Str "tbl.\160\&3.1)",Space,Str "and",Space,Str "sections",Space,Str "(",Str "secs.\160\&1,",Space,Str "2,",Space,Str "secs.\160\&4.1-4.3)"] ,Para [Str "For",Space,Str "immediate",Space,Str "example,",Space,Str "see",Space,Str "fig.\160\&1"] - ,Para [Image ("fig:figure0",[],[]) [Str "Figure",Space,Str "#",Space,Str "1:",Space,Str "A",Space,Str "figure"] ("img1.jpg","fig:")] - ,Para [Str "There",Space,Str "is",Space,Str "also",Space,Str "support",Space,Str "for",Space,Str "code",Space,Str "blocks,",Space,Str "for",Space,Str "example,",Space,Str "lsts.\160\&1-3"] - ,Para [Str "It\8217s",Space,Str "possible",Space,Str "to",Space,Str "capitalize",Space,Str "reference",Space,Str "prefixes,",Space,Str "like",Space,Str "this:",Space,Str "Fig.\160\&2."] - ,Para [Str "In",Space,Str "case",Space,Str "of",Space,Str "multiple",Space,Str "references,",Space,Str "capitalization",Space,Str "is",Space,Str "determined",Space,Str "by",Space,Str "first",Space,Str "reference.",Space,Str "Figs.\160\&2,",Space,Str "3",Space,Str "is",Space,Str "capitalized,",Space,Str "while",Space,Str "figs.\160\&2,",Space,Str "3",Space,Str "is",Space,Str "not."] - ,Para [Str "It",Space,Str "is",Space,Str "also",Space,Str "possible",Space,Str "to",Space,Str "mix",Space,Str "different",Space,Str "references,",Space,Str "like",Space,Str "fig.\160\&2,",Space,Str "tbl.\160\&1,",Space,Str "lsts.\160\&1,",Space,Str "2,",Space,Str "figs.\160\&3,",Space,Str "4,",Space,Str "which",Space,Str "will",Space,Str "be",Space,Str "grouped",Space,Str "in",Space,Str "order",Space,Str "they",Space,Str "are",Space,Str "specified.",Space,Str "You",Space,Str "can",Space,Str "even",Space,Str "intermix",Space,Str "this",Space,Str "with",Space,Str "regular",Space,Str "citations,",Space,Str "although",Space,Str "it\8217s",Space,Str "not",Space,Str "recommended:",Space,Str "fig.\160\&2,",Space,Str "tbl.\160\&1,",Space,Cite [Citation {citationId = "unprocessedCitation", citationPrefix = [], citationSuffix = [], citationMode = NormalCitation, citationNoteNum = 11, citationHash = 0}] [Str "[@unprocessedCitation]"]] - ,Para [Str "You",Space,Str "can",Space,Str "also",Space,Str "have",Space,Str "custom",Space,Str "chapter",Space,Str "reference",Space,Str "labels,",Space,Str "like",Space,Str "sec.\160AppA.CustLab"] - ,Para [Str "Subfigures",Space,Str "are",Space,Str "supported,",Space,Str "see",Space,Str "figs.\160\&5,",Space,Str "5",Space,Str "(b)"] + ,Para [Image ("fig:figure0",[],[]) [Str "Figure\160\&1:",Space,Str "A",Space,Str "figure"] ("img1.jpg","fig:")] + ,Para [Str "There",Space,Str "is",Space,Str "also",Space,Str "support",Space,Str "for",Space,Str "code",Space,Str "blocks,",Space,Str "for",Space,Str "example,",Space,Str "lsts.\160\&4.1.1,",Space,Str "4.2.1,",Space,Str "4.3.1"] + ,Para [Str "It\8217s",Space,Str "possible",Space,Str "to",Space,Str "capitalize",Space,Str "reference",Space,Str "prefixes,",Space,Str "like",Space,Str "this:",Space,Str "Fig.\160\&1.1."] + ,Para [Str "In",Space,Str "case",Space,Str "of",Space,Str "multiple",Space,Str "references,",Space,Str "capitalization",Space,Str "is",Space,Str "determined",Space,Str "by",Space,Str "first",Space,Str "reference.",Space,Str "Figs.\160\&1.1,",Space,Str "1.2",Space,Str "is",Space,Str "capitalized,",Space,Str "while",Space,Str "figs.\160\&1.1,",Space,Str "1.2",Space,Str "is",Space,Str "not."] + ,Para [Str "It",Space,Str "is",Space,Str "also",Space,Str "possible",Space,Str "to",Space,Str "mix",Space,Str "different",Space,Str "references,",Space,Str "like",Space,Str "fig.\160\&1.1,",Space,Str "tbl.\160\&3.1,",Space,Str "lsts.\160\&4.1.1,",Space,Str "4.2.1,",Space,Str "figs.\160\&1.2,",Space,Str "1.3,",Space,Str "which",Space,Str "will",Space,Str "be",Space,Str "grouped",Space,Str "in",Space,Str "order",Space,Str "they",Space,Str "are",Space,Str "specified.",Space,Str "You",Space,Str "can",Space,Str "even",Space,Str "intermix",Space,Str "this",Space,Str "with",Space,Str "regular",Space,Str "citations,",Space,Str "although",Space,Str "it\8217s",Space,Str "not",Space,Str "recommended:",Space,Str "fig.\160\&1.1,",Space,Str "tbl.\160\&3.1,",Space,Cite [Citation {citationId = "unprocessedCitation", citationPrefix = [], citationSuffix = [], citationMode = NormalCitation, citationNoteNum = 11, citationHash = 0}] [Str "[@unprocessedCitation]"]] + ,Para [Str "You",Space,Str "can",Space,Str "also",Space,Str "have",Space,Str "custom",Space,Str "chapter",Space,Str "reference",Space,Str "labels,",Space,Str "like",Space,Str "sec.\160A.I"] + ,Para [Str "Subfigures",Space,Str "are",Space,Str "supported,",Space,Str "see",Space,Str "fig.\160\&1.5,",Space,Str "fig.\160\&1.5(b)"] ,Header 1 ("sec:sec1",[],[]) [Str "Chapter",Space,Str "1.",Space,Str "Figures"] - ,Para [Image ("fig:figure1",[],[]) [Str "Figure",Space,Str "#",Space,Str "2:",Space,Str "First",Space,Str "figure"] ("img1.jpg","fig:")] - ,Para [Image ("fig:figure2",[],[]) [Str "Figure",Space,Str "#",Space,Str "3:",Space,Str "Second",Space,Str "figure"] ("img2.jpg","fig:")] - ,Para [Image ("fig:figure3",[],[]) [Str "Figure",Space,Str "#",Space,Str "4:",Space,Str "Third",Space,Str "figure"] ("img3.jpg","fig:")] - ,Para [Image ("",[],[]) [Str "Unlabelled",Space,Str "image"] ("img1.jpg","fig:")] - ,Div ("fig:subfigures",["subfigures"],[]) - [Para [Image ("",[],[]) [Str "a"] ("img1.jpg","fig:")] - ,Para [Image ("fig:subfigureB",[],[]) [Str "b"] ("img1.jpg","fig:")] - ,Para [Str "Figure",Space,Str "#",Space,Str "5:",Space,Str "Subfigures",Space,Str "caption.",Space,Str "a",Space,Str "\8212",Space,Str "Subfigure",Space,Str "a,",Space,Str "b",Space,Str "\8212",Space,Str "Subfigure",Space,Str "b"]] + ,Para [Image ("fig:figure1",[],[]) [Str "Figure\160\&1.1:",Space,Str "First",Space,Str "figure"] ("img1.jpg","fig:")] + ,Para [Image ("fig:figure2",[],[]) [Str "Figure\160\&1.2:",Space,Str "Second",Space,Str "figure"] ("img2.jpg","fig:")] + ,Para [Image ("fig:figure3",[],[]) [Str "Figure\160\&1.3:",Space,Str "Third",Space,Str "figure"] ("img3.jpg","fig:")] + ,Para [Image ("",[],[]) [Str "Figure\160\&1.4:",Space,Str "Unlabelled",Space,Str "image"] ("img1.jpg","fig:")] + ,Div ("fig:subfigures",["subcaption"],[]) + [Table ("",[],[]) (Caption Nothing + []) + [(AlignCenter,ColWidth 0.99)] + (TableHead ("",[],[]) + []) + [(TableBody ("",[],[]) (RowHeadColumns 0) + [] + [Row ("",[],[]) + [Cell ("",[],[]) AlignDefault (RowSpan 0) (ColSpan 0) + [Div ("",[],[]) + [Para [Image ("",[],[("width","100%")]) [Str "a"] ("img1.jpg","fig:")]]]] + ,Row ("",[],[]) + [Cell ("",[],[]) AlignDefault (RowSpan 0) (ColSpan 0) + [Div ("",[],[]) + [Para [Image ("fig:subfigureB",[],[("width","100%")]) [Str "b"] ("img1.jpg","fig:")]]]]])] + (TableFoot ("",[],[]) + []) + ,Para [Str "Figure\160\&1.5:",Space,Str "Subfigures",Space,Str "caption.",Space,Span ("",[],[]) [Str "a",Space,Str "\8211",Space,Str "Subfigure",Space,Str "a,",Space,Str "b",Space,Str "\8211",Space,Str "Subfigure",Space,Str "b"]]] ,Header 1 ("sec:sec2",[],[]) [Str "Chapter",Space,Str "2.",Space,Str "Equations"] ,Para [Str "Display",Space,Str "equations",Space,Str "are",Space,Str "labelled",Space,Str "and",Space,Str "numbered"] - ,Para [Span ("eq:eqn1",[],[]) [Math DisplayMath " P_i(x) = \\sum_i a_i x^i \\qquad(1)"]] - ,Para [Str "Since",Space,Str "0.1.6.0",Space,Str "those",Space,Str "can",Space,Str "also",Space,Str "appear",Space,Str "in",Space,Str "the",Space,Str "middle",Space,Str "of",Space,Str "paragraph",SoftBreak,Span ("eq:quadr",[],[]) [Math DisplayMath "a x^2 + b x^2 + c = 0\\qquad(2)"],Space,Str "like",Space,Str "this."] - ,Header 1 ("sec:chapter-3.-tables",[],[]) [Str "Chapter",Space,Str "3.",Space,Str "Tables"] + ,Para [Span ("eq:eqn1",[],[]) [Math DisplayMath " P_i(x) = \\sum_i a_i x^i \\qquad(2.1)"]] + ,Para [Str "Since",Space,Str "0.1.6.0",Space,Str "those",Space,Str "can",Space,Str "also",Space,Str "appear",Space,Str "in",Space,Str "the",Space,Str "middle",Space,Str "of",Space,Str "paragraph",SoftBreak,Span ("eq:quadr",[],[]) [Math DisplayMath "a x^2 + b x^2 + c = 0\\qquad(2.2)"],Space,Str "like",Space,Str "this."] + ,Header 1 ("sec:tables",[],[]) [Str "Chapter",Space,Str "3.",Space,Str "Tables"] ,Div ("tbl:table1",[],[]) [Table ("",[],[]) (Caption Nothing - [Plain [Emph [Str "Table",Space,Str "1"],Str ":",Space,Str "Table",Space,Str "example"]]) + [Plain [Str "Table\160\&3.1:",Space,Str "Table",Space,Str "example"]]) [(AlignLeft,ColWidthDefault) ,(AlignLeft,ColWidthDefault)] (TableHead ("",[],[]) @@ -71,44 +86,45 @@ [Plain [Str "Content",Space,Str "Cell"]]]])] (TableFoot ("",[],[]) []) - ,Header 1 ("sec:chapter-4.-code-blocks",[],[]) [Str "Chapter",Space,Str "4.",Space,Str "Code",Space,Str "blocks"] + ,Header 1 ("sec:code-blocks",[],[]) [Str "Chapter",Space,Str "4.",Space,Str "Code",Space,Str "blocks"] ,Para [Str "There",Space,Str "are",Space,Str "a",Space,Str "couple",Space,Str "options",Space,Str "for",Space,Str "code",Space,Str "block",Space,Str "labels.",Space,Str "Those",Space,Str "work",Space,Str "only",Space,Str "if",Space,Str "code",Space,Str "block",Space,Str "id",Space,Str "starts",Space,Str "with",Space,Code ("",[],[]) "lst:",Str ",",Space,Str "e.g.\160",Code ("",[],[]) "{#lst:label}"] - ,Header 2 ("sec:caption-attr",[],[]) [Code ("",[],[]) "caption",Space,Str "attribute"] + ,Header 2 ("sec:caption-attr",[],[]) [Str "Section",Space,Str "4.1.",Space,Code ("",[],[]) "caption",Space,Str "attribute"] ,Para [Code ("",[],[]) "caption",Space,Str "attribute",Space,Str "will",Space,Str "be",Space,Str "treated",Space,Str "as",Space,Str "code",Space,Str "block",Space,Str "caption.",Space,Str "If",Space,Str "code",Space,Str "block",Space,Str "has",Space,Str "both",Space,Str "id",Space,Str "and",Space,Code ("",[],[]) "caption",Space,Str "attributes,",Space,Str "it",Space,Str "will",Space,Str "be",Space,Str "treated",Space,Str "as",Space,Str "numbered",Space,Str "code",Space,Str "block."] ,Div ("lst:captionAttr",["listing","haskell"],[]) - [Para [Str "Listing",Space,Str "1:",Space,Str "Listing",Space,Str "caption"] + [Para [Str "Listing\160\&4.1.1:",Space,Str "Listing",Space,Str "caption"] ,CodeBlock ("",["haskell"],[]) "main :: IO ()\nmain = putStrLn \"Hello World!\""] ,RawBlock (Format "tex") "\\pagebreak" - ,Header 2 ("sec:table-capts",[],[]) [Str "Table-style",Space,Str "captions"] + ,Header 2 ("sec:table-capts",[],[]) [Str "Section",Space,Str "4.2.",Space,Str "Table-style",Space,Str "captions"] ,Para [Str "Enabled",Space,Str "with",Space,Code ("",[],[]) "codeBlockCaptions",Space,Str "metadata",Space,Str "option.",Space,Str "If",Space,Str "code",Space,Str "block",Space,Str "is",Space,Str "immediately",SoftBreak,Str "adjacent",Space,Str "to",Space,Str "paragraph,",Space,Str "starting",Space,Str "with",Space,Code ("",[],[]) "Listing:",Space,Str "or",Space,Code ("",[],[]) ":",Str ",",Space,Str "said",Space,Str "paragraph",Space,Str "will",Space,Str "be",SoftBreak,Str "treated",Space,Str "as",Space,Str "code",Space,Str "block",Space,Str "caption."] ,Div ("lst:tableCaption",["listing","haskell"],[]) - [Para [Str "Listing",Space,Str "2:",Space,Str "Listing",Space,Str "caption"] + [Para [Str "Listing\160\&4.2.1:",Space,Str "Listing",Space,Str "caption"] ,CodeBlock ("",["haskell"],[]) "main :: IO ()\nmain = putStrLn \"Hello World!\""] - ,Header 2 ("sec:wrapping-div",[],[]) [Str "Wrapping",Space,Str "div"] - ,Para [Str "Wrapping",Space,Str "code",Space,Str "block",Space,Str "without",Space,Str "label",Space,Str "in",Space,Str "a",Space,Str "div",Space,Str "with",Space,Str "id",Space,Code ("",[],[]) "lst:...",Space,Str "and",Space,Str "class,",Space,Str "starting",Space,Str "with",Space,Code ("",[],[]) "listing",Str ",",Space,Str "and",Space,Str "adding",Space,Str "paragraph",Space,Str "before",Space,Str "code",Space,Str "block,",Space,Str "but",Space,Str "inside",Space,Str "div,",Space,Str "will",Space,Str "treat",Space,Str "said",Space,Str "paragraph",Space,Str "as",Space,Str "code",Space,Str "block",Space,Str "caption."] - ,Div ("lst:wrappingDiv",["listing","haskell"],[]) - [Para [Str "Listing",Space,Str "3:",Space,Str "Listing",Space,Str "caption"] + ,Header 2 ("sec:wrapping-div",[],[]) [Str "Section",Space,Str "4.3.",Space,Str "Wrapping",Space,Str "div"] + ,Para [Str "Wrapping",Space,Str "code",Space,Str "block",Space,Str "without",Space,Str "label",Space,Str "in",Space,Str "a",Space,Str "div",Space,Str "with",Space,Str "id",Space,Code ("",[],[]) "lst:...",Space,Str "and",Space,Str "class,",Space,Str "starting",Space,Str "with",Space,Code ("",[],[]) "listing",Str ",",Space,Str "and",Space,Str "adding",Space,Str "paragraph",Space,Str "after",Space,Str "code",Space,Str "block,",Space,Str "but",Space,Str "inside",Space,Str "div,",Space,Str "starting",Space,Str "with",Space,Code ("",[],[]) ":",Space,Str "will",Space,Str "treat",Space,Str "said",Space,Str "paragraph",Space,Str "as",Space,Str "code",Space,Str "block",Space,Str "caption."] + ,Div ("lst:wrappingDiv",["listing"],[]) + [Para [Str "Listing\160\&4.3.1:",Space,Str "Listing",Space,Str "caption"] ,CodeBlock ("",["haskell"],[]) "main :: IO ()\nmain = putStrLn \"Hello World!\""] ,Header 1 ("sec:unnumbered-chapter.",["unnumbered"],[]) [Str "Unnumbered",Space,Str "chapter."] - ,Para [Str "This",Space,Str "chapter",Space,Str "doesn\8217t",Space,Str "change",Space,Str "chapter",Space,Str "prefix",Space,Str "of",Space,Str "referenced",Space,Str "elements,",Space,Str "instead",Space,Str "keeping",Space,Str "number",Space,Str "of",Space,Str "previous",Space,Str "chapter,",Space,Str "e.g.",SoftBreak,Span ("eq:eqn2",[],[]) [Math DisplayMath " S(x) = \\int_{x_1}^{x_2} a x+b \\ \\mathrm{d}x \\qquad(3)"]] - ,Header 1 ("sec:chapter-5.-reference-lists",[],[]) [Str "Chapter",Space,Str "5.",Space,Str "Reference",Space,Str "lists"] + ,Para [Str "This",Space,Str "chapter",Space,Str "doesn\8217t",Space,Str "change",Space,Str "chapter",Space,Str "prefix",Space,Str "of",Space,Str "referenced",Space,Str "elements,",Space,Str "instead",Space,Str "keeping",Space,Str "number",Space,Str "of",Space,Str "previous",Space,Str "chapter,",Space,Str "e.g.",SoftBreak,Span ("eq:eqn2",[],[]) [Math DisplayMath " S(x) = \\int_{x_1}^{x_2} a x+b \\ \\mathrm{d}x \\qquad(1)"]] + ,Header 1 ("sec:reference-lists",[],[]) [Str "Chapter",Space,Str "5.",Space,Str "Reference",Space,Str "lists"] ,Para [Str "It\8217s",Space,Str "also",Space,Str "possible",Space,Str "to",Space,Str "show",Space,Str "lists",Space,Str "of",Space,Str "figures",Space,Str "and",Space,Str "tables,",Space,Str "like",Space,Str "this:"] - ,Header 2 ("list-of-figures",[],[]) [Str "List",Space,Str "of",Space,Str "Figures"] - ,OrderedList (1,DefaultStyle,DefaultDelim) - [[Plain [Str "A",Space,Str "figure"]] - ,[Plain [Str "First",Space,Str "figure"]] - ,[Plain [Str "Second",Space,Str "figure"]] - ,[Plain [Str "Third",Space,Str "figure"]] - ,[Plain [Str "Subfigure",Space,Str "a"]] - ,[Plain [Str "Subfigure",Space,Str "b"]] - ,[Plain [Str "Subfigures",Space,Str "caption"]]] - ,Header 2 ("list-of-tables",[],[]) [Str "List",Space,Str "of",Space,Str "Tables"] - ,OrderedList (1,DefaultStyle,DefaultDelim) - [[Plain [Str "Table",Space,Str "example"]]] + ,Header 1 ("",[],[]) [Str "List",Space,Str "of",Space,Str "Figures"] + ,Div ("",["list"],[]) + [Para [Str "1.",Space,Str "A",Space,Str "figure"] + ,Para [Str "1.1.",Space,Str "First",Space,Str "figure"] + ,Para [Str "1.2.",Space,Str "Second",Space,Str "figure"] + ,Para [Str "1.3.",Space,Str "Third",Space,Str "figure"] + ,Para [Str "1.4.",Space,Str "Unlabelled",Space,Str "image"] + ,Para [Str "1.5.",Space,Str "Subfigures",Space,Str "caption.",Space,Span ("",[],[]) []] + ,Para [Str "1.5(a).",Space,Str "Subfigure",Space,Str "a"] + ,Para [Str "1.5(b).",Space,Str "Subfigure",Space,Str "b"]] + ,Header 1 ("",[],[]) [Str "List",Space,Str "of",Space,Str "Tables"] + ,Div ("",["list"],[]) + [Para [Str "3.1.",Space,Str "Table",Space,Str "example"]] ,Header 1 ("",[],[]) [Str "List",Space,Str "of",Space,Str "Listings"] - ,OrderedList (1,DefaultStyle,DefaultDelim) - [[Plain [Str "Listing",Space,Str "caption"]] - ,[Plain [Str "Listing",Space,Str "caption"]] - ,[Plain [Str "Listing",Space,Str "caption"]]] - ,Header 1 ("sec:appendix-a.-custom-labels",[],[("label","AppA")]) [Str "Appendix",Space,Str "A.",Space,Str "Custom",Space,Str "labels"] - ,Header 2 ("sec:custlabs",[],[("label","CustLab")]) [Str "This",Space,Str "section",Space,Str "will",Space,Str "have",Space,Str "custom",Space,Str "label"]] + ,Div ("",["list"],[]) + [Para [Str "4.1.1.",Space,Str "Listing",Space,Str "caption"] + ,Para [Str "4.2.1.",Space,Str "Listing",Space,Str "caption"] + ,Para [Str "4.3.1.",Space,Str "Listing",Space,Str "caption"]] + ,Header 1 ("sec:custom-labels",[],[("label","A"),("title","Appendix")]) [Str "Appendix",Space,Str "A.",Space,Str "Custom",Space,Str "labels"] + ,Header 2 ("sec:custlabs",[],[("label","I")]) [Str "Section",Space,Str "A.I.",Space,Str "This",Space,Str "section",Space,Str "will",Space,Str "have",Space,Str "custom",Space,Str "label"]] From 004e7632451f6aab620a486a846a3a1aa23c7dfd Mon Sep 17 00:00:00 2001 From: Nikolay Yakimov Date: Sun, 21 Mar 2021 22:16:42 +0300 Subject: [PATCH 128/134] Move default settings to embedded yaml files --- .../Text/Pandoc/CrossRef/Util/Meta.hs | 2 +- .../Text/Pandoc/CrossRef/Util/Settings.hs | 141 ++---------------- .../Pandoc/CrossRef/Util/Settings/Embed.hs | 14 ++ .../CrossRef/Util/Settings/LiftPandoc.hs | 33 ++++ .../Pandoc/CrossRef/Util/Settings/Util.hs | 28 ++++ package.yaml | 3 + pandoc-crossref.cabal | 11 +- settings/chapters.yaml | 8 + settings/default.yaml | 45 ++++++ settings/numberSections.yaml | 4 + settings/subfigures.yaml | 10 ++ 11 files changed, 167 insertions(+), 132 deletions(-) create mode 100644 lib-internal/Text/Pandoc/CrossRef/Util/Settings/Embed.hs create mode 100644 lib-internal/Text/Pandoc/CrossRef/Util/Settings/LiftPandoc.hs create mode 100644 lib-internal/Text/Pandoc/CrossRef/Util/Settings/Util.hs create mode 100644 settings/chapters.yaml create mode 100644 settings/default.yaml create mode 100644 settings/numberSections.yaml create mode 100644 settings/subfigures.yaml diff --git a/lib-internal/Text/Pandoc/CrossRef/Util/Meta.hs b/lib-internal/Text/Pandoc/CrossRef/Util/Meta.hs index 78044a7c..9197d36b 100644 --- a/lib-internal/Text/Pandoc/CrossRef/Util/Meta.hs +++ b/lib-internal/Text/Pandoc/CrossRef/Util/Meta.hs @@ -42,7 +42,7 @@ import Text.Pandoc.Definition import Text.Pandoc.Builder import Data.Default import Text.Pandoc.Walk -import Text.Pandoc.Shared hiding (capitalize, toString) +import Text.Pandoc.Shared hiding (capitalize) import Data.Maybe import qualified Data.Map as M import qualified Data.Text as T diff --git a/lib-internal/Text/Pandoc/CrossRef/Util/Settings.hs b/lib-internal/Text/Pandoc/CrossRef/Util/Settings.hs index 97821d06..4a7cd4ac 100644 --- a/lib-internal/Text/Pandoc/CrossRef/Util/Settings.hs +++ b/lib-internal/Text/Pandoc/CrossRef/Util/Settings.hs @@ -19,19 +19,18 @@ with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -} -{-# LANGUAGE OverloadedStrings #-} +{-# LANGUAGE OverloadedStrings, TemplateHaskell, BangPatterns #-} module Text.Pandoc.CrossRef.Util.Settings (readSettings, defaultMeta, Settings(..)) where import Text.Pandoc -import Text.Pandoc.Builder hiding ((<>)) import Control.Exception (handle,IOException) -import Text.Pandoc.CrossRef.Util.Settings.Gen +import Text.Pandoc.CrossRef.Util.Settings.Embed +import Text.Pandoc.CrossRef.Util.Settings.Util import Text.Pandoc.CrossRef.Util.Settings.Types import Text.Pandoc.CrossRef.Util.Meta import System.Directory import System.FilePath -import System.IO import qualified Data.Text as T import qualified Data.Map as M @@ -42,26 +41,18 @@ readSettings fmt inMeta = do Meta m | Just (MetaMap cm) <- M.lookup "crossref" m -> Settings (Meta cm) _ -> Settings inMeta - dirConfig <- readConfig . T.unpack $ getMetaString "crossrefYaml" (meta <> defaultMeta meta) + dirConfig <- readConfig' . T.unpack $ getMetaString "crossrefYaml" (meta <> defaultMeta meta) home <- getHomeDirectory - globalConfig <- readConfig (home ".pandoc-crossref" "config.yaml") + globalConfig <- readConfig' (home ".pandoc-crossref" "config.yaml") formatConfig <- maybe (return mempty) (readFmtConfig home) fmt return $ globalConfig <> formatConfig <> dirConfig <> meta where - readConfig path = - handle handler $ do - h <- openFile path ReadMode - hSetEncoding h utf8 - yaml <- hGetContents h - Pandoc meta' _ <- readMd $ T.pack $ unlines ["---", yaml, "---"] - return $ Settings meta' - readMd = handleError . runPure . readMarkdown def{readerExtensions=pandocExtensions} - readFmtConfig home fmt' = readConfig (home ".pandoc-crossref" "config-" ++ T.unpack (fmtStr fmt') ++ ".yaml") + readConfig' = handle handler . readConfig + readFmtConfig home fmt' = readConfig' (home ".pandoc-crossref" "config-" ++ T.unpack (fmtStr fmt') ++ ".yaml") handler :: IOException -> IO Settings handler _ = return mempty fmtStr (Format fmtstr) = fmtstr - defaultMeta :: Settings -> Settings defaultMeta userSettings | null option = basicMeta @@ -69,118 +60,8 @@ defaultMeta userSettings | otherwise = mconcat . reverse $ basicMeta : map name2set option where option = getMetaStringList "defaultOption" userSettings - name2set "chapters" = chaptersMeta - name2set "subfigures" = subfiguresMeta - name2set "numberSections" = numberSectionsMeta + name2set "chapters" = $(embedFile "chapters") + name2set "subfigures" = $(embedFile "subfigures") + name2set "numberSections" = $(embedFile "numberSections") name2set x = error . T.unpack $ "Unknown defaultOption value: " <> x - -chaptersMeta :: Settings -chaptersMeta = Settings $ - captionIndexTemplate (var "s.i%." <> var "ri") - <> customMeta [ "scope" .= ("sec" :: T.Text) ] - <> prefixes' [ - "sec" .: [ - "title" .= ("Chapter" :: T.Text), - "sub" .: [ - "title" .= ("Section" :: T.Text), - "referenceIndexTemplate" .= var "i" <> var "suf" - ] - ] - ] - -numberSectionsMeta :: Settings -numberSectionsMeta = Settings $ - prefixes' [ - "sec" .: [ - "captionIndexTemplate" .= var "s.i%." <> var "ri", - "captionTemplate" .= var "title" <> space <> var "i" - <> str "." <> space <> var "t" - ] - ] - -subfiguresMeta :: Settings -subfiguresMeta = Settings $ - prefixes' [ - "fig" .: [ - "subcaptions" .= True, - "sub" .: [ - "numbering" .= ("alpha a" :: T.Text), - "referenceIndexTemplate" .= si, - "listItemTemplate" .= (si <> var "listItemNumberDelim" <> var "t"), - "captionTemplate" .= var "i", - "scope" .= ["fig" :: T.Text], - "captionIndexTemplate" .= var "ri" - ] - ] - ] - where si = var "s.i" <> str "(" <> var "i" <> str ")" - -basicMeta :: Settings -basicMeta = Settings $ - codeBlockCaptions False - <> adjustSectionIdentifiers False - <> autoSectionLabels ("sec" :: T.Text) - <> titleDelim (str ":" <> space) - <> listItemNumberDelim (str "." <> space) - <> rangeDelim (str "-") - <> pairDelim (str "," <> space) - <> lastDelim (str "," <> space) - <> refDelim (str "," <> space) - <> crossrefYaml ("pandoc-crossref.yaml" :: T.Text) - <> linkReferences False - <> nameInLink False - <> collectedCaptionDelim (str "," <> space) - <> collectedCaptionItemDelim (space <> str "–" <> space) - -- these are merely the defaults, can (and will) be overridden in prefix configs - <> captionTemplate (var "title%\160" <> var "i" <> var "titleDelim" <> var "t") - <> captionIndexTemplate (var "ri") - <> referenceTemplate (var "Ref[n]%\160" <> var "rs") - <> listItemTemplate (var "i" <> var "listItemNumberDelim" <> var "t") - <> collectedCaptionTemplate (var "i" <> var "collectedCaptionItemDelim" <> var "t") - <> referenceIndexTemplate (var "i" <> var "suf") - <> listOfTitle (header 1 $ text "List of " <> var "title" <> str "s") - <> numbering ("arabic" :: T.Text) - <> prefixes' [ - "eq" .: [ - "ref" .= map str ["eq.", "eqns."], - "captionTemplate" .= var "t" <> str "\\qquad(" <> var "i" <> str ")", - "title" .= text "Equation" - ], - "fig" .: [ - "ref" .= map str ["fig.", "figs."], - "title" .= text "Figure" - ], - "lst" .: [ - "ref" .= map str ["lst.", "lsts."], - "title" .= text "Listing", - "captionPosition" .= ("above" :: T.Text) - ], - "tbl" .: [ - "ref" .= map str ["tbl.", "tbls."], - "title" .= text "Table" - ], - "sec" .: [ - "ref" .= map str ["sec.", "secs."], - "title" .= text "Section", - "captionTemplate" .= var "t", - "scope" .= ["sec" :: T.Text], - "referenceIndexTemplate" .= var "s.refi%." <> var "i" <> var "suf" - ] - ] - -var :: T.Text -> Inlines -var = displayMath - -prefixes' :: [(T.Text, MetaValue)] -> Meta -prefixes' = prefixes . MetaMap . M.fromList - -customMeta :: [(T.Text, MetaValue)] -> Meta -customMeta = Meta . M.fromList - -infixr 0 .: -(.:) :: T.Text -> [(T.Text, MetaValue)] -> (T.Text, MetaValue) -key .: val = (key, MetaMap $ M.fromList val) - -infixr 0 .= -(.=) :: ToMetaValue a => T.Text -> a -> (T.Text, MetaValue) -key .= val = (key, toMetaValue val) + basicMeta = $(embedFile "default") diff --git a/lib-internal/Text/Pandoc/CrossRef/Util/Settings/Embed.hs b/lib-internal/Text/Pandoc/CrossRef/Util/Settings/Embed.hs new file mode 100644 index 00000000..5c9f4eea --- /dev/null +++ b/lib-internal/Text/Pandoc/CrossRef/Util/Settings/Embed.hs @@ -0,0 +1,14 @@ +{-# LANGUAGE TemplateHaskell, DeriveLift, StandaloneDeriving #-} +module Text.Pandoc.CrossRef.Util.Settings.Embed where + +import Text.Pandoc.CrossRef.Util.Settings.Util +import Text.Pandoc.CrossRef.Util.Settings.LiftPandoc() +import Language.Haskell.TH +import Language.Haskell.TH.Syntax +import System.FilePath + +embedFile :: FilePath -> Q Exp +embedFile name = + qAddDependentFile fp >> + runIO (readConfig fp) >>= \v -> [|v|] + where fp = "settings" (name <> ".yaml") diff --git a/lib-internal/Text/Pandoc/CrossRef/Util/Settings/LiftPandoc.hs b/lib-internal/Text/Pandoc/CrossRef/Util/Settings/LiftPandoc.hs new file mode 100644 index 00000000..197a5a53 --- /dev/null +++ b/lib-internal/Text/Pandoc/CrossRef/Util/Settings/LiftPandoc.hs @@ -0,0 +1,33 @@ +{-# OPTIONS_GHC -Wno-orphans #-} +{-# LANGUAGE TemplateHaskell, DeriveLift, StandaloneDeriving #-} +module Text.Pandoc.CrossRef.Util.Settings.LiftPandoc where + +import Text.Pandoc.CrossRef.Util.Settings.Types +import Language.Haskell.TH.Syntax (Lift(..)) +import Text.Pandoc +import Data.Map.Internal (Map(..)) + +deriving instance Lift Format +deriving instance Lift ColSpan +deriving instance Lift RowSpan +deriving instance Lift Alignment +deriving instance Lift Cell +deriving instance Lift Row +deriving instance Lift TableFoot +deriving instance Lift ListNumberDelim +deriving instance Lift ListNumberStyle +deriving instance Lift RowHeadColumns +deriving instance Lift TableBody +deriving instance Lift TableHead +deriving instance Lift ColWidth +deriving instance Lift Caption +deriving instance Lift Block +deriving instance Lift Citation +deriving instance Lift CitationMode +deriving instance Lift QuoteType +deriving instance Lift MathType +deriving instance Lift Inline +deriving instance Lift MetaValue +deriving instance (Lift k, Lift v) => Lift (Map k v) +deriving instance Lift Meta +deriving instance Lift Settings diff --git a/lib-internal/Text/Pandoc/CrossRef/Util/Settings/Util.hs b/lib-internal/Text/Pandoc/CrossRef/Util/Settings/Util.hs new file mode 100644 index 00000000..0ac912b9 --- /dev/null +++ b/lib-internal/Text/Pandoc/CrossRef/Util/Settings/Util.hs @@ -0,0 +1,28 @@ +{-# LANGUAGE OverloadedStrings #-} +module Text.Pandoc.CrossRef.Util.Settings.Util where + +import Text.Pandoc.CrossRef.Util.Settings.Types +import System.IO +import qualified Data.Text as T +import Text.Pandoc +import Text.Pandoc.Walk + +readMd :: T.Text -> IO Pandoc +readMd = handleError . runPure . readMarkdown def{ + readerExtensions=disableExtension Ext_auto_identifiers pandocExtensions + } + +readConfig :: FilePath -> IO Settings +readConfig path = do + h <- openFile path ReadMode + hSetEncoding h utf8 + yaml <- hGetContents h + Pandoc meta' _ <- readMd $ T.pack $ unlines ["---", yaml, "---"] + return . normalizeSpaces $ Settings meta' + +normalizeSpaces :: Settings -> Settings +normalizeSpaces (Settings s) = Settings $ walk walkInlines s + where + walkInlines :: Inline -> Inline + walkInlines (Span ("",["s"],[]) []) = Space + walkInlines x = x diff --git a/package.yaml b/package.yaml index 6e02e2b0..56d9d3ca 100644 --- a/package.yaml +++ b/package.yaml @@ -12,6 +12,7 @@ github: lierdakil/pandoc-crossref extra-source-files: - test/*.inc - CHANGELOG.md +- settings/* data-files: - docs/demo/demo.md - docs/index.md @@ -31,6 +32,7 @@ library: - mtl >=1.1 && <2.3 internal-libraries: pandoc-crossref-internal: + ghc-options: -Wall source-dirs: lib-internal dependencies: - mtl >=1.1 && <2.3 @@ -45,6 +47,7 @@ internal-libraries: - directory >=1 && <1.4 - filepath >=1.1 && <1.5 - template-haskell >=2.7.0.0 && <3.0.0.0 + - bytestring flags: enable_flaky_tests: description: Some tests rely on specific behaviour of pandoc, which diff --git a/pandoc-crossref.cabal b/pandoc-crossref.cabal index 03627a99..cf0a5d8e 100644 --- a/pandoc-crossref.cabal +++ b/pandoc-crossref.cabal @@ -4,7 +4,7 @@ cabal-version: 2.0 -- -- see: https://github.com/sol/hpack -- --- hash: a754d86ea092e3ea9812807abc8b57a9f3ce11dfa8658c5dd19c17d475e8e832 +-- hash: cba9cf0aff9fcad7237aceef08988c567a09042d3b738bb7950772c27cecb550 name: pandoc-crossref version: 0.4.0.0 @@ -21,6 +21,10 @@ build-type: Simple extra-source-files: test/demo.inc CHANGELOG.md + settings/chapters.yaml + settings/default.yaml + settings/numberSections.yaml + settings/subfigures.yaml data-files: docs/demo/demo.md docs/index.md @@ -129,9 +133,12 @@ library pandoc-crossref-internal Text.Pandoc.CrossRef.Util.Prefixes.Types Text.Pandoc.CrossRef.Util.Replace Text.Pandoc.CrossRef.Util.Settings + Text.Pandoc.CrossRef.Util.Settings.Embed Text.Pandoc.CrossRef.Util.Settings.Gen + Text.Pandoc.CrossRef.Util.Settings.LiftPandoc Text.Pandoc.CrossRef.Util.Settings.Template Text.Pandoc.CrossRef.Util.Settings.Types + Text.Pandoc.CrossRef.Util.Settings.Util Text.Pandoc.CrossRef.Util.Template Text.Pandoc.CrossRef.Util.Template.Types Text.Pandoc.CrossRef.Util.Util @@ -140,8 +147,10 @@ library pandoc-crossref-internal Paths_pandoc_crossref hs-source-dirs: lib-internal + ghc-options: -Wall build-depends: base >=4.11 && <5 + , bytestring , containers >=0.1 && <0.7 , data-accessor >=0.2.2.6 && <0.3.0.0 , data-accessor-template >=0.2.1.12 && <0.3.0.0 diff --git a/settings/chapters.yaml b/settings/chapters.yaml new file mode 100644 index 00000000..46c2acb2 --- /dev/null +++ b/settings/chapters.yaml @@ -0,0 +1,8 @@ +captionIndexTemplate: $$s.i%.$$$$ri$$ +scope: sec +prefixes: + sec: + title: Chapter + sub: + title: Section + referenceIndexTemplate: $$i$$$$suf$$ diff --git a/settings/default.yaml b/settings/default.yaml new file mode 100644 index 00000000..e1b92559 --- /dev/null +++ b/settings/default.yaml @@ -0,0 +1,45 @@ +codeBlockCaptions: False +adjustSectionIdentifiers: False +autoSectionLabels: sec +titleDelim: ":[]{.s}" +listItemNumberDelim: ".[]{.s}" +rangeDelim: "-" +pairDelim: ",[]{.s}" +lastDelim: ",[]{.s}" +refDelim: ",[]{.s}" +crossrefYaml: "pandoc-crossref.yaml" +linkReferences: False +nameInLink: False +collectedCaptionDelim: ",[]{.s}" +collectedCaptionItemDelim: "[]{.s}--[]{.s}" +# these are merely the defaults, can (and will) be overridden in prefix configs +captionTemplate: "$$title%\u00a0$$$$i$$$$titleDelim$$$$t$$" +captionIndexTemplate: $$ri$$ +referenceTemplate: "$$Ref[n]%\u00a0$$$$rs$$" +listItemTemplate: $$i$$$$listItemNumberDelim$$$$t$$ +collectedCaptionTemplate: $$i$$$$collectedCaptionItemDelim$$$$t$$ +referenceIndexTemplate: $$i$$$$suf$$ +listOfTitle: | + # List of $$title$$s +numbering: arabic +prefixes: + eq: + ref: ["eq.", "eqns."] + captionTemplate: "$$t$$\\\\qquad($$i$$)" + title: Equation + fig: + ref: ["fig.", "figs."] + title: Figure + lst: + ref: ["lst.", "lsts."] + title: Listing + captionPosition: above + tbl: + ref: ["tbl.", "tbls."] + title: Table + sec: + ref: ["sec.", "secs."] + title: Section + captionTemplate: $$t$$ + scope: sec + referenceIndexTemplate: $$s.refi%.$$$$i$$$$suf$$ diff --git a/settings/numberSections.yaml b/settings/numberSections.yaml new file mode 100644 index 00000000..75974129 --- /dev/null +++ b/settings/numberSections.yaml @@ -0,0 +1,4 @@ +prefixes: + sec: + captionIndexTemplate: $$s.i%.$$$$ri$$ + captionTemplate: $$title$$ $$i$$. $$t$$ diff --git a/settings/subfigures.yaml b/settings/subfigures.yaml new file mode 100644 index 00000000..fa3a9f38 --- /dev/null +++ b/settings/subfigures.yaml @@ -0,0 +1,10 @@ +prefixes: + fig: + subcaptions: True + sub: + numbering: alpha a + referenceIndexTemplate: $$s.i$$($$i$$) + listItemTemplate: $$s.i$$($$i$$)$$listItemNumberDelim$$$$t$$ + captionTemplate: $$i$$ + scope: fig + captionIndexTemplate: $$ri$$ From f174256a153a44865dd0e0faa0faf7ed52fa93e9 Mon Sep 17 00:00:00 2001 From: Nikolay Yakimov Date: Sun, 21 Mar 2021 23:04:33 +0300 Subject: [PATCH 129/134] Support variables in prefix/suffix --- .../Text/Pandoc/CrossRef/Util/Template.hs | 24 ++++++++++++------- 1 file changed, 15 insertions(+), 9 deletions(-) diff --git a/lib-internal/Text/Pandoc/CrossRef/Util/Template.hs b/lib-internal/Text/Pandoc/CrossRef/Util/Template.hs index 619a292f..e7ef4f29 100644 --- a/lib-internal/Text/Pandoc/CrossRef/Util/Template.hs +++ b/lib-internal/Text/Pandoc/CrossRef/Util/Template.hs @@ -48,9 +48,10 @@ data PRVar = PRVar { prvName :: T.Text , prvIdx :: [IdxT] } deriving Show data IdxT = IdxVar [PRVar] | IdxStr T.Text | IdxNum T.Text deriving Show +data Sfx = SfxVar [PRVar] | SfxLit T.Text deriving Show data ParseRes = ParseRes { prVar :: [PRVar] - , prPfx :: T.Text - , prSfx :: T.Text + , prPfx :: [Sfx] + , prSfx :: [Sfx] } deriving Show isVariableSym :: Char -> Bool @@ -59,17 +60,19 @@ isVariableSym '_' = True isVariableSym c = isAlphaNum c parse :: ReadP ParseRes -parse = uncurry <$> (ParseRes <$> var) <*> option ("", "") ps <* eof +parse = uncurry <$> (ParseRes <$> var) <*> option ([], []) ps <* eof where var = sepBy1 (PRVar <$> varName <*> many varIdx) (char '?') varName = T.pack <$> munch1 isVariableSym varIdx = between (char '[') (char ']') (IdxVar <$> var <|> IdxStr <$> litStr <|> IdxNum <$> litNum) litStr = T.pack <$> between (char '"') (char '"') (many (satisfy (/='"'))) litNum = T.pack <$> many (satisfy isDigit) - prefix = T.pack <$> (char '#' *> many (satisfy (/='%'))) - suffix = T.pack <$> (char '%' *> many (satisfy (/='#'))) - ps = (flip (,) <$> suffix <*> option "" prefix) - +++ ((,) <$> prefix <*> option "" suffix) + prefix = char '#' *> many (sfx '%') + suffix = char '%' *> many (sfx '#') + sfx stop = between (char '`') (char '`') (SfxVar <$> var) + +++ (SfxLit . T.pack <$> munch1 (`notElem` ['`', stop])) + ps = (flip (,) <$> suffix <*> option [] prefix) + +++ ((,) <$> prefix <*> option [] suffix) instance MakeTemplate Template where type ElemT Template = Inlines @@ -100,8 +103,11 @@ scan = bottomUp . go where go vf (Math DisplayMath var:xs) | ParseRes{..} <- fst . head $ readP_to_S parse $ T.unpack var - = let replaceVar = maybe mempty (modifier . toInlines ("variable " <> var)) - modifier = (<> text prSfx) . (text prPfx <>) + = let replaceVar = replaceVar' ((<> handleSfx prSfx) . (handleSfx prPfx <>)) + replaceVar' m = maybe mempty (m . toInlines ("variable" <> var)) + handleSfx = mconcat . map oneSfx + oneSfx (SfxVar vars) = replaceVar' id (tryVars vars) + oneSfx (SfxLit txt) = text txt tryVar PRVar{..} = case prvIdx of [] -> vf prvName From 65d5d818edfe072bb27aa944aa52567c688623ff Mon Sep 17 00:00:00 2001 From: Nikolay Yakimov Date: Sun, 21 Mar 2021 23:05:11 +0300 Subject: [PATCH 130/134] Tweak numberSections to align better with pandoc-crossref v0.3 --- settings/numberSections.yaml | 8 ++++++-- test/m2m/chapDelim/input.md | 5 +---- test/m2m/emptyChapterLabels/input.md | 7 ------- test/m2m/label-precedence/expect.md | 6 +++--- test/m2m/secLabels/expect.md | 6 +++--- 5 files changed, 13 insertions(+), 19 deletions(-) diff --git a/settings/numberSections.yaml b/settings/numberSections.yaml index 75974129..29036137 100644 --- a/settings/numberSections.yaml +++ b/settings/numberSections.yaml @@ -1,4 +1,8 @@ +chapDelim: . prefixes: sec: - captionIndexTemplate: $$s.i%.$$$$ri$$ - captionTemplate: $$title$$ $$i$$. $$t$$ + captionTemplate: $$i$$ $$t$$ + captionIndexTemplate: $$ri$$ + referenceIndexTemplate: $$i$$$$suf$$ + sub: + captionIndexTemplate: $$s.i$$$$ri#`chapDelim`$$ diff --git a/test/m2m/chapDelim/input.md b/test/m2m/chapDelim/input.md index 0939a336..c6ecbe67 100644 --- a/test/m2m/chapDelim/input.md +++ b/test/m2m/chapDelim/input.md @@ -2,10 +2,7 @@ defaultOption: - numberSections adjustSectionIdentifiers: true -prefixes: - sec: - captionTemplate: $$i$$ $$t$$ - captionIndexTemplate: $$s.i%delim$$$$ri$$ +chapDelim: delim ... # Section diff --git a/test/m2m/emptyChapterLabels/input.md b/test/m2m/emptyChapterLabels/input.md index 6bffe3bb..a3cbaa99 100644 --- a/test/m2m/emptyChapterLabels/input.md +++ b/test/m2m/emptyChapterLabels/input.md @@ -2,13 +2,6 @@ defaultOption: - numberSections adjustSectionIdentifiers: true -prefixes: - sec: - captionTemplate: $$i$$ $$t$$ - captionIndexTemplate: $$ri$$ - referenceIndexTemplate: $$i$$$$suf$$ - sub: - captionIndexTemplate: $$s.i$$$$ri#.$$ ... # Section diff --git a/test/m2m/label-precedence/expect.md b/test/m2m/label-precedence/expect.md index 8960b049..b2e85555 100644 --- a/test/m2m/label-precedence/expect.md +++ b/test/m2m/label-precedence/expect.md @@ -1,15 +1,15 @@ -# Section \*. First Section {#first-section label="*"} +# \* First Section {#first-section label="*"} text ![Figure α: A figure](image.png){#fig:fig1} -## Section \*.A. Subsection {#subsection} +## \*.A Subsection {#subsection} other text ![Figure +: A figure with custom label](image.png){#fig:fig2 label="+"} -### Section \*.A.A. Subsubsection {#subsubsection} +### \*.A.A Subsubsection {#subsubsection} text text text diff --git a/test/m2m/secLabels/expect.md b/test/m2m/secLabels/expect.md index f50cc08e..31a7a8eb 100644 --- a/test/m2m/secLabels/expect.md +++ b/test/m2m/secLabels/expect.md @@ -1,10 +1,10 @@ -# Section a. First Level Section {#first-level-section} +# a First Level Section {#first-level-section} -## Section a.a. Second Level Section {#second-level-section} +## a.a Second Level Section {#second-level-section} ![Figure a: my figure](myfig.png){#fig:myfig} -## Section a.b. Other Second Level Section {#other-second-level-section} +## a.b Other Second Level Section {#other-second-level-section} ::: {#tbl:mytable} a b c From c67fd2d05445608c0e15564db7ac926d15fe2f66 Mon Sep 17 00:00:00 2001 From: Nikolay Yakimov Date: Sun, 21 Mar 2021 23:36:54 +0300 Subject: [PATCH 131/134] Add `titleSections` option; fix demo.md --- docs/demo/demo.md | 7 ++++--- lib-internal/Text/Pandoc/CrossRef/Util/Settings.hs | 1 + settings/titleSections.yaml | 3 +++ 3 files changed, 8 insertions(+), 3 deletions(-) create mode 100644 settings/titleSections.yaml diff --git a/docs/demo/demo.md b/docs/demo/demo.md index 3b49a70a..bf54e119 100644 --- a/docs/demo/demo.md +++ b/docs/demo/demo.md @@ -3,9 +3,10 @@ codeBlockCaptions: True adjustSectionIdentifiers: True autoFigLabels: fig defaultOption: - - numberSections - - chapters - - subfigures +- numberSections +- titleSections +- chapters +- subfigures title: pandoc-crossref demo document --- diff --git a/lib-internal/Text/Pandoc/CrossRef/Util/Settings.hs b/lib-internal/Text/Pandoc/CrossRef/Util/Settings.hs index 4a7cd4ac..8ef87462 100644 --- a/lib-internal/Text/Pandoc/CrossRef/Util/Settings.hs +++ b/lib-internal/Text/Pandoc/CrossRef/Util/Settings.hs @@ -63,5 +63,6 @@ defaultMeta userSettings name2set "chapters" = $(embedFile "chapters") name2set "subfigures" = $(embedFile "subfigures") name2set "numberSections" = $(embedFile "numberSections") + name2set "titleSections" = $(embedFile "titleSections") name2set x = error . T.unpack $ "Unknown defaultOption value: " <> x basicMeta = $(embedFile "default") diff --git a/settings/titleSections.yaml b/settings/titleSections.yaml new file mode 100644 index 00000000..11ee2fa7 --- /dev/null +++ b/settings/titleSections.yaml @@ -0,0 +1,3 @@ +prefixes: + sec: + captionTemplate: $$title$$ $$i$$. $$t$$ From 1e8bc6599a02a9b2474debab4dd5b2dd11aead1c Mon Sep 17 00:00:00 2001 From: Nikolay Yakimov Date: Mon, 22 Mar 2021 15:42:24 +0300 Subject: [PATCH 132/134] [CI] do not fail-fast --- .github/workflows/haskell.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.github/workflows/haskell.yml b/.github/workflows/haskell.yml index 06312119..d756eb9b 100644 --- a/.github/workflows/haskell.yml +++ b/.github/workflows/haskell.yml @@ -5,6 +5,7 @@ on: [push] jobs: build: strategy: + fail-fast: false matrix: os: [ubuntu-latest, macos-latest, windows-latest] pandocver: ["2.13"] From d613fc2da3f25a3ba27b61fefffdc8f0302e9459 Mon Sep 17 00:00:00 2001 From: Nikolay Yakimov Date: Mon, 22 Mar 2021 16:07:24 +0300 Subject: [PATCH 133/134] Update cabalfile --- pandoc-crossref.cabal | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/pandoc-crossref.cabal b/pandoc-crossref.cabal index cf0a5d8e..1f080bfb 100644 --- a/pandoc-crossref.cabal +++ b/pandoc-crossref.cabal @@ -4,7 +4,7 @@ cabal-version: 2.0 -- -- see: https://github.com/sol/hpack -- --- hash: cba9cf0aff9fcad7237aceef08988c567a09042d3b738bb7950772c27cecb550 +-- hash: 031e4b85f89a0c982d26b289cc24dc3f6810e028780b70f70b9e08556bb67223 name: pandoc-crossref version: 0.4.0.0 @@ -25,6 +25,7 @@ extra-source-files: settings/default.yaml settings/numberSections.yaml settings/subfigures.yaml + settings/titleSections.yaml data-files: docs/demo/demo.md docs/index.md From 179d8bdd23d2df8ae8a38dedc475a3ef0eec3676 Mon Sep 17 00:00:00 2001 From: Nikolay Yakimov Date: Mon, 22 Mar 2021 16:36:48 +0300 Subject: [PATCH 134/134] [CI] Try nuking the cache --- .github/workflows/haskell.yml | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/.github/workflows/haskell.yml b/.github/workflows/haskell.yml index d756eb9b..8ef84139 100644 --- a/.github/workflows/haskell.yml +++ b/.github/workflows/haskell.yml @@ -39,11 +39,11 @@ jobs: - uses: actions/cache@v2 with: path: .cabal-store - key: r2-${{runner.os}}-${{matrix.ghcver}}-${{matrix.pandocver}}-${{hashFiles('pandoc-crossref.cabal')}}-${{hashFiles('dist-newstyle/cache/plan.json')}} + key: r3-${{runner.os}}-${{matrix.ghcver}}-${{matrix.pandocver}}-${{hashFiles('pandoc-crossref.cabal')}}-${{hashFiles('dist-newstyle/cache/plan.json')}} restore-keys: | - r2-${{runner.os}}-${{matrix.ghcver}}-${{matrix.pandocver}}-${{hashFiles('pandoc-crossref.cabal')}}-${{hashFiles('dist-newstyle/cache/plan.json')}} - r2-${{runner.os}}-${{matrix.ghcver}}-${{matrix.pandocver}}-${{hashFiles('pandoc-crossref.cabal')}} - r2-${{runner.os}}-${{matrix.ghcver}}-${{matrix.pandocver}} + r3-${{runner.os}}-${{matrix.ghcver}}-${{matrix.pandocver}}-${{hashFiles('pandoc-crossref.cabal')}}-${{hashFiles('dist-newstyle/cache/plan.json')}} + r3-${{runner.os}}-${{matrix.ghcver}}-${{matrix.pandocver}}-${{hashFiles('pandoc-crossref.cabal')}} + r3-${{runner.os}}-${{matrix.ghcver}}-${{matrix.pandocver}} - shell: bash run: | rm -rvf .cabal-store/ghc-${{matrix.ghcver}}/pandoc-crossref-*