NSAppleScript to highlight text in any Mac app with given NSRange

179 views Asked by At

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.

1

There are 1 answers

2
vadian On

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: