AppleScript Objective C Clippings

Again, just take this for what it’s worth, but…

Yes, the shortcuts are learning tools. You would not distribute poorly written applescripts that follow bad habits, either in the clipping menu or anywhere else*. Whether they are fully formed scripts or the barest shortcuts, people are learning from them.

Plus, with respect, you’re probably the most experienced person in the universe with ASObjC. What you may find to be a useful and clearly written shortcut may be ideal for you (or Chris; Bill; Jim; Mark, etc.) but may not be at all useful to someone working their way through the book and trying to get a handle on this.

For example, the enumerators for skipping hidden files and skipping package descendants in the one below are just placed as numbers with no indication what those numbers do, or what numbers could change options if, for example, you wanted hidden files or package contents.

Even if they’re not handlized, I think they should be clarified.


use framework "Foundation"

-- classes, constants, and enums used

property NSDirectoryEnumerationSkipsHiddenFiles : a reference to 4
property NSFileManager : a reference to current application's NSFileManager
property NSDirectoryEnumerationSkipsPackageDescendants : a reference to 2

set theURLs to (NSFileManager's defaultManager()'s enumeratorAtURL:fileOrURL includingPropertiesForKeys:{} options:(NSDirectoryEnumerationSkipsPackageDescendants + (get NSDirectoryEnumerationSkipsHiddenFiles)) errorHandler:(missing value))'s allObjects()
set allPosixPaths to (theURLs's valueForKey:"path") as list

To the extent that any sample code can be a learning aid, yes, one could learn from a Clipping.

But, in general, Clippings may be written to provide the snippet in a very compact form. Often the more compact the code is, the harder it is to read for those who did not write it.

That is why I suggested that links be provided in all of the clipping snippets that provide more info. That would be the starting point for learning, if so desired.

Here’s is an example of the “entire contents” Clipping inserted into a blank script (except for the “use” statements):

###Revised ASObjC Entire Contents Clipping in Script

use AppleScript version "2.4" -- Yosemite (10.10) or later
use framework "Foundation"
use scripting additions


--- GET LIST OF POSIX PATHS OF ALL ITEMS IN THE FOLDER & SUB-FOLDERS ---
(*
  REF:
    1.  NSFile​Manager
        https://developer.apple.com/reference/foundation/nsfilemanager
    2.  NSURL
        https://developer.apple.com/reference/foundation/nsurl  
        
  REQUIRES:
    • use framework "Foundation"
*)
--- SET FOLDER TO SEARCH ---
##set folderToSearchPath to POSIX path of (choose folder)
## OR
set folderToSearchPath to "~/Documents/Test"

-- classes, constants, and enums used
set curApp to current application
set NSDirectoryEnumerationSkipsHiddenFiles to a reference to 4
set NSFileManager to a reference to curApp's NSFileManager
set NSDirectoryEnumerationSkipsPackageDescendants to a reference to 2

set nsPath to curApp's NSString's stringWithString:folderToSearchPath

--- EXPAND TILDE & SYMLINK (if any exist) ---
set nsPath to nsPath's stringByResolvingSymlinksInPath()

--- GETS THE NSURL, WHETHER OR NOT THE FILE/FOLDER EXISTS ---
set folderNSURL to curApp's |NSURL|'s fileURLWithPath:nsPath

set theURLs to (NSFileManager's defaultManager()'s enumeratorAtURL:folderNSURL includingPropertiesForKeys:{} options:(NSDirectoryEnumerationSkipsPackageDescendants + (get NSDirectoryEnumerationSkipsHiddenFiles)) errorHandler:(missing value))'s allObjects()

--- GET THE FOLDER CONTENTS ---
### THIS LOCKS UP FOR A LARGE FOLDER LIKE ~/Documents ###
with timeout of 60 seconds -- Doesn't help.  Still locks up.
  set folderItemList to (theURLs's valueForKey:"path") as list
end timeout

###Source for Revised Entire Contents Clipping

--- GET LIST OF POSIX PATHS OF ALL ITEMS IN THE FOLDER ---
(*
  REF:
    1.  NSFile​Manager
        https://developer.apple.com/reference/foundation/nsfilemanager
    2.  NSURL
        https://developer.apple.com/reference/foundation/nsurl  
        
  REQUIRES:
    • use framework "Foundation"
*)
--- SET FOLDER TO SEARCH ---
##set #=~folderToSearchPath~# to POSIX path of (choose folder)
## OR
set #=~folderToSearchPath~# to "~/Documents/Test"

-- classes, constants, and enums used
set curApp to current application
set NSDirectoryEnumerationSkipsHiddenFiles to a reference to 4
set NSFileManager to a reference to curApp's NSFileManager
set NSDirectoryEnumerationSkipsPackageDescendants to a reference to 2

set nsPath to curApp's NSString's stringWithString:#=~folderToSearchPath~#

--- EXPAND TILDE & SYMLINK (if any exist) ---
set nsPath to nsPath's stringByResolvingSymlinksInPath()

--- GETS THE NSURL, WHETHER OR NOT THE FILE/FOLDER EXISTS ---
set folderNSURL to curApp's |NSURL|'s fileURLWithPath:nsPath

set nsItemURLList to (NSFileManager's defaultManager()'s enumeratorAtURL:folderNSURL includingPropertiesForKeys:{} options:(NSDirectoryEnumerationSkipsPackageDescendants + (get NSDirectoryEnumerationSkipsHiddenFiles)) errorHandler:(missing value))'s allObjects()

--- GET THE FOLDER CONTENTS ---
### THIS LOCKS UP FOR A LARGE FOLDER LIKE ~/Documents ###
set #~folderItemList~# to (nsItemURLList's valueForKey:"path") as list

###Primary Changes I Made

  1. Added references at top in collapsable comment block
  2. Added comments to explain ASObjC statement
  • Moved the “input” variable out of ASObjC block
  • Reduced placeholders to two
  • The starting point for the user is a statement that does NOT require any knowledge of ASObjC, and at the same gives the user two common means of specifying a POSIX path (which can also be confusing):
--- SET FOLDER TO SEARCH ---
##set folderToSearchPath to POSIX path of (choose folder)
## OR
set folderToSearchPath to "~/Documents/Test"

###View When Clipping is First Inserted (before compile)

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

IMO, this approach is a reasonable compromise between what @estockly is asking for, and the bare-bones ASObjC clippings that we have now.

BTW, if anyone finds my clipping to be too verbose, it is easy enough to delete all of the comments, or just fold the comments of the ref section at top.

I would love to see this used with every ASObjC clipping.
Those new or less familiar with AppleScript might this this same approach helpful for the normal AppleScript clippings.

1 Like

Jim,

I think that your idea of coming up with a new way is interesting. I assume the green buttons are created by a clipping or something and when clicked expand into an example. Although I can’t tell what they expand to in the picture.

But to teach ASObj-C seems to require looking at it from the mind set of the learner.

While your example doesn’t require knowledge at the start it would be probably be perceived my many as requiring such knowledge. It looks just like something a developer would look at. It has been my experience when people new to ASObj-C see something like that in the beginning they just move on.

I’m not entirely sure what a collapsable comment block is.

But your comment raises a good question. What links would you use. Most of the links are done by people who are terrible at explaining, I came across a lot that never worked when I tried them. I doubt you could find many high quality links, for people at different levels of experience, to include. Even a decent link doesn’t tell people what they are doing wrong. In most cases they just provide good examples. But a very few do give helpful hints and warning about what not to do.

I tried creating original content that did teach. I tried to make information available to people with virtually no effort on their part and only a few people weren’t interested. This is a tough problem and I doubt links are going to provide any real assistance even to those who do want to learn.

So many links assume pre-knowledge and use terminology that is not likely to known by scripters. For example most scripters would not know why you made a special mention about NSURL and how the file or folder doesn’t have to exist to create one. It is a very important point, especially if like using aliases, but most people don’t know about the problem so they would skip right over that.

The most interesting part about what you wrote is the idea about collapsable comment blocks. Advanced readers could read the content without ever expanding anything while people who are unsure about a part can expand that part. That is something that that is missing in a lot of documentation. The closest I see is link in text that when clicked go into more depth. But I often find that disruptive to do to any real extent when they fill up the window I was just reading with a new page and go back to the old page when I’m done. Collapsable comment blocks sound like something that might not suffer from that problem.

Bill

Bill, have you tried inserting a SD clipping?
The green buttons are the placeholders produced by SD.

You can try my clipping by just a copy/paste from my clipping code snippet (which is just plain text) and paste into a SD document.

Well, I suppose this depends on how Script Debugger Help system describes/defines clippings. If SD ASObjC clippings are designed like mine, then it could be made clear that you (the user) do not need to understand the ASObjC statements, unless you wish to modify them.

In the case of my example, I’m using the SD clipping for “entire contents of folder” in a way that the user does NOT need to understand how the ASObjC statements work.

Bill, if you will just try copy/paste of my clipping, it should be obvious.

It uses the SD folding feature that will allow you to fold (collapse) all of the lines between block comment statements that start with (* and end with *).

Does this make sense?

Well, maybe, but maybe not.
It seems to me the links I provided would be obvious to any author of the ASObjC clipping. Did you try my links? Do the seem appropriate and helpful to you?

The links I used, and I’m suggesting that others use, are “reference” links.
This means they point to an authoritative source that defines the terms/statements that are used in the clipping. There are NOT intended to be a tutorial. Just a reference. But this should be enough to get the user started.

Actually I have never used any clippings with SD. Once I start on a script I don’t even think of things like clippings. I did load your sample in into SD a few minutes ago and tried the collapsable comment block. As I expected it is a vary good feature for leaving it up to the user to decide how much is placed on the screen. Once it is read it is also easy to get out of the way.[quote=“JMichaelTX, post:24, topic:495”]
Bill, if you will just try copy/paste of my clipping, it should be obvious.

It uses the SD folding feature that will allow you to fold (collapse) all of the lines between block comment statements that start with (* and end with *).

Does this make sense?
[/quote]

I tried it and it made perfect sense.

Authoritative references tend to appeal to experienced users. But they can have have the opposite affect on people new to ASObj-C. Again it is the problem of having so many different levels of experience with users.

You might have to literally say somewhere up near the top no ASObj-C knowledge is not needed to keep from scaring people off.

Well I am going to have to look into collapsable comment blocks. I think this could be of use for me in producing things about ASObj-C. Thanks for your comments.

Bill

This could be a comment at the top of the ASObjC clipping.

(* 
NOTICE:  Use of this ASObjC Clipping does NOT require understanding of ASObjC, 
unless you want to make changes to these statements.
*)

I like this. It’s direct, short and is worded in such as way that it would probably surprise someone who hasn’t worked much with ASObj-C. They might even read on out of sheer curiosity. It brings up right away that whatever is ahead probably has value and they don’t even have to understand it. Sort of like a car. Many people get a lot of great use out of it with understanding much of anything about how it works.

Bill

I like this idea of providing “code writing aids” in the form of clippings. Learning how to write good code comes from actually writing good code and being able to access such good code directly is a huge boost to performance and understanding.

As far as distribution is concerned, maybe a separate package for beginners could be made available.

Jean-Christophe,

I’m going to post an update for database in the next few days that provides helps with writing ASObj-C code. It’s called “ASObj-C database.” It has sample code in it. There is an advanced, intermediate and beginning section for the samples. Right now most of the samples are in the intermediate level section. The current version is stored under the topic “Permanent place for ASObj-C database” When I post the new version I’ll also post that to the same topic. You might want to check that out.

Bill

For the longest time, I’ve wanted to see a collection of well written appleScript samples illustrating best scripting practices (more or less) for AppleScript in general, and for scripting various applications, freely available.

As for a separate package for clippings and scripts, they don’t have to come with SD or from Latenight. Anyone could put together a collection of well written clippings and scripts and it would be rather trivial to install them in sub-menus in the clippings and/or scripts folders. Same for libraries.

I think this is needed more for ASObj-C than for regular appleScripting, but I’ll bet new users might disagree.

The bottom line for me was I feel I learned more about ASObj-C by playing with the clippings provided, than from the book or database.

At one time there was a project with O’Reilly to develop an AppleScript cookbook that covered just this territory. Sadly, the project never progressed, but I’ve often thought the need was clear. As with Script Debugger, there just isn’t a large market of people willing to support such efforts financially.

1 Like

Mark,

This is the biggest reason I am trying to document ASObj-C. No publisher will touch it. But there is 2 reasons. One the market is small. The other is how fast the books get out dated. Someone has to be willing to keep the documentation updated.

People who could write documentation don’t want to do it and receive nothing for their efforts. I do plan on addressing Ed concerns with the limitations of the database. But there are many areas to address. When deciding on what to do next it always seems to be what will do the greater good and not what I want to do next.

But the new version I am coming out with will have more then a database in it. The database by itself is not enough.

The database is becoming more like the research I did at UCI. Define a problem in rigorous term, test a possible solution, learn, then test new different solutions while building a better model of the answer and the problem. This method produces small positive results in the beginning but leads to better improvements the father along the process I get.

There are a lot of parameters I never used to think about that now I am considering. This in not a simple problem. But Ed teaches me things about the importance of samples showing the fundamentals, and Jim helps me see the results oriented side of of working with AppleScript. Shane helps keep me from going off in too many directions. I get lots of input that helps me better understand what is really needed.

I have learned that documentation is not the biggest problem with ASObj-C. It is accessibility of the documentation, ASObj-C concepts, how to handle things with really big names, methods to use in development to better facilitate quicker and easier development, … So I have had to adapt my original plan to fit the new information I have learned.

No one is going to follow this process just to write a ASObj-C book. From Ed’s comments I have started to see a different way to go. But I have to figure out how to implement a solution based on what I have learned. Ed is different in that he wants to really understand the ASObj-C he is working with as opposed to just finding ways to get what he wants form ASObj-C without taking time to fully understand it. There are people who just use brut force trial and error until they get it right without a strong understanding of the under laying principles. I’m not saying that is wrong. It is a personal choice on how to get the result they want. While brute force methods produce result quicker but understanding things on deeper level in the end allows a person to go farther. But some scripters don’t need, or want, to go farther, while others do want to go farther. This is another problem with ASObj-C in that with its increased power a person can go farther then before and different scripter have different places they want to stop and go no further. Again this is not a simple problem.

Bill

@BillKopp, have you considered starting a wiki?

I know you have a lot invested in your database, but wikis make it much easier for a community to contribute to, and use.

I would think that with a little scripting, which you’re good at, you could export the database into wiki format.

Jim,

I’m not sticking with the database because I have a lot invested in it. I spent a lot of documenting things and a database is far more powerful as far as getting to the stored information. Text is simpler to use for simple searches, but much harder to use complex searches.

At the same time I am seeing how a database by itself is too limited. In the beginning I thought the entire problem was the fact information was so difficult to find and/or understand. But it’s more than that.

What I have realized is that while developers do seem to have very similar ways of going about things scripting is a lot less standardized. There isn’t any one accepted way to go about anything in AppleScript. If I want a script to solve a problem and 100 scripter did their own script I would not be surprised to 100 very different scripts. But If I had the same thing except I had 100 developers. I would be surprised to see 100 very different scripts. Developers seem to follow standards while scripter do what works. That is a hug difference. No one ever published any kind of applescript standard for how to write scripts. The only rule was you had to get it to compile.

While I was aware of this I didn’t give it enough thought. Then when apple mixed something done with standards like Object-C with AppleScript the same type of thing happened. The only standard was you had to get it to compile.

My early tries with the database did not take into account this very wide diversity. No “one size fits all” mentality is going to work for ASObj-C. One of the biggest examples of this is the model-view concept followed by developers. Scripters for the most part never hear of it and if they have heard of it they have heard of it through ASObj-C. Scripters are no where near as rigid about it despite the warnings from developers about needing to keep these things separate.

It’s like development is more of a formula while a script is more a process of an innovation. Developers do at times break from the accepted norm but when I script I’m often not sure if there is a standard or accepted way.

This one idea alone means the solution has to handle a lot of diversity. My database offered a way for scripter to get at information easier if they follow my way of getting to that information. Now that I see how stupid this is I have to come up with a more variable solution. Which is what the database is why the database is only part of the of the solution instead of the entire solution.

Once I implement the full search capabilities you will see why the database has its uses. Creating a search that allows people to find answers without having to know much, or even anything anything, about the answer is when databases become powerful. Currently that step has not been implemented yet. Not surprisingly this the hardest part to get right. If you have ever used a database that seems to require you to know what you’re looking for before you can find it then you have seen this import part of the database development fail. Currently my database fails in that exact same way because I do not have powerful search keys yet. It is still a baby database.

Bill

I understand I’m slightly drifting off-topic right now, but besides for good idiosyncratic code samples/clippings that would be tremendously helpful with syntax, I think something like an XSL transformation of the whole Foundation documentation to create something that’s readable for ASObj-C scripters is in order. As far as I am concerned, I can go through the AS reference and try the various dictionaries until I get something to work, but the Cocoa reference is just something that’s extremely foreign and totally unparsable by normal AS readers.

Bill,

Of course you are free to choose whatever tool you prefer to provide ASObjC help/info. However, I would challenge your assertion that “Text is simpler to do for simple searches, but much harder to do complex searches.”

Perhaps that was true at one time, long, long, ago, but today I have found the best, easiest-to-use, and most effective searches to be those that use a free-form search that is a combination of plain text and qualified text. Most wikis today provide a powerful search. Combine this with the ability to create saved searches, and you have a very powerful system.

I have been a user of, and contributing author of, a wiki for Keyboard Maestro for several years now. I can testify from experience that it provides both power and ease-of-use.

But the most important feature of a wiki, which I believe you are overlooking, is that it makes it very easy for multiple users to easily contribute to the knowledge base.

For example, assuming that @ShaneStanley had the interest, he could easily modify/correct/extend a section of a ASObjC wiki that you (or others) had posted. The great thing here is that it would not require any more effort on Shane’s part to edit the wiki than to make a post here, and maybe even less effort.

Just so you know, I have been the developer of many database apps over the years, and I fully understand their power. But I also understand their limitations.

IAC, I applaud your efforts to help use learn and use ASObjC.

Jean Christophe,

Are you talking about transforming all the documentation into XSL for the purpose of the user further modifying the format, or do you mean so it can be used in a browser? What about the way the information is formatted do you not like? I don’t actually work with XSL, html or any of that browser stuff.

While there is a AppleScript reference by Apple there is no ASObj-C reference from Apple. There was a single technical note that Apple published about using ASObj-C and that’s it. This is the reason I created the database.

But even if the AppleScript online reference had ASObj-C documentation in the future going through one at a time still wouldn’t work. Multipage pages of online documentation is difficult to search since if you use a normal Google search it searches the entire internet and not the online AS reference part. You can type your search terms, put a space then type site:apple.com in google and it will only search on Apple’s site. But still you would get a lot of unhelpful hits. This means you would have to go through a lot of unhelpful search hits for every thing you looked up. If you don’t know what you are looking for before you searched you probably won’t recognize it in the search results.

Unless you are down to choosing from only a few possibilities that would mean going through most of the AS documentation for each question. Again that is not a real solution. If the person is new to ASObj-C the very next line in the script would have the user doing the same thing all over again. So I wouldn’t say you could go through AS documentation even it covered ASObj-C. There are thousands of just methods alone that could be used with ASObj-C. Even if Apple went back to a book format for documentation it still would be a tremendously hard to get it right. It is the sheer size of the documentation required to fully document ASObj-C that makes a book form impractical. It would take years to write and might require a team as opposed to a single author. That is not going to happen.

You can’t go through any ASObj-C documentation beyond one tech note posted by apple because there isn’t any. What some people use, that I think you are referring to, is the Apple documentation for Objective-C and ASObj-C and Objective-C are not the same language. The are not even close. The only thing that is the same is method names, enums and constants, … If you use that documentation you have to guess what ASObj-C requires based on what Objective-C uses. This was the motivation for creating documentation.

This is why Shane created his book on ASObj-C and why I created some more additional documentation in the form of the database. That’s all the documentation on ASObj-C there is except for a small chapter at the end of a book about ASObj-C. The book was published back in 2010 and is called “Learn AppleScript: The Comprehensive Guide to Scripting and Automation 3ed,” and was written by Hamish Sanderson and Hanaan Rosenthal. But that book has been out of print for years.

Bill

Jim,

Perhaps you are right about wiki’s being easier to use then I think. Perhaps my exposure to them a long time ago has prejudiced my perception of them today. But the biggest reason I am hesitant to do that is because I have no experience with that kind of stuff and I am busy continuously every day with things from morning til bed time and I just don’t have time to figure that out, create a wiki and then maintain it.

While I put copyright notices on stuff I do, I don’t have a problem with other people using what I produce to create other things to teach ASObj-C. I only put copyright notices on things because a long time I didn’t and someone else copyrighted what I produced and I ended up not being able to use my own stuff. So the reason I copyright it is so it can remain free to be used by everyone. The only requirement for using what I create is that it only be used to produce things that a person will use for themselves or that are “free” for others to use. Once a derivative or outright copy of my stuff is sold and I do nothing then things get more complicated as far as keeping it free for every one.

If you know anyone who would like to do what you suggest they can use anything I produced. I can even reformat my data to something that would work for their use. But the idea of squeezing one more thing into my life right now is painful to just think about.

But I do appreciate the suggestion. So seriously if you know someone who might want to do a wiki they can literally copy and paste from what I have produced, they can ask me to reformat what I have. They can even keep copies of the various files used for the database on their site, or put links to my drop box on their site.

Bill

I may be wrong about my understanding of the Cocoa documentation, but it is specifically formatted with Objective-C in mind so I would transform it so that ASObj-C learners (or users who don’t want to learn Objective-C and Cocoa to make use of ASObj-C) can make sense of it.

Now, that may make no sense at all, and I can’t judge since I’ve not been able to make sense of the Cocoa reference for now.

Jean Christophe,

The same formatting is used for swift and Objective-C so it is not language specific. Apple uses conventions and terminology that are common with object oriented languages. While AppleScript is loaded with objects it is not the same same kind of object oriented language. AppleScript was designed to be a simple language to use. Languages like Objective-C and Swift are designed to be powerful, fast, memory efficient, … and simplicity was not even a consideration.

I take it you have never looked at my database. I removed all that hard to understand language and replaced it with something the average person can read. If the problem is the way the information is laid out on the screen that is is a different matter altogether. The database has a description place that says what something does. Then there is a notes section where any special information a person needs to know is included. Then every executable command has a sample where it is used. There are things other than executable commands in the database. The constants and enums that ASObj-C uses are also stored in the database.

If it is the particular way I laid out the information in the window I would like to know what that is or if you have suggestions for a better layout I would like to hear that as well. It is possible to have 2 information layouts for a window where the user can pick which they like best and just use that. That is one of the advantages of a database is the information can be changed around without having to convert anything. Databases hold raw information that can be display many, many different ways.

Can you tell me would would like to see in a in a window or what you dislike about what is in the current window in the database I did. There are just too many possibilities for how the information can be laid out I can’t just list them for you.

But adding an alternate document layout is not vary hard to do.

Bill