OO-Snippets: Count words of the selected text with ooRexx

Commons

Keywordscount, words, ooRexx
LanguageooRexx
ApplicationWriter
AuthorsJosef Frysak (initial)
Supported Versions2.4.1  
Supported OSAll  
QuestionHow to count the words of selected text?
Answer

First get the selected text. Now iterate trough the selection parts and

get each of them as a string. Use this string with the "WORDS()"

function of ooRexx to count its words. Finally sum up all counts.

For further details see http://wi.wu-wien.ac.at/rgf/diplomarbeiten/BakkStuff/2008/200809_Frysak/200809_Frysak_Automating_OOo_ooRexx_Nutshells.pdf.

Code-Snippet-Listing (snippet-source)

-- try to get a script context, will be .nil, if script was not invoked by OOo
x_ScriptContext = uno.getScriptContext()
if (x_ScriptContext <> .nil) then
do
   -- invoked by OOo as a macro

   -- get context
   x_ComponentContext = x_ScriptContext~getComponentContext
   -- get desktop (an XDesktop)
   x_Desktop  = x_ScriptContext~getDesktop
   -- get current document
   x_Document = x_ScriptContext~getDocument
end
else  
do
   -- called from outside of OOo, create a connection

   -- connect to Open Office and get component context
   x_ComponentContext = UNO.connect()
   -- create a desktop service and its interface
   service = "com.sun.star.frame.Desktop"
   s_Desktop = x_ComponentContext~getServiceManager~XMultiServiceFactory~createInstance(service)
   x_Desktop = s_Desktop~XDesktop
   -- get the last active document
   x_Document = x_Desktop~getCurrentComponent()  
end




-- really easy example, using ooRexx!!!

-- counter variable
wordcount = 0

-- get access to the current selection
x_Model = x_Document~XModel
s_Container = x_Model~getCurrentSelection()


if s_Container <> .nil then
do
   -- if at least one selection has been made:
   
   -- get an index list of the selection
   x_IndexAccess = s_Container~XIndexAccess
   size = x_IndexAccess~getCount()

   -- iterate trough the selections and retrieve the selected strings
   -- count the words within the strings by using ooRexx builtin function WORDS
   do counter = 1 to size
      s_text = x_IndexAccess~getByIndex(counter - 1)
      x_TextRange = s_text~XTextRange

      wordstring = x_TextRange~getString()

      wordcount = wordcount + WORDS(wordstring)

   end
end

-- output of counted words
.bsf.dialog~messageBox("Counted Words: " || wordcount, "WordCount", "information")

::requires UNO.CLS

Changelog

DateUserModification
2008-10-141Initial version

and