Getting Selection and Inserting Text into a Text View

Here’s one that has been asked a lot and I thought I’d post my solutions for “future generations.” :wink:

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.

Hi, Kevin.

I think you should say what this is written for. There’s no such thing a ‘call method’ in vanilla AppleScript.

Quite right! This is for text views in Applescript Studio.