4

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.

mh taqia
  • 3,506
  • 1
  • 24
  • 35

1 Answers1

4

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.

omz
  • 53,243
  • 5
  • 129
  • 141
  • @omz plese check my issue : https://stackoverflow.com/questions/45274564/i-am-not-able-to-get-the-range-of-selected-text-in-textedit-application-from-my – kulss Jul 24 '17 at 09:14
  • It doesn't work in the sandboxed application even though accessibility permission is set. Any way to do it in the sandbox? – Wojciech Kulik May 27 '22 at 12:15
  • @WojciechKulik nope, you can't have both. if your app is sandboxed, you can't even prompt for AX permissions. it's one or the other. – godbout Aug 10 '22 at 03:54
  • @godbout actually you can prompt for AX permission. I use it to be able to simulate keys, and everything works, but not selecting text :) – Wojciech Kulik Aug 11 '22 at 07:06
  • @WojciechKulik i've never been able to. although i didn't dig any further as Apple doesn't allow apps that use the AX on the App Store (after 2012). but i know each time i start a new app that needs the AX, i'm getting reminded about the sandbox thing because the prompt, in my case, doesn't appear as long as i didn't switch the sandboxing off. – godbout Aug 12 '22 at 08:26