Submit Hint Search The Forums LinksStatsPollsHeadlinesRSS
14,000 hints and counting!


Click here to return to the 'Use AppleScript to count words and characters in text' hint
The following comments are owned by whoever posted them. This site is not responsible for what they say.
Use AppleScript to count words and characters in text
Authored by: robleach on Nov 07, '14 08:26:34AM
Just did this for any selected text (without having to copy)...

set debug to false

--Get the highlighted text
set selecTxt to getHighlight(debug)

set myCount to count (selecTxt)
set myWords to count words of (selecTxt)
set myParas to count paragraphs of (selecTxt)

display dialog "Characters: " & myCount & "
Words: " & myWords & "
Paragraphs: " & myParas


on getHighlight(debug)
	
	--Save the current contents of the clipboard
	set theSpare to the clipboard as record
	--Save a text version of the contents of the clipboard if possible
	set spareTest to ""
	try
		set spareTest to the clipboard as text
	end try
	--Declare the variable we're going to return
	set selecTxt to ""
	
	tell application "System Events"
		--Initiate the copy
		keystroke "c" using {command down}
		
		--Wait up to 2 seconds for the copy to finish
		set done to "no"
		set waitnum to 0
		set waitInterval to 0.02
		set maxwaits to 100
		
		--Repeat while the clipboard contents have not changed
		repeat while done = "no"
			--Get the contents of the clipboard
			set selecTxt to the clipboard as text
			
			--See if we're done or need to wait
			if waitnum is equal to maxwaits then
				set done to "yes"
			else if spareTest is equal to selecTxt then
				delay waitInterval
				set waitnum to waitnum + 1
			else
				set done to "yes"
			end if
			
		end repeat
		
		if debug is true then
			display dialog "Copied text: " & (the clipboard as text)
		end if
	end tell
	
	--Restore the original clipboard contents
	set the clipboard to theSpare as record
	
	--Return the highlighted text
	return selecTxt
	
end getHighlight


[ Reply to This | # ]