Signing off now for the weekend, but here is a sketch:
Code:
SubTreeMatch("bob")
on SubTreeMatch(strSearch)
tell application id "OOut"
tell front document
set lstRows to rows where topic contains strSearch
set lstAncestors to my GetAncestors(lstRows)
end tell
-- Process unique list of ancestors
set strTree to ""
repeat with oAncestor in lstAncestors
tell oAncestor
set strTree to strTree & topic & return
set {lstLevel, lstTopic} to {level, topic} of rows
repeat with i from 1 to length of lstLevel
set strTree to strTree & my LevelTabs(item i of lstLevel) & item i of lstTopic & return
end repeat
end tell
set strTree to strTree & return
end repeat
end tell
return strTree
end SubTreeMatch
on LevelTabs(n)
if n < 2 then return ""
set str to ""
repeat with i from 2 to n
set str to str & tab
end repeat
str
end LevelTabs
-- Purge any duplicate ancestors
on GetAncestors(lstRows)
set lstUnion to {}
tell application id "OOut"
repeat with oRow in lstRows
tell oRow
if level > 1 then
set strID to id of (last ancestor)
else
set strID to id of it
end if
end tell
if not (lstUnion contains strID) then set end of lstUnion to strID
end repeat
if lstUnion ≠ {} then
tell front document
repeat with i from 1 to length of lstUnion
set item i of lstUnion to row id (item i of lstUnion)
end repeat
end tell
lstUnion
else
{}
end if
end tell
end GetAncestors