Here’s one that has been asked a lot and I thought I’d post my solutions for “future generations.”
Here are 2 handlers that use call methods to get a selection range and insert text and one that converts the selection range into the actual selected text:
on getSelection(aTextView)
set theContent to content of aTextView
set theRange to selectedRange(aTextView)
set beginAt to ((item 1 of theRange) as integer)+1
set endAt to (item 2 of theRange) as integer
set theSelection to (text beginAt thru endAt of theContent)
return theSelection
end getSelection
on selectedRange(aTextView)
set theRange to call method "selectedRange" of aTextView
return theRange
end selectedRange
on insertText(aTextView, theText)
call method "insertText:" of aTextView with parameter (theText)
end insertText
Using these, you can manage insertions before, after and in place of, the selection.