Search code examples
htmlrmarkdownr-markdownbookdown

custom labels and counters in r-markdown


Is it possible to create an intext custom counter in r-markdown. For instance, say I have the following text

Einstein was a clever man [Fact 1]. Einstein worked for Princeton University [Fact 2]. Anyone who is employed by Princeton University is clever.

My ideal outcome is to define a counter for facts, with a specific formatting (e.g. bold and red in a bracket). So any time I call the counter it would print the counter label with the new number. Something like

Einstein was a clever man factCounter. Einstein worked for Princeton University factCounter. Anyone who is employed by Princeton University is clever.


Solution

  • A pandoc Lua filter would do the job:

    local utils = require 'pandoc.utils'
    local fact_counter = 0
    
    function Code (code)
      if utils.stringify(code) == 'factCounter' then
        fact_counter = fact_counter + 1
        return pandoc.Str(string.format('[Fact %s]', fact_counter))
      end
    end
    

    Just add --lua-filters=FILE-CONTAINING-ABOVE-CODE.lua to your pandoc_args knitr options. All occurences of `factCounter` in your text will be replaced by an actual fact count.