Simple word-count functionality

Here’s a space-lua script with some simple word-count functionality.

command.define {
  name = "Word Count",
  run = function()
    editor.flashNotification("Word count: "..countCurrentPage())
  end
}

function countCurrentPage()
  local text = editor.getText()
  return wordCount(text)
end

function wordCount(s)
  _,n = s:gsub("%S+","") -- count words
  return n
end

And some example expressions to write in your pages:

  • Word count a string:
    ${wordCount(“some random text”)}

  • Simple button to return the word count for the current page:
    {[Word Count]}

  • Display a wordcount for the current page:
    ${countCurrentPage()}
    (though this isn’t accurate once text is edited)

Any improvements gratefully received. I should probably put these into their own namespace…

1 Like

A little update to tidy things up into a namespace. I’m finding these small experiments to be a very useful way of getting my head around the SB ecosystem.

wc=wc or {}

function wc.currentpage()
  local text = editor.getText()
  return wc.string(text)
end

function wc.string(s)
  _,n = s:gsub("%S+","") -- count words
  return n
end

command.define {
  name = "Word Count",
  run = function()
    editor.flashNotification("Word count: "..wc.currentpage())
  end
}

Expressions
${wc.string(“some random text”)}
${wc.currentpage()}
{[Word Count]}