I've tried the following script in a test stack, and it seems to work fine here - no crashes or endless loops...
Code: Select all
on mouseUp
lock screen
local tWords, tExit, tItem
put "en" into tWords
repeat for each item tItem in tWords
find empty
put false into tExit
repeat until tExit
find chars tItem in field "test"
if char ((word 2 of the foundChunk) - 1) of fld "test" = space then next repeat
if char ((word 2 of the foundChunk) + 1) of fld "test" = space then next repeat
if the foundChunk is empty then
put true into tExit
else
set the foregroundColor of the foundChunk to "red"
end if
end repeat
end repeat
end mouseUp
Note, however, that
space is not the only word delimiter, and depending on what kind of text you are dealing with, you may have to check for additional characters - like return, comma, colon, semi-colon, dashes, single and double quotes, etc.
The following code is another way to go about doing the same job. It is a bit more advanced, as it uses
Regular Expressions, or "Regex", to do the finding.The
matchChunk function allows us to use Regular Expressions instead of a simple search string:
Code: Select all
on mouseUp
lock screen
local tList, tSubstring, tRegex, tOffset, tStartPos, tEndPos
put "en" into tList
put 1 into tOffset
put the number of chars in field "test" into tEndPos
repeat for each item tSubstring in tList
-- build Regex we're going to use:
put "\w+(" & tSubstring & ")\w+" into tRegex
repeat while matchChunk(char tOffset to tEndPos of field "test", tRegex, tStartPos, tEndPos)
add (tOffset-1) to tStartPos
add (tOffset-1) to tEndPos
set the foregroundColor of char tStartPos to tEndPos of field "test" to "red"
put tEndPos into tOffset
put the number of chars in field "test" into tEndPos
end repeat
end repeat
end mouseUp
If we take the substring "en" as an example, the regex being used here is
"\w+(en)\w+". It looks complicated, but it is actually quite simple. It means: "find one or more characters that are not word-boundaries, followed by 'en', followed again by one or more characters that are not word-boundaries." That is: find "en" in the middle of a word.
The matchChunk function then gives us the position of the "en" in the tStartPos and tEndPos variables, and we use these values to colour the text, and then to offset the next search.
I hope this helps!