diff --git a/README.md b/README.md
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# pandoc-crossref filter [![Build Status](https://travis-ci.org/lierdakil/pandoc-crossref.svg?branch=master)](https://travis-ci.org/lierdakil/pandoc-crossref)
+# pandoc-crossref filter [![Build Status](https://travis-ci.org/lierdakil/pandoc-crossref.svg?branch=master)](https://travis-ci.org/lierdakil/pandoc-crossref) [![Build status](https://ci.appveyor.com/api/projects/status/v04mfbglpcdqfln4/branch/master?svg=true)](https://ci.appveyor.com/project/lierdakil/pandoc-crossref/branch/master)
 
 pandoc-crossref is a pandoc filter for numbering figures, equations, tables and cross-references to them.
 
@@ -188,6 +188,20 @@
 
 WARNING: With LaTeX output, you have to invoke pandoc with `--number-sections`, otherwise section labels won't work. It's also advised with other output formats, since with no numbers in section titles, it would be hard to navigate anyway.
 
+#### Section numbering
+
+Pandoc doesn't properly support numbering sections in some output formats, and section reference labels (see below).
+
+You can let pandoc-crossref handle section numbering instedad. This is done via `numberSections` and `sectionsDepth` metadata options.
+
+`numberSections` controls if pandoc-crossref handles numbering sections, while `sectionsDepth` controls what sections are numbered.
+
+Set `sectionsDepth` to `0` to make section numbering consistent with `chaptersDepth`.
+
+If `sectionsDepth` value is lesser than `0`, all sections will be numbered.
+
+Otherwise, only header levels up to and including `sectionsDepth` will be numbered.
+
 ### Section reference labels
 
 ***Not currently supported with LaTeX output***
@@ -277,6 +291,24 @@
 
 You can capitalize first reference character to get capitalized prefix, e.g. `[@Fig:label1]` will produce `Fig. ...` by default. Capitalized prefixes are derived automatically by capitalizing first letter of every word in non-capitalized prefix, unless overriden with metadata settings. See [Customization](#customization) for more information.
 
+#### Linking references
+
+To make references into hyperlinks to referenced element, enable `linkReferences` metadata option. This has no effect on LaTeX output, since in this case, hyperlinking references is handled with `hyperref` LaTeX package.
+
+#### Custom prefix per-reference
+
+It's possible to provide your own prefix per-reference, f.ex. `[Prefix @reference]` will replace default prefix (`fig.`/`sec.`/etc) with prefix verbatim, e.g. `[Prefix @fig:1]` will be rendered as `Prefix 1` instead of `fig. 1`.
+
+In citation group, citations with the same prefix will be grouped. So, for example `[A @fig:1; A @fig:2; B @fig:3]` will turn into `A 1, 2, B 3`. It can be used to an advantage, although it's a bit more cumbersome than it should be, e.g. `[Appendices @sec:A1; Appendices @sec:A2; Appendices @sec:A3]` will turn into `Appendices @A1-@A3` (with `@A1` and `@A3` being relevant section numbers). Note that non-contiguous sequences of identical prefixes *will not* be grouped.
+
+***Not supported with cleferef LaTeX output.***
+
+#### Prefix suppression
+
+Prepending `-` before `@`, like so `[-@citation]`, will suppress default prefix, e.g. `[-@fig:1]` will produce just `1` (or whatever number it happens to be) without `fig.` prefix.
+
+In citation group, citations with and without prefixes will be in different groups. So `[-@fig:1; @fig:2; -@fig:3]` will be rendered as `1, fig. 2, 3`, so be careful with this feature. Again, non-contiguous sequences are not grouped together.
+
 ### Lists
 
 It's possible to use raw latex commands `\listoffigures`, `\listoftables` and `listoflistings`, which will produce ordered list of figure/table/listings titles, in order of appearance in document.
@@ -325,6 +357,11 @@
 * `cref`: if True, latex export will use `\cref` from cleveref package. Only relevant for LaTeX output. `\usepackage{cleveref}` will be automatically added to `header-includes`.
 * `chapters`: if True, number elements as `chapter.item`, and restart `item` on each first-level heading (as `--chapters` for latex/pdf output)
 * `chaptersDepth`, default `1`: header level to treat as "chapter". If `chaptersDepth>1`, then items will be prefixed with several numbers, corresponding to header numbers, e.g. `fig. 1.4.3`.
+* `numberSections`, default `false`: if True, pandoc-crossref will prepend section number to section titles (as counted by pandoc-crossref itself).
+* `sectionsDepth`, default `0`:
+    - sectionsDepth < 0 -- number all sections
+    - sectionsDepth == 0 -- be consistent with `chaptersDepths`
+    - sectionsDepth > 0 -- number section levels up to and including `sectionsDepth`
 * `listings`: if True, generate code blocks for `listings` package. Only relevant for LaTeX output. `\usepackage{listings}` will be automatically added to `header-includes`. You need to specify `--listings` option as well.
 * `codeBlockCaptions`: if True, parse table-style code block captions.
 * `autoSectionLabels`, default `false`: Automatically prefix all section labels with `sec:`. Note that this messes with pandoc's automatic header references.
@@ -361,6 +398,7 @@
 * `secPrefix`, default `sec.`, `secs.`: Prefix for references to sections, e.g. `secs. 2,5`
 * `chapDelim`, default `.`: Delimiter between chapter number and item number.
 * `rangeDelim`, default `-`: Delimiter between reference ranges, e.g. `eq. 2-5`
+* `linkReferences`, default `false`: Make references hyperlinks to the referenced element
 
 `figPrefix`, `eqnPrefix`, `tblPrefix`, `lstPrefix` can be YAML arrays. That way, value at index corresponds to total number of references in group, f.ex.
 
@@ -418,6 +456,8 @@
 * `tblPrefixTemplate`, defualt `\\[p\\]&nbsp;\\[i\\]` -- table reference template
 * `lstPrefixTemplate`, defualt `\\[p\\]&nbsp;\\[i\\]` -- listing reference template
 * `secPrefixTemplate`, defualt `\\[p\\]&nbsp;\\[i\\]` -- section reference template
+* `refIndexTemplate`, default `\\[i\\]\\[suf\\]` -- individual reference index template
+* `subfigureRefIndexTemplate`, default `\\[i\\]\\[suf\\] (\\[s\\])` -- subfigure reference index template
 
 #### LaTeX customization
 
@@ -451,7 +491,12 @@
 
 * `i` -- object number, possibly with chapter number (if `chapter=True`)
 * `t` -- object caption, as given in source Markdown
+
+Also there is a number of specific variables that are meaningful only in certain contexts:
+
 * `ccs` -- collected subfigure captions. Only applicable to `subfigureTemplate`. Collected captions will be separated by `ccsDelim` and individual captions will be printed with `ccsTemplate`. See [Subfigures](#subfigures)
+* `suf` -- reference suffix, applicable to `refIndexTemplate`, `subfigureRefIndexTemplate`
+* `s` -- subfigure index, applicable to `subfigureRefIndexTemplate`
 
 `xPrefixTemplate`, where `x` is `fig`, `eqn`, etc, are a special case. Those don't have `t` variable, since there is no caption in source markdown, but instead have `p` variable, that binds to relevant `xPrefix`. This is done this way, since actual prefix vaule can depend on `i`.
 
diff --git a/lib/Text/Pandoc/CrossRef/References/Blocks.hs b/lib/Text/Pandoc/CrossRef/References/Blocks.hs
--- a/lib/Text/Pandoc/CrossRef/References/Blocks.hs
+++ b/lib/Text/Pandoc/CrossRef/References/Blocks.hs
@@ -24,7 +24,7 @@
 
 replaceAll :: (Data a) => Options -> a -> WS a
 replaceAll opts =
-    runReplace (mkM (replaceBlock opts) `extM` replaceInline opts)
+    runReplace (mkRR (replaceBlock opts) `extRR` replaceInline opts)
   . runSplitMath
   . everywhere (mkT divBlocks `extT` spanInlines opts)
   where
@@ -33,7 +33,7 @@
                  = everywhere (mkT splitMath)
                  | otherwise = id
 
-replaceBlock :: Options -> Block -> WS Block
+replaceBlock :: Options -> Block -> WS (ReplacedResult Block)
 replaceBlock opts (Header n (label, cls, attrs) text')
   = do
     let label' = if autoSectionLabels opts && not ("sec:" `isPrefixOf` label)
@@ -55,15 +55,22 @@
         , refTitle=normalizeSpaces text'
         , refSubfigure = Nothing
         }
-        return ()
-    return $ Header n (label', cls, attrs) text'
+    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'
+               | 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 (mkM $ replaceSubfigs opts') $ init images) def
+    let (cont, st) = runState (runReplace (mkRR $ replaceSubfigs opts') $ init images) def
         collectedCaptions =
             intercalate (ccsDelim opts)
           $ map (collectCaps . snd)
@@ -90,14 +97,14 @@
           $ imgRefs_ st)
     case outFormat opts of
           f | isFormat "latex" f ->
-            return $ Div nullAttr $
+            replaceNoRecurse $ Div nullAttr $
               [ RawBlock (Format "tex") "\\begin{figure}" ]
               ++ cont ++
               [ Para [RawInline (Format "tex") "\\caption"
                        , Span nullAttr caption]
               , RawBlock (Format "tex") $ mkLaTeXLabel label
               , RawBlock (Format "tex") "\\end{figure}"]
-          _  -> return $ Div (label, "subfigures":cls, attrs) $ toTable cont capt
+          _  -> replaceNoRecurse $ Div (label, "subfigures":cls, attrs) $ toTable cont capt
   where
     opts' = opts
               { figureTemplate = subfigureChildTemplate opts
@@ -105,8 +112,8 @@
               }
     toTable :: [Block] -> [Inline] -> [Block]
     toTable blks capt
-      | subfigGrid opts = [Table [] align widths [] $ map blkToRow blks, Para capt]
-      | otherwise = blks ++ [Para 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"
@@ -136,7 +143,7 @@
         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,_,attrs) [Table title align widths header cells])
+replaceBlock opts (Div divOps@(label,_,attrs) [Table title align widths header cells])
   | not $ null title
   , "tbl:" `isPrefixOf` label
   = do
@@ -146,7 +153,7 @@
               f | isFormat "latex" f ->
                 RawInline (Format "tex") (mkLaTeXLabel label) : title
               _  -> applyTemplate idxStr title $ tableTemplate opts
-    return $ Table title' align widths header cells
+    replaceNoRecurse $ Div divOps [Table title' align widths header cells]
 replaceBlock opts cb@(CodeBlock (label, classes, attrs) code)
   | not $ null label
   , "lst:" `isPrefixOf` label
@@ -154,10 +161,10 @@
   = case outFormat opts of
       f
         --if used with listings package,nothing shoud be done
-        | isFormat "latex" f, listings opts -> return cb
+        | isFormat "latex" f, listings opts -> noReplaceNoRecurse
         --if not using listings, however, wrap it in a codelisting environment
         | isFormat "latex" f ->
-          return $ Div nullAttr [
+          replaceNoRecurse $ Div nullAttr [
               RawBlock (Format "tex")
                 $ "\\begin{codelisting}\n\\caption{"++caption++"}"
             , cb
@@ -167,8 +174,8 @@
         let cap = toList $ text caption
         idxStr <- replaceAttr opts (Right label) (lookup "label" attrs) cap lstRefs
         let caption' = applyTemplate idxStr cap $ listingTemplate opts
-        return $ Div (label, "listing":classes, []) [
-            Para caption'
+        replaceNoRecurse $ Div (label, "listing":classes, []) [
+            mkCaption opts "Caption" caption'
           , CodeBlock ([], classes, attrs \\ [("caption", caption)]) code
           ]
 replaceBlock opts
@@ -180,10 +187,10 @@
       f
         --if used with listings package, return code block with caption
         | isFormat "latex" f, listings opts ->
-          return $ CodeBlock (label,classes,("caption",stringify caption):attrs) code
+          replaceNoRecurse $ CodeBlock (label,classes,("caption",stringify caption):attrs) code
         --if not using listings, however, wrap it in a codelisting environment
         | isFormat "latex" f ->
-          return $ Div nullAttr [
+          replaceNoRecurse $ Div nullAttr [
               RawBlock (Format "tex") "\\begin{codelisting}"
             , Para [
                 RawInline (Format "tex") "\\caption"
@@ -195,8 +202,8 @@
       _ -> do
         idxStr <- replaceAttr opts (Right label) (lookup "label" attrs) caption lstRefs
         let caption' = applyTemplate idxStr caption $ listingTemplate opts
-        return $ Div (label, "listing":classes, []) [
-            Para caption'
+        replaceNoRecurse $ Div (label, "listing":classes, []) [
+            mkCaption opts "Caption" caption'
           , CodeBlock ([], classes, attrs) code
           ]
 replaceBlock opts (Para [Span attrs [Math DisplayMath eq]])
@@ -204,8 +211,8 @@
   , tableEqns opts
   = do
     (eq', idx) <- replaceEqn opts attrs eq
-    return $ Table [] [AlignCenter, AlignRight] [0.9, 0.09] [] [[[Plain [Math DisplayMath eq']], [Plain [Math DisplayMath $ "(" ++ idx ++ ")"]]]]
-replaceBlock _ x = return x
+    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
@@ -216,16 +223,16 @@
           | otherwise = eq++"\\qquad("++stringify idxStr++")"
   return (eq', stringify idxStr)
 
-replaceInline :: Options -> Inline -> WS Inline
+replaceInline :: Options -> Inline -> WS (ReplacedResult Inline)
 replaceInline opts (Span attrs@(label,_,_) [Math DisplayMath eq])
   | "eq:" `isPrefixOf` label || null label && autoEqnLabels opts
   = case outFormat opts of
       f | isFormat "latex" f ->
         let eqn = "\\begin{equation}"++eq++mkLaTeXLabel label++"\\end{equation}"
-        in return $ RawInline (Format "tex") eqn
+        in replaceNoRecurse $ RawInline (Format "tex") eqn
       _ -> do
         (eq', _) <- replaceEqn opts attrs eq
-        return $ Math DisplayMath eq'
+        replaceNoRecurse $ Span attrs [Math DisplayMath eq']
 replaceInline opts (Image attr@(label,_,attrs) alt img@(_, tit))
   | "fig:" `isPrefixOf` label && "fig:" `isPrefixOf` tit
   = do
@@ -233,11 +240,11 @@
     let alt' = case outFormat opts of
           f | isFormat "latex" f -> alt
           _  -> applyTemplate idxStr alt $ figureTemplate opts
-    return $ Image attr alt' img
-replaceInline _ x = return x
+    replaceNoRecurse $ Image attr alt' img
+replaceInline _ _ = noReplaceRecurse
 
-replaceSubfigs :: Options -> [Inline] -> WS [Inline]
-replaceSubfigs opts = fmap 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))
@@ -299,7 +306,7 @@
 replaceAttr o label refLabel title prop
   = do
     chap  <- take (chaptersDepth o) `fmap` get curChap
-    i     <- (1+) `fmap` (M.size . M.filter (ap ((&&) . (chap ==) . init . refIndex) (isNothing . refSubfigure)) <$> get prop)
+    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)]
         label' = either (++ ':':show index) id label
     hasLabel <- M.member label' <$> get prop
@@ -331,3 +338,8 @@
       , [Span nullAttr $ img:texlabel]
       ]
 latexSubFigure x _ = [x]
+
+mkCaption :: Options -> String -> [Inline] -> Block
+mkCaption opts style
+  | outFormat opts == Just (Format "docx") = Div ([], [], [("custom-style", style)]) . return . Para
+  | otherwise = Para
diff --git a/lib/Text/Pandoc/CrossRef/References/Refs.hs b/lib/Text/Pandoc/CrossRef/References/Refs.hs
--- a/lib/Text/Pandoc/CrossRef/References/Refs.hs
+++ b/lib/Text/Pandoc/CrossRef/References/Refs.hs
@@ -5,6 +5,7 @@
 import Text.Pandoc.Shared (normalizeInlines, normalizeSpaces)
 import Control.Monad.State hiding (get, modify)
 import Data.List
+import qualified Data.List.HT as HT
 import Data.Maybe
 import Data.Function
 import qualified Data.Map as M
@@ -82,7 +83,15 @@
     all (p `isPrefixOf`) $ map (uncapitalizeFirst . citationId) cits
 
 replaceRefsLatex :: String -> Options -> [Citation] -> WS [Inline]
-replaceRefsLatex prefix opts cits =
+replaceRefsLatex prefix opts cits
+  | cref opts
+  = replaceRefsLatex' prefix opts cits
+  | otherwise
+  = normalizeInlines . intercalate [Str ",", Space] <$>
+      mapM (replaceRefsLatex' prefix opts) (groupBy citationGroupPred cits)
+
+replaceRefsLatex' :: String -> Options -> [Citation] -> WS [Inline]
+replaceRefsLatex' prefix opts cits =
   return $ p [texcit]
   where
     texcit =
@@ -91,10 +100,17 @@
         cref'++"{"++listLabels prefix "" "," "" cits++"}"
         else
           listLabels prefix "\\ref{" ", " "}" cits
+    suppressAuthor = all (==SuppressAuthor) $ map citationMode cits
+    noPrefix = all null $ map citationPrefix cits
     p | cref opts = id
-      | otherwise = getRefPrefix opts prefix cap (length cits - 1)
+      | suppressAuthor
+      = id
+      | noPrefix
+      = getRefPrefix opts prefix cap (length cits - 1)
+      | otherwise = ((citationPrefix (head cits) ++ [Space]) ++)
     cap = maybe False isFirstUpper $ getLabelPrefix . citationId . head $ cits
-    cref' | cap = "\\Cref"
+    cref' | suppressAuthor = "\\labelcref"
+          | cap = "\\Cref"
           | otherwise = "\\cref"
 
 listLabels :: String -> String -> String -> String -> [Citation] -> String
@@ -111,48 +127,90 @@
   where p = (++ ":") . takeWhile (/=':') $ lab
 
 replaceRefsOther :: String -> Options -> [Citation] -> WS [Inline]
-replaceRefsOther prefix opts cits = do
+replaceRefsOther prefix opts cits =
+  normalizeInlines . intercalate [Str ",", Space] <$>
+    mapM (replaceRefsOther' prefix opts) (groupBy citationGroupPred cits)
+
+citationGroupPred :: Citation -> Citation -> Bool
+citationGroupPred = (==) `on` liftM2 (,) citationPrefix citationMode
+
+replaceRefsOther' :: String -> Options -> [Citation] -> WS [Inline]
+replaceRefsOther' prefix opts cits = do
   indices <- mapM (getRefIndex prefix opts) cits
   let
-    indices' = groupBy ((==) `on` (fmap init . fst)) (sort indices)
     cap = maybe False isFirstUpper $ getLabelPrefix . citationId . head $ cits
-  return $ normalizeInlines $ getRefPrefix opts prefix cap (length cits - 1) $ intercalate [Str ",", Space]  (makeIndices opts `map` indices')
+    writePrefix | all (==SuppressAuthor) $ map citationMode cits
+                = id
+                | all null $ map citationPrefix cits
+                = getRefPrefix opts prefix cap (length cits - 1)
+                | otherwise
+                = ((citationPrefix (head cits) ++ [Space]) ++)
+  return $ normalizeInlines $ writePrefix (makeIndices opts indices)
 
-getRefIndex :: String -> Options -> Citation -> WS (Maybe Index, [Inline])
-getRefIndex prefix opts Citation{citationId=cid,citationSuffix=suf}
+data RefData = RefData { rdLabel :: String
+                       , rdIdx :: Maybe Index
+                       , rdSubfig :: Maybe Index
+                       , rdSuffix :: [Inline]
+                       } deriving (Eq)
+
+instance Ord RefData where
+  (<=) = (<=) `on` rdIdx
+
+getRefIndex :: String -> Options -> Citation -> WS RefData
+getRefIndex prefix _opts Citation{citationId=cid,citationSuffix=suf}
   = do
     ref <- M.lookup lab <$> get prop
-    let sub = join $ refSubfigure <$> ref
+    let sub = refSubfigure <$> ref
         idx = refIndex <$> ref
-        suf' | Just sub' <- sub =
-                    suf
-                ++  [Space, Str "("]
-                ++  makeIndices opts [(Just sub',[])]
-                ++  [Str ")"]
-             | otherwise = suf
-    return (idx ,suf')
+    return RefData
+      { rdLabel = lab
+      , rdIdx = idx
+      , rdSubfig = join sub
+      , rdSuffix = suf
+      }
   where
   prop = lookupUnsafe prefix accMap
   lab = prefix ++ getLabelWithoutPrefix cid
 
-makeIndices :: Options -> [(Maybe Index, [Inline])] -> [Inline]
-makeIndices _ s | any (isNothing . fst) s = [Strong [Str "??"]]
-makeIndices o s = intercalate sep $ reverse $ map f $ foldl' f2 [] $ map (A.first fromJust) $ filter (isJust . fst) s
+makeIndices :: Options -> [RefData] -> [Inline]
+makeIndices o s = intercalate sep $ map f $ HT.groupBy g $ sort $ nub s
   where
-  f2 :: [[(Index, [Inline])]] -> (Index, [Inline]) -> [[(Index, [Inline])]]
-  f2 [] (i,suf) = [[(i,suf)]]
-  f2 ([]:xs) (i,suf) = [(i,suf)]:xs
-  f2 l@(x@((ix,sufp):_):xs) (i,suf)
-    | not (null suf) || not (null sufp) = [(i,suf)]:l
-    | ni-hx == 0 = l        -- remove duplicates
-    | ni-hx == 1 = ((i,[]):x):xs -- group sequental
-    | otherwise     = [(i,[])]:l    -- new group
-    where
-      hx = fst $ last ix
-      ni = fst $ last i
+  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)
+          )
+  follows :: Index -> Index -> Bool
+  follows a b
+    | Just (ai, al) <- HT.viewR a
+    , Just (bi, bl) <- HT.viewR b
+    = ai == bi && A.first (+1) bl == al
+  follows _ _ = False
+  f :: [RefData] -> [Inline]
   f []  = []                          -- drop empty lists
   f [w] = show' w                    -- single value
-  f [w1,w2] = show' w2 ++ sep ++ show' w1 -- two values
-  f (x:xs) = show' (last xs) ++ rangeDelim o ++ show' x -- shorten more than two values
+  f [w1,w2] = show' w1 ++ sep ++ show' w2 -- two values
+  f (x:xs) = show' x ++ rangeDelim o ++ show' (last xs) -- shorten more than two values
   sep = [Str ",", Space]
-  show' (i,suf) = chapPrefix (chapDelim o) i ++ suf
+  show' :: RefData -> [Inline]
+  show' RefData{rdLabel=l, rdIdx=Just i, rdSubfig = sub, rdSuffix = suf}
+    | linkReferences o = [Link nullAttr txt ('#':l,[])]
+    | 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} = Strong [Str $ "¿" ++ l ++ "?"] : suf
diff --git a/lib/Text/Pandoc/CrossRef/Util/Options.hs b/lib/Text/Pandoc/CrossRef/Util/Options.hs
--- a/lib/Text/Pandoc/CrossRef/Util/Options.hs
+++ b/lib/Text/Pandoc/CrossRef/Util/Options.hs
@@ -7,6 +7,8 @@
                        , listings :: Bool
                        , codeBlockCaptions  :: Bool
                        , autoSectionLabels  :: Bool
+                       , numberSections  :: Bool
+                       , sectionsDepth  :: Int
                        , figPrefix   :: Bool -> Int -> [Inline]
                        , eqnPrefix   :: Bool -> Int -> [Inline]
                        , tblPrefix   :: Bool -> Int -> [Inline]
@@ -17,6 +19,8 @@
                        , tblPrefixTemplate :: Template
                        , lstPrefixTemplate :: Template
                        , secPrefixTemplate :: Template
+                       , refIndexTemplate :: Template
+                       , subfigureRefIndexTemplate :: Template
                        , chapDelim   :: [Inline]
                        , rangeDelim  :: [Inline]
                        , lofTitle    :: [Block]
@@ -35,4 +39,5 @@
                        , tableEqns :: Bool
                        , autoEqnLabels :: Bool
                        , subfigGrid :: Bool
+                       , linkReferences :: Bool
                        }
diff --git a/lib/Text/Pandoc/CrossRef/Util/Settings.hs b/lib/Text/Pandoc/CrossRef/Util/Settings.hs
--- a/lib/Text/Pandoc/CrossRef/Util/Settings.hs
+++ b/lib/Text/Pandoc/CrossRef/Util/Settings.hs
@@ -25,6 +25,8 @@
   <> listings False
   <> codeBlockCaptions False
   <> autoSectionLabels False
+  <> numberSections False
+  <> sectionsDepth "0"
   <> figLabels "arabic"
   <> eqnLabels "arabic"
   <> tblLabels "arabic"
@@ -46,6 +48,8 @@
   <> 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")
@@ -63,4 +67,5 @@
   <> tableEqns False
   <> autoEqnLabels False
   <> subfigGrid False
+  <> linkReferences False
   where var = displayMath
diff --git a/lib/Text/Pandoc/CrossRef/Util/Util.hs b/lib/Text/Pandoc/CrossRef/Util/Util.hs
--- a/lib/Text/Pandoc/CrossRef/Util/Util.hs
+++ b/lib/Text/Pandoc/CrossRef/Util/Util.hs
@@ -32,12 +32,44 @@
 chapPrefix :: [Inline] -> Index -> [Inline]
 chapPrefix delim index = intercalate delim (map (return . Str . uncurry (fromMaybe . show)) index)
 
-runReplace :: (Monad m) => GenericM m -> GenericM m
+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
-  x' <- f x
-  if x' `geq` x
-  then gmapM (runReplace f) x'
-  else return x'
+  res <- f 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
+
+mkRR :: (Monad m, Typeable a, Typeable b)
+     => (b -> m (ReplacedResult b))
+     -> (a -> m (ReplacedResult a))
+mkRR = extRR (const noReplaceRecurse)
+
+extRR :: ( Monad m, Typeable a, Typeable b)
+     => (a -> m (ReplacedResult a))
+     -> (b -> m (ReplacedResult b))
+     -> (a -> m (ReplacedResult a))
+extRR def' ext = unRR (RR def' `ext0` RR ext)
+
+replaceRecurse :: Monad m => a -> m (ReplacedResult a)
+replaceRecurse = return . Replaced True
+
+replaceNoRecurse :: Monad m => a -> m (ReplacedResult a)
+replaceNoRecurse = return . Replaced False
+
+noReplace :: Monad m => Bool -> m (ReplacedResult a)
+noReplace recurse = return $ NotReplaced recurse
+
+noReplaceRecurse :: Monad m => m (ReplacedResult a)
+noReplaceRecurse = noReplace True
+
+noReplaceNoRecurse :: Monad m => m (ReplacedResult a)
+noReplaceNoRecurse = noReplace False
 
 mkLaTeXLabel :: String -> String
 mkLaTeXLabel l
diff --git a/pandoc-crossref.cabal b/pandoc-crossref.cabal
--- a/pandoc-crossref.cabal
+++ b/pandoc-crossref.cabal
@@ -2,7 +2,7 @@
 -- documentation, see http://haskell.org/cabal/users-guide/
 
 name:                pandoc-crossref
-version:             0.2.3.0
+version:             0.2.4.1
 synopsis:            Pandoc filter for cross-references
 description:         pandoc-crossref is a pandoc filter for numbering figures, equations, tables and cross-references to them.
 license:             GPL-2
@@ -40,7 +40,7 @@
 source-repository this
   type: git
   location: https://github.com/lierdakil/pandoc-crossref
-  tag: v0.2.3.0
+  tag: v0.2.4.1
 
 library
   exposed-modules:     Text.Pandoc.CrossRef
@@ -61,11 +61,11 @@
                        Text.Pandoc.CrossRef.Util.Settings.Template
                        Text.Pandoc.CrossRef.Util.Gap
                        Text.Pandoc.CrossRef.Util.PandocOrphans
-  build-depends:       base >=4.2 && <5
-                     , pandoc >= 1.17.1 && <1.18
+  build-depends:       base >=4.8 && <5
+                     , pandoc >= 1.17.1 && <1.19
                      , mtl >= 1.1 && <2.3
                      , containers >= 0.1 && <0.6
-                     , pandoc-types >= 1.16 && < 1.17
+                     , pandoc-types >= 1.16 && < 1.18
                      , yaml >= 0.8 && <0.9
                      , data-default >= 0.4 && <0.8
                      , bytestring >=0.9 && <0.11
@@ -75,6 +75,7 @@
                      , template-haskell >= 2.7.0.0 && < 3.0.0.0
                      , roman-numerals == 0.5.*
                      , syb >= 0.4 && < 0.7
+                     , utility-ht >= 0.0.11 && < 0.1.0
   hs-source-dirs:      lib
   if impl(ghc >= 8.0.1)
     hs-source-dirs:      ghc-8
@@ -85,11 +86,11 @@
 
 executable pandoc-crossref
   main-is:             pandoc-crossref.hs
-  build-depends:       base >=4.2 && <5
-                     , pandoc >= 1.17.1 && <1.18
+  build-depends:       base >=4.8 && <5
+                     , pandoc >= 1.17.1 && <1.19
                      , mtl >= 1.1 && <2.3
                      , containers >= 0.1 && <0.6
-                     , pandoc-types >= 1.16 && < 1.17
+                     , pandoc-types >= 1.16 && < 1.18
                      , yaml >= 0.8 && <0.9
                      , data-default >= 0.4 && <0.8
                      , bytestring >=0.9 && <0.11
@@ -106,11 +107,11 @@
     hs-source-dirs:      ghc-8
   else
     hs-source-dirs:      ghc-7
-  Build-Depends:   base >=4.2 && <5
-                 , pandoc >= 1.17.1 && <1.18
+  Build-Depends:   base >=4.8 && <5
+                 , pandoc >= 1.17.1 && <1.19
                  , mtl >= 1.1 && <2.3
                  , containers >= 0.1 && <0.6
-                 , pandoc-types >= 1.16 && < 1.17
+                 , pandoc-types >= 1.16 && < 1.18
                  , yaml >= 0.8 && <0.9
                  , data-default >= 0.4 && <0.8
                  , bytestring >=0.9 && <0.11
@@ -123,6 +124,7 @@
                  , roman-numerals == 0.5.*
                  , syb >= 0.4 && < 0.7
                  , pandoc-crossref
+                 , utility-ht >= 0.0.11 && < 0.1.0
   other-modules:
                 Native
                 Paths_pandoc_crossref
@@ -151,7 +153,7 @@
   Type:           exitcode-stdio-1.0
   Main-Is:        test-integrative.hs
   hs-source-dirs: test
-  Build-Depends:   base >=4.2 && <5
+  Build-Depends:   base >=4.8 && <5
                  , hspec
                  , pandoc
                  , filepath
diff --git a/test/demo-chapters.inc b/test/demo-chapters.inc
--- a/test/demo-chapters.inc
+++ b/test/demo-chapters.inc
@@ -18,16 +18,17 @@
    ,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"]]
   ,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 [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,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(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:chapter-3.-tables",[],[]) [Str "Chapter",Space,Str "3.",Space,Str "Tables"]
-  ,Table [Emph [Str "Table",Space,Str "3.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"]]]]
+  ,Div ("tbl:table1",[],[])
+   [Table [Emph [Str "Table",Space,Str "3.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"]]
@@ -55,7 +56,7 @@
    [Para [Str "Listing",Space,Str "4.3:",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't",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,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't",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)"]]
   ,Header 1 ("sec:chapter-5.-reference-lists",[],[]) [Str "Chapter",Space,Str "5.",Space,Str "Reference",Space,Str "lists"]
   ,Para [Str "It's",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"]
diff --git a/test/demo.inc b/test/demo.inc
--- a/test/demo.inc
+++ b/test/demo.inc
@@ -13,21 +13,22 @@
   ,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 ("",[],[]) [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"]]
   ,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 [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,Math DisplayMath "a x^2 + b x^2 + c = 0\\qquad(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"]
-  ,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"]]]]
+  ,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"]]
@@ -55,7 +56,7 @@
    [Para [Str "Listing",Space,Str "3:",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't",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,Math DisplayMath " S(x) = \\int_{x_1}^{x_2} a x+b \\  \\mathrm{d}x \\qquad(3)"]
+  ,Para [Str "This",Space,Str "chapter",Space,Str "doesn't",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's",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"]
diff --git a/test/m2m/equations-auto/expect.md b/test/m2m/equations-auto/expect.md
--- a/test/m2m/equations-auto/expect.md
+++ b/test/m2m/equations-auto/expect.md
@@ -1,32 +1,32 @@
 This is a test file with some referenced equations, line
-$$ this \qquad(1)$$
+<span>$$ this \qquad(1)$$</span>
 
-Some equations might be inside of text, $$ for example \qquad(2)$$ this
-one.
+Some equations might be inside of text,
+<span>$$ for example \qquad(2)$$</span> this one.
 
 Some equations might be on start of paragraphs:
 
-$$ start \qquad(3)$$ of paragraph.
+<span>$$ start \qquad(3)$$</span> of paragraph.
 
 Other might be on separate paragraphs of their own:
 
-$$ separate \qquad(4)$$
+<span>$$ separate \qquad(4)$$</span>
 
 Some of those can be labelled:
 
-This is a test file with some referenced equations, line
-$$ this \qquad(5)$$
+This is a test file with some referenced equations, line <span
+id="eq:0">$$ this \qquad(5)$$</span>
 
-Some equations might be inside of text, $$ for example \qquad(6)$$ this
-one.
+Some equations might be inside of text, <span
+id="eq:1">$$ for example \qquad(6)$$</span> this one.
 
 Some equations might be on start of paragraphs:
 
-$$ start \qquad(7)$$ of paragraph.
+<span id="eq:2">$$ start \qquad(7)$$</span> of paragraph.
 
 Other might be on separate paragraphs of their own:
 
-$$ separate \qquad(8)$$
+<span id="eq:3">$$ separate \qquad(8)$$</span>
 
 Then they can be referenced:
 
diff --git a/test/m2m/equations-tables-auto/expect.md b/test/m2m/equations-tables-auto/expect.md
--- a/test/m2m/equations-tables-auto/expect.md
+++ b/test/m2m/equations-tables-auto/expect.md
@@ -1,68 +1,100 @@
 This is a test file with some referenced equations, line
 
+<div>
+
   ---------------------------------------------------------------- ------
                              $$ this $$                            $$(1)$
                                                                         $
   ---------------------------------------------------------------- ------
 
+</div>
+
 Some equations might be inside of text,
 
+<div>
+
   ---------------------------------------------------------------- ------
                          $$ for example $$                         $$(2)$
                                                                         $
   ---------------------------------------------------------------- ------
 
+</div>
+
 this one.
 
 Some equations might be on start of paragraphs:
 
+<div>
+
   ---------------------------------------------------------------- ------
                             $$ start $$                            $$(3)$
                                                                         $
   ---------------------------------------------------------------- ------
 
+</div>
+
 of paragraph.
 
 Other might be on separate paragraphs of their own:
 
+<div>
+
   ---------------------------------------------------------------- ------
                            $$ separate $$                          $$(4)$
                                                                         $
   ---------------------------------------------------------------- ------
 
+</div>
+
 Some of those can be labelled:
 
 This is a test file with some referenced equations, line
 
+<div id="eq:0">
+
   ---------------------------------------------------------------- ------
                              $$ this $$                            $$(5)$
                                                                         $
   ---------------------------------------------------------------- ------
 
+</div>
+
 Some equations might be inside of text,
 
+<div id="eq:1">
+
   ---------------------------------------------------------------- ------
                          $$ for example $$                         $$(6)$
                                                                         $
   ---------------------------------------------------------------- ------
 
+</div>
+
 this one.
 
 Some equations might be on start of paragraphs:
 
+<div id="eq:2">
+
   ---------------------------------------------------------------- ------
                             $$ start $$                            $$(7)$
                                                                         $
   ---------------------------------------------------------------- ------
 
+</div>
+
 of paragraph.
 
 Other might be on separate paragraphs of their own:
 
+<div id="eq:3">
+
   ---------------------------------------------------------------- ------
                            $$ separate $$                          $$(8)$
                                                                         $
   ---------------------------------------------------------------- ------
+
+</div>
 
 Then they can be referenced:
 
diff --git a/test/m2m/equations-tables/expect.md b/test/m2m/equations-tables/expect.md
--- a/test/m2m/equations-tables/expect.md
+++ b/test/m2m/equations-tables/expect.md
@@ -14,35 +14,51 @@
 
 This is a test file with some referenced equations, line
 
+<div id="eq:0">
+
   ---------------------------------------------------------------- ------
                              $$ this $$                            $$(1)$
                                                                         $
   ---------------------------------------------------------------- ------
 
+</div>
+
 Some equations might be inside of text,
 
+<div id="eq:1">
+
   ---------------------------------------------------------------- ------
                          $$ for example $$                         $$(2)$
                                                                         $
   ---------------------------------------------------------------- ------
 
+</div>
+
 this one.
 
 Some equations might be on start of paragraphs:
 
+<div id="eq:2">
+
   ---------------------------------------------------------------- ------
                             $$ start $$                            $$(3)$
                                                                         $
   ---------------------------------------------------------------- ------
 
+</div>
+
 of paragraph.
 
 Other might be on separate paragraphs of their own:
 
+<div id="eq:3">
+
   ---------------------------------------------------------------- ------
                            $$ separate $$                          $$(4)$
                                                                         $
   ---------------------------------------------------------------- ------
+
+</div>
 
 Then they can be referenced:
 
diff --git a/test/m2m/equations/expect.md b/test/m2m/equations/expect.md
--- a/test/m2m/equations/expect.md
+++ b/test/m2m/equations/expect.md
@@ -12,19 +12,19 @@
 
 Some of those can be labelled:
 
-This is a test file with some referenced equations, line
-$$ this \qquad(1)$$
+This is a test file with some referenced equations, line <span
+id="eq:0">$$ this \qquad(1)$$</span>
 
-Some equations might be inside of text, $$ for example \qquad(2)$$ this
-one.
+Some equations might be inside of text, <span
+id="eq:1">$$ for example \qquad(2)$$</span> this one.
 
 Some equations might be on start of paragraphs:
 
-$$ start \qquad(3)$$ of paragraph.
+<span id="eq:2">$$ start \qquad(3)$$</span> of paragraph.
 
 Other might be on separate paragraphs of their own:
 
-$$ separate \qquad(4)$$
+<span id="eq:3">$$ separate \qquad(4)$$</span>
 
 Then they can be referenced:
 
@@ -33,3 +33,12 @@
 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
+
+Reference prefix will override default prefix Equation 1, eqns. 3, 4
+
+References with `-` prepended won't have prefix at all: 1, 2, eqns. 3, 4
+
+References with suffix will have suffix printed after index
+(configurable): eqns. 1, 2 suffix, 3
diff --git a/test/m2m/equations/expect.tex b/test/m2m/equations/expect.tex
--- a/test/m2m/equations/expect.tex
+++ b/test/m2m/equations/expect.tex
@@ -35,3 +35,15 @@
 
 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}
+
+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/input.md b/test/m2m/equations/input.md
--- a/test/m2m/equations/input.md
+++ b/test/m2m/equations/input.md
@@ -31,3 +31,13 @@
 Or in groups [@eq:0; @eq:1; @eq:3]
 
 Groups will be compacted [@eq:0; @eq:1; @eq:3; @eq:2]
+
+Unknown references will print labels [@eq:0; @eq:none; @eq:3; @eq:2]
+
+Reference prefix will override default prefix [Equation @eq:0; @eq:3; @eq:2]
+
+References with `-` prepended won't have prefix at all:
+[-@eq:0; -@eq:1; @eq:2; @eq:3]
+
+References with suffix will have suffix printed after index (configurable):
+[@eq:0; @eq:1 suffix; @eq:2]
diff --git a/test/test-integrative.hs b/test/test-integrative.hs
--- a/test/test-integrative.hs
+++ b/test/test-integrative.hs
@@ -21,8 +21,12 @@
     p@(Pandoc meta _) <- either (fail . show) return $ readMarkdown def input
     let actual_md = writeMarkdown def $ runCrossRef meta (Just $ Format "markdown") defaultCrossRefAction p
         actual_tex = writeLaTeX def $ runCrossRef meta (Just $ Format "latex") defaultCrossRefAction p
-    it "Markdown" $ zipWithM_ shouldBe (lines' actual_md) (lines' expect_md)
-    it "LaTeX" $ zipWithM_ shouldBe (lines' actual_tex) (lines' expect_tex)
+    it "Markdown" $ do
+      zipWithM_ shouldBe (lines' actual_md) (lines' expect_md)
+      length (lines' actual_md) `shouldBe` length (lines' expect_md)
+    it "LaTeX" $ do
+      zipWithM_ shouldBe (lines' actual_tex) (lines' expect_tex)
+      length (lines' actual_tex) `shouldBe` length (lines' expect_tex)
 
 main :: IO ()
 main = do
diff --git a/test/test-pandoc-crossref.hs b/test/test-pandoc-crossref.hs
--- a/test/test-pandoc-crossref.hs
+++ b/test/test-pandoc-crossref.hs
@@ -1,4 +1,4 @@
-{-# LANGUAGE FlexibleContexts #-}
+{-# LANGUAGE FlexibleContexts, CPP #-}
 import Test.Hspec
 import Text.Pandoc hiding (readMarkdown)
 import Text.Pandoc.Builder
@@ -32,7 +32,7 @@
     describe "References.Blocks.replaceInlines" $ do
       it "Labels equations" $
         testAll (equation' "a^2+b^2=c^2" "equation")
-        (equation' "a^2+b^2=c^2\\qquad(1)" [],
+        (spanWith ("eq:equation", [], []) (equation' "a^2+b^2=c^2\\qquad(1)" []),
           eqnRefs =: M.fromList $ refRec'' "eq:equation" 1)
       it "Labels equations in the middle of text" $
         testAll (
@@ -41,7 +41,7 @@
              <> text " it should be labeled")
         (
            text "This is an equation: "
-        <> equation' "a^2+b^2=c^2\\qquad(1)" []
+        <> spanWith ("eq:equation", [], []) (equation' "a^2+b^2=c^2\\qquad(1)" [])
         <> text " it should be labeled",
           eqnRefs =: M.fromList $ refRec'' "eq:equation" 1)
       it "Labels equations in the beginning of text" $
@@ -49,7 +49,7 @@
                 equation' "a^2+b^2=c^2" "equation"
              <> text " it should be labeled")
         (
-           equation' "a^2+b^2=c^2\\qquad(1)" []
+           spanWith ("eq:equation", [], []) (equation' "a^2+b^2=c^2\\qquad(1)" [])
         <> text " it should be labeled",
           eqnRefs =: M.fromList $ refRec'' "eq:equation" 1)
       it "Labels equations in the end of text" $
@@ -58,7 +58,7 @@
              <> equation' "a^2+b^2=c^2" "equation")
         (
            text "This is an equation: "
-        <> equation' "a^2+b^2=c^2\\qquad(1)" [],
+        <> spanWith ("eq:equation", [], []) (equation' "a^2+b^2=c^2\\qquad(1)" []),
           eqnRefs =: M.fromList $ refRec'' "eq:equation" 1)
 
     -- TODO:
@@ -122,7 +122,7 @@
             )
       it "Labels equations" $
         testAll (equation "a^2+b^2=c^2" "equation")
-        (equation "a^2+b^2=c^2\\qquad(1)" [],
+        (para $ spanWith ("eq:equation", [], []) (equation' "a^2+b^2=c^2\\qquad(1)" []),
           eqnRefs =: M.fromList $ refRec'' "eq:equation" 1)
       it "Labels equations in the middle of text" $
         testAll (para $
@@ -131,7 +131,7 @@
              <> text " it should be labeled")
         (para $
            text "This is an equation: "
-        <> equation' "a^2+b^2=c^2\\qquad(1)" []
+        <> spanWith ("eq:equation", [], []) (equation' "a^2+b^2=c^2\\qquad(1)" [])
         <> text " it should be labeled",
           eqnRefs =: M.fromList $ refRec'' "eq:equation" 1)
       it "Labels equations in the beginning of text" $
@@ -139,7 +139,7 @@
                 equation' "a^2+b^2=c^2" "equation"
              <> text " it should be labeled")
         (para $
-           equation' "a^2+b^2=c^2\\qquad(1)" []
+           spanWith ("eq:equation", [], []) (equation' "a^2+b^2=c^2\\qquad(1)" [])
         <> text " it should be labeled",
           eqnRefs =: M.fromList $ refRec'' "eq:equation" 1)
       it "Labels equations in the end of text" $
@@ -148,11 +148,11 @@
              <> equation' "a^2+b^2=c^2" "equation")
         (para $
            text "This is an equation: "
-        <> equation' "a^2+b^2=c^2\\qquad(1)" [],
+        <> spanWith ("eq:equation", [], []) (equation' "a^2+b^2=c^2\\qquad(1)" []),
           eqnRefs =: M.fromList $ refRec'' "eq:equation" 1)
       it "Labels tables" $
         testAll (table' "Test table" "table")
-        (table' "Table 1: Test table" [],
+        (divWith ("tbl:table", [], []) $ table' "Table 1: Test table" [],
           tblRefs =: M.fromList $ refRec' "tbl:table" 1 "Test table")
       it "Labels code blocks" $
         testAll (codeBlock' "Test code block" "codeblock")
@@ -281,7 +281,11 @@
         it "Image labels" $
           figure "img.png" [] "Title" "figure_label1"
             <> para (citeGen "fig:figure_label" [1])
+#if MIN_VERSION_pandoc(1,18,0)
+            `test` "\\begin{figure}\n\\centering\n\\includegraphics{img.png}\n\\caption{Title}\\label{fig:figure_label1}\n\\end{figure}\n\nfig.~\\ref{fig:figure_label1}"
+#else
             `test` "\\begin{figure}[htbp]\n\\centering\n\\includegraphics{img.png}\n\\caption{Title}\\label{fig:figure_label1}\n\\end{figure}\n\nfig.~\\ref{fig:figure_label1}"
+#endif
 
         it "Eqn labels" $
           equation "x^2" "some_equation1"
@@ -291,7 +295,7 @@
         it "Tbl labels" $
           table' "A table" "some_table1"
             <> para (citeGen "tbl:some_table" [1])
-            `test` "\\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\\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}"
 
         it "Code block labels" $ do
           codeBlock' "A code block" "some_codeblock1"
