Modify formatted text fields via ApplicationServices

Hey folks. First time writing here!
I'm writing a (simple?) macOS application (in Swift) to apply text macros to selected text in the open application (e.g. indent, deindent, capitalize selection).
I've found that I can read the attribute value for `"AXSelectedText"`, edit it, and write out the value back to `"AXSelectedText"`. However, this only works for plain text. If I have some formatted text selected (e.g. a portion of an RTF file in TextEdit), all the formatting is stripped lost.
Is there some way to retrieve/save an `NSAttributedString` for the `"AXSelectedText"` attribute?
Alternatively, is there a way to just tell the application "delete this range of text", "insert this text here", etc., without losing formatting?


(And yes I'm aware that automator services can achieve this, but they're not as powerful as generalized Swift code, they're slow to load/run, and they don't have the UX I'm looking for)

Modify formatted text fields via ApplicationServices
 
 
Q