> I have been having a great deal (weeks) of trouble with the find
> command. I can find one instance of a pattern in a text file
> containing multiple instances, but I must use the option "starting at
> top". This won't work inside a loop
To deterministically iterate over all the matches in a document via
script, you must either use the batch find technique, *or* make sure
you start from the top on the first loop iteration. This is the
technique I suggested last time you asked this question. Let me give
you an explicit example:
tell application "BBEdit"
tell text window 1
set zStartAtTop to true
repeat while true
set zFindResult to find "co.*eia" options {search mode:grep,
starting at top:zStartAtTop} with selecting match
set zStartAtTop to false
if found of zFindResult then
set selection to "NEW_TEXT"
else
exit repeat
end if
end repeat
end tell
end tell
> so I had to decipher the structure of the "found matches" record of
> the "Search Match" record of "find"
> using error messages in XCode.
[...]
> This doesn't quite work either: The returned strings do contain the
> pattern but they also contain text on either side of the pattern.
If you use the batch method for find, in the returned record will be a
list of "Result Entry". You can look at the definition of this in the
scripting dictionary.
The "message" is the message text that would be displayed if we
displayed the match in a search results browser.
There is no field of the record which specifies the matched text. But
the record does tell you the file and offsets of the match (the values
for "start_offset" and "end_offset") so you can extract the text
directly as necessary.
Here's an abbreviated example:
tell application "BBEdit"
set zFindResult to find "co.*eia" options {search mode:grep,
returning results:true} searching in {text window 1}
if found of zFindResult and length of found matches of zFindResult >
0 then
set zEntry to item 1 of found matches of zFindResult
-- assume text window 1 since we know we search it above
set zString to characters (start_offset of zEntry) thru (end_offset
of zEntry) of text window 1 as text
display alert zString
end if
end tell
Jim