0

I am trying to highlight text in any Mac app through may custom Mac app, by making use of NSAppleScript. I have tried below code but it doesn't work.

NSAppleScript* scriptObject = [[NSAppleScript alloc] initWithSource:[NSString stringWithFormat:@"\
tell application \"%@\"\n\
activate\n\
end tell\n\
tell application \"%@\"\n\
set theRange to create range start %ld end %ld\n\
set highlight color index of theRange to %@\n\
end tell\n\
",[[NSUserDefaults standardUserDefaults] valueForKey:@"AppName"],[[NSUserDefaults standardUserDefaults] valueForKey:@"AppName"],(unsigned long)range.location, (unsigned long)(range.location+range.length),@"yellow"]];

But I am getting below error :

NSAppleScriptErrorBriefMessage = "Expected end of line but found identifier.";
    NSAppleScriptErrorMessage = "Expected end of line but found identifier.";
    NSAppleScriptErrorNumber = "-2741";
    NSAppleScriptErrorRange = "NSRange: {459, 5}";

Is there any other way I can do this? any help will be appreciated.

Krishna Maru
  • 164
  • 13
  • 1
    Tip: Test the script string in Script Editor. – Willeke Oct 26 '18 at 13:58
  • @Willeke, it doesn't work in Script Editor too. Is there anyway I can check which keywords works fine in appleScript for which application. I have got a reference link [https://iworkautomation.com/pages/body-text-basics.html] in which there is an example to change text color. but setting background color / selection of text doesn't work. – Krishna Maru Oct 29 '18 at 06:08
  • Open the dictionary of the application in Script Editor. – Willeke Oct 29 '18 at 12:19

1 Answers1

2

This cannot work for all applications because the application specified in NSUserDefaults must have an AppleScript dictionary and this dictionary must contain the commands, properties and classes.

Many applications aren't scriptable at all and almost all applications don't understand create range and highlight color index.

The error is a compiling error.


And from the ObjC perspective never use valueForKey: with NSUserDefaults unless you can explain why KVC is explicitly needed in this case. There is stringForKey: and for id objects objectForKey:

vadian
  • 274,689
  • 30
  • 353
  • 361