Programmatically select text range in TextEdit

applescript, cocoa, macos, macos-carbon

Solution

Not sure how to do it with AppleScript (should be possible though), with the accessibility APIs, you could do something like this:

AXUIElementRef systemWideElement = AXUIElementCreateSystemWide();
AXUIElementRef focussedElement = NULL;
AXError error = AXUIElementCopyAttributeValue(systemWideElement, kAXFocusedUIElementAttribute, (CFTypeRef *)&focussedElement);
CFRange range = CFRangeMake(0, 10);
AXUIElementSetAttributeValue(focussedElement, kAXSelectedTextRangeAttribute, AXValueCreate(kAXValueCFRangeType, &range));
CFRelease(focussedElement);
CFRelease(systemWideElement);

That would select the first 10 characters if the TextEdit window is focussed.

Problem

Is it possible to select (Highlight) a range of text in TextEdit (by AppleScript,Cocoa or Carbon)? I tryed this code but not work: ``` set value of attribute "AXSelectedTextRange" to {selStart, selLen} ``` It seems this attribute is readonly. Thanks.

Original source