@@ -91,6 +91,7 @@ instance Default WriterEnv
9191
9292data WriterState = WriterState { stNotes :: Notes
9393 , stRefs :: Refs
94+ , stKeys :: Set.Set Key
9495 , stIds :: Set.Set String
9596 , stNoteNum :: Int
9697 }
@@ -98,6 +99,7 @@ data WriterState = WriterState { stNotes :: Notes
9899instance Default WriterState
99100 where def = WriterState{ stNotes = []
100101 , stRefs = []
102+ , stKeys = Set.empty
101103 , stIds = Set.empty
102104 , stNoteNum = 1
103105 }
@@ -798,19 +800,21 @@ getKey = toKey . render Nothing
798800-- Prefer label if possible; otherwise, generate a unique key.
799801getReference :: PandocMonad m => Attr -> Doc -> Target -> MD m Doc
800802getReference attr label target = do
801− st <- get
802− let keys = map (\(l,_,_) -> getKey l) (stRefs st)
803− case find (\(_,t,a) -> t == target && a == attr) (stRefs st) of
803+ refs <- gets stRefs
804+ case find (\(_,t,a) -> t == target && a == attr) refs of
804805 Just (ref, _, _) -> return ref
805806 Nothing -> do
806− label' <- case getKey label `elem` keys of
807− True -> -- label is used; generate numerical label
808− case find (\n -> Key n `notElem` keys) $
809− map show [1..(10000 :: Integer)] of
810− Just x -> return $ text x
811− Nothing -> throwError $ PandocSomeError "no unique label"
812− False -> return label
813− modify (\s -> s{ stRefs = (label', target, attr) : stRefs st })
807+ keys <- gets stKeys
808+ label' <- if isEmpty label || getKey label `Set.member` keys
809+ then case find (\n -> not (Key n `Set.member` keys)) $
810+ map show [1..(10000 :: Integer)] of
811+ Just x -> return $ text x
812+ Nothing ->
813+ throwError $ PandocSomeError "no unique label"
814+ else return label
815+ modify (\s -> s{ stRefs = (label', target, attr) : stRefs s,
816+ stKeys = Set.insert (getKey label') (stKeys s)
817+ })
814818 return label'
815819
816820-- | Convert list of Pandoc inline elements to markdown.