grgr.me

latest commits to https://grgr.me/
Log | Files | Refs

wordcount.lua (1167B)


      1 -- adapted from https://pandoc.org/lua-filters.html#counting-words-in-a-document
      2 -- license: GPL v2 per https://github.com/jgm/pandoc-website/blob/0001df4a44901b60d37ea0d06f0212bdc5283a21/CONTRIBUTING.md#patches-and-pull-requests
      3 -- see: http://www.gnu.org/copyleft/gpl.html
      4 -- Copyright 2006-2017 John MacFarlane, Copyright 2018 grgr.me
      5 words = 0
      6 minutes = 0
      7 wpm = 150
      8 
      9 wordcount = {
     10   Str = function(el)
     11     if el.text:match("%P") then
     12       words = words + 1
     13     end
     14   end,
     15 
     16   Code = function(el)
     17     _,n = el.text:gsub("%S+", "")
     18     words = words + n
     19   end,
     20 
     21   CodeBlock = function(el)
     22     _,n = el.text:gsub("%S+", "")
     23     words = words + n
     24   end
     25 }
     26 
     27 function count(el)
     28   pandoc.walk_block(pandoc.Div(el.blocks), wordcount)
     29   minutes = math.ceil(words / wpm)
     30 end
     31 
     32 function replace(el)
     33   if el.identifier == "time-to-read" then
     34     tooltip = words .. " words at a speed of " .. wpm .. " wpm."
     35     attr = pandoc.Attr("", {}, {{"class", "bold-on-hover"}, {"title", tooltip}})
     36     time_to_read = "~" .. minutes .. " minutes of text*"
     37     el.attr = attr
     38     el.content = { pandoc.Str(time_to_read) }
     39   end
     40   return el
     41 end
     42 
     43 return {{Pandoc = count}, {Span = replace}}