As usual, the simple case is simple, and the rest, well, not as simple :-)
If you only have a flat list of contexts in your database, and you've got a task in oTask,
Code:
name of context of oTask
would give you the name of that context. However, if you might have a nested context, like Errands : Downtown, the name of that context is only going to be Downtown, and you'll have to tiptoe through the tree structures (with apologies to Tiny Tim) to figure out the whole thing. Here's a sample piece of code that simply prints out the names of the contexts of the selected items:
Code:
tell application "OmniFocus"
local strCt
tell front document
tell document window 1
set strMessage to "Contexts of selected actions are:" & return & return
set oTrees to selected trees of content
set lngTrees to count of oTrees
if (lngTrees > 0) then
repeat with iTree from 1 to lngTrees
set oTask to value of (item iTree of oTrees)
set strMessage to strMessage & space & my ContextName(oTask) & return
end repeat
display alert strMessage
else
display alert "No content selected!"
end if
end tell
end tell
end tell
-- return full name of context, or "(None)"
-- uses ":" as hierarchy separator, as OmniFocus does not appear to expose
-- the value conveniently
on ContextName(oTask)
using terms from application "OmniFocus"
local oContext
local strContextName
set strContextName to ""
set oContext to context of oTask
if (oContext is missing value) then
return "(None)" -- easy case!
end if
-- if there is a context set, we need to construct the full name,
-- climbing up the tree to the top. We take the name of our starting
-- point, then look at the container. Each time the container is not
-- of class document, there's another layer, and we tack its name on
-- to the front of the string.
set strContextName to name of oContext
repeat while (class of (container of oContext) is not document)
set strContextName to ":" & strContextName
set oContext to container of oContext
set strContextName to name of oContext & strContextName
end repeat
return strContextName
end using terms from
end ContextName