MarksLib on GitHub

markslib
finder
json
library

(Mark Alldritt) #1

My MarksLib AppleScript library, which is featured in many of my Script Debugger tutorial videos, is now part of my AppleScript Libraries repository on GitHub.

MarksLib

MarksLib is a collection of handlers for everyday operations that I find myself using in almost every script I write. There are tools for reading and writing text files, string substitution, converting between strings and arrays and more.

Installation

Download and run this script application:

Install AppleScriptLibraries.zip (71.1 KB)

Installation (manually)

Enter the following command in the Terminal application to install the latest version of MarksLib on your machine:

curl https://raw.githubusercontent.com/alldritt/AppleScriptLibraries/master/MarksLib.applescript | osacompile -o ~/Library/Script\ Libraries/MarksLib.scpt

Usage

MarksLib provides the following handlers:

containerOf

The containerOf(theReference) handler returns the container of an object specifier. For example, containerOf(file 1 of folder 1 of application "Finder") would return file 1's container: folder 1 of application "Finder".

readFromFile

The readFromFile(theFile) handler reads the contents of a text file. The theFile parameter can take many forms:

  • full HFS path (e.g. readFromFile("Macintosh HD:Users:Mark:Desktop:file.txt"))
  • full POSIX path (e.g. readFromFile("/Users/Mark/Desktop/file.txt"))
  • relative POSIX path (e.g. readFromFile("~/Desktop/file.txt"))
  • alias (e.g. readFromFile(alias "Macintosh HD:Users:Mark:Desktop:file.txt"))
  • file reference (e.g. readFromFile(file "Macintosh HD:Users:Mark:Desktop:file.txt"))

writeToFile

The writeToFile(theFile, theData) handler writes the contents of a variable to a text file. The theFile parameter can take many forms:

  • full HFS path (e.g. readFromFile("Macintosh HD:Users:Mark:Desktop:file.txt"))
  • full POSIX path (e.g. readFromFile("/Users/Mark/Desktop/file.txt"))
  • relative POSIX path (e.g. readFromFile("~/Desktop/file.txt"))
  • alias (e.g. readFromFile(alias "Macintosh HD:Users:Mark:Desktop:file.txt"))
  • file reference (e.g. readFromFile(file "Macintosh HD:Users:Mark:Desktop:file.txt"))

The theData parameter should be a string.

doesFileExist

The doesFileExist(theFile) handler tests to see if a file exists. The theFile parameter can take many forms:

  • full HFS path (e.g. readFromFile("Macintosh HD:Users:Mark:Desktop:file.txt"))
  • full POSIX path (e.g. readFromFile("/Users/Mark/Desktop/file.txt"))
  • relative POSIX path (e.g. readFromFile("~/Desktop/file.txt"))
  • alias (e.g. readFromFile(alias "Macintosh HD:Users:Mark:Desktop:file.txt"))
  • file reference (e.g. readFromFile(file "Macintosh HD:Users:Mark:Desktop:file.txt"))

replaceText

The replaceText(theString, fString, rString) handler replaces all occurrences of fString in theString with rString.

use AppleScript version "2.4" -- Yosemite (10.10) or later
use MarksLib : script "MarksLib" version "1.0"

MarksLib's replaceText("the quick brown fox jumped over the lazy dog", "the", "xxx")
-->"xxx quick brown fox jumped over xxx lazy dog"

trim

The trim(theString) handler trims leading and trailing whitespace from a string. The functional also works on arrays of strings, returning an array of trimmed strings.

use AppleScript version "2.4" -- Yosemite (10.10) or later
use MarksLib : script "MarksLib" version "1.0"

MarksLib's trim("  hello world  " & return)
-->"hello world"
MarksLib's trim({" abc ", "1234   ", "   "})
-->{"abc", "1234", ""}

split

The split(theString, theSeparator) handler splits a string into an array of strings.

use AppleScript version "2.4" -- Yosemite (10.10) or later
use MarksLib : script "MarksLib" version "1.0"

MarksLib's split("1, 2, 3, 4", ",")
-->{"1", " 2", " 3", " 4"}
MarksLib's trim(MarksLib's split("1, 2, 3, 4", ","))
-->{"1", "2", "3", "4"}

join

The |join|(theString, theSeparator) handler joins an array of strings together into a single string.

use AppleScript version "2.4" -- Yosemite (10.10) or later
use MarksLib : script "MarksLib" version "1.0"

MarksLib's join({"hello", "world"}, " ")
-->{"hello world"}
MarksLib's join(MarksLib's trim(MarksLib's split("1, 2, 3, 4", ",")), "-")
-->{"1-2-3-4"} 

formatForJSON

The formatForJSON(theValue) handler formats a string so that it is suitable for use as a value in a JSON structure.

use AppleScript version "2.4" -- Yosemite (10.10) or later
use MarksLib : script "MarksLib" version "1.0"

MarksLib's formatForJSON("My name is \"Mark\"")
-->"My name is \"Mark\""

formatForCSV

The formatCSVString(theValue) handler formats a string so that is suitable for use as a value in a CSV file.

use AppleScript version "2.4" -- Yosemite (10.10) or later
use MarksLib : script "MarksLib" version "1.0"

MarksLib's formatCSVString("Nothing special")
-->"Nothing special"
MarksLib's formatCSVString("My name is \"Mark\"")
-->"My name is ""Mark"""

How Do I Search Contacts for String in EMail Address?
MarkdownLib on GitHub
MarkdownLib on GitHub
Export OmniOutliner document to Markdown
(Jim Underwood) #2

Thanks for sharing, Mark.
This looks like great stuff. :+1:


(Phil Stokes) #3

I like that installation trick. I never thought of doing that before! :+1:t3:


(Phil Stokes) #4

I like the ability to supply either a string or a list to your trim function. √

I was wondering why you didn’t use the Cocoa methods for some of these functions, though

e.g., stringByTrimmingCharactersInSet

for trim and

componentsJoinedByString
componentsSeparatedByString

for the corresponding Join and Split handlers.


(Ed Stockly) #5

Is this doable from an appleScript? This didn’t work:

do shell script quoted form of "curl https://raw.githubusercontent.com/alldritt/AppleScriptLibraries/master/MarksLib.applescript | osacompile -o ~/Library/Script\\ Libraries/MarksLib.scpt"

Couldn’t find the path, so I think it would have to build the path on the fly or maybe set the home directory? (worked just fine from terminal)


(Mark Alldritt) #6

It’s just very old code that works and I’ve not bothered to upgrade. This stuff has existed for almost 20 years in one form or another. I began by copy-pasting these handlers into scripts, then used SD’s old libraries mechanism and now use AppleScript libraries.

I was also late to the ASObjC train. Shane had to drag me kicking and screaming into our present.


(Phil Stokes) #7

To be fair, I don’t think there was a train till SD6. Maybe it’s just me, but I’m sure I’m seeing a lot more people on ASUsers list (largely SD users I recognise from here) posting ASObjC in their scripts.

The wagon might just be starting to pull out of the station…


(Mark Alldritt) #8

No sure why this is failing for you. When I execute this code it works correctly:

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

do shell script "curl https://raw.githubusercontent.com/alldritt/AppleScriptLibraries/master/MarksLib.applescript | osacompile -o ~/Library/Script\\ Libraries/MarksLib.scpt"

(Ed Stockly) #9

That worked here. Thank you!


(Ed Stockly) #10

So I’ve been thinking about taking a fairly straight forward library and adding a SDEF to it, to help me learn how to write a good AppleScript dictionary.

I’m thinking that MarksLib might be a good candidate. Would you mind if I did that publicly on the forum? (Either this thread or a new dedicated thread).


(Mark Alldritt) #11

Go right ahead. If you like, you can clone the GitHub repository and do as you please. I suggest a separate thread with a link back to this one.


(Jim Underwood) #12

Ed,

I don’t think you should mix “quoted form of” and escaping spaces in the path.
I believe it is one or the other. Note Mark does NOT use “quoted form of”.

Getting quotes right in shell scripts is always tricky (at least for me). :wink:


(Jim Underwood) #13

Phil, good point.
So, why not do a pull on Mark’s Github and revise those handlers to use ASObjC?
Would be a great example for all of us.


(Phil Stokes) #14

Partly cos I don’t have the time and don’t use github, but mostly because “if it ain’t broken, don’t fix it”. I think the longevity of Mark’s code is a good tesitmonial for sticking with vanilla AS unless there’s a reason not to. Apple like to deprecate Cocoa methods willy-nilly, sometimes in as little as two versions, and that’s one of the things that makes me nervous about using them in AppleScripts (that said, the particular APIs I was referrring to above are all fairly long in the tooth).

Since I’m on that tack, I’ll also throw another warning flag for people jumping into ASObjC: you need to check the minimum version of any new method you discover. A good example of that is a recent thread here which was discussing using NSProcessInfo's operatingSystemVersionString. If you look at the docs for that, you’ll see you’re fairly good to go: available from 10.2. But it’s closely related sibling operatingSystemVersion is only available from 10.10 onwards. It’s easy to get caught by those gotchas* if you don’t get into the habit of checking every method you use.

As for examples, though, I do have a bunch that I already use. I’m a bit slack regarding provenance, but I suspect these were largely written by Shane; however, any of them may have been written by or modified by myself, so if there’s any errors then you can credit those to me.

!! Don’t forget to add the appropriate property if you cut and paste the handler into another script (like I just did!)

property NSArray : a reference to current application's NSArray
property NSString : a reference to current application's NSString
property NSMutableArray : a reference to current application's NSMutableArray

# remove characters from a string
on remove:remove_string fromString:source_string
	set s_String to NSString's stringWithString:source_string
	set r_String to NSString's stringWithString:remove_string
	return s_String's stringByReplacingOccurrencesOfString:r_String withString:""
end remove:fromString:

# get substring from a character to end of string
on getSubstringFromCharacter:char inString:source_string
	set s_String to NSString's stringWithString:source_string
	set find_char to NSString's stringWithString:char
	set rangeOf to s_String's rangeOfString:char
	return s_String's substringFromIndex:(rangeOf's location)
end getSubstringFromCharacter:inString:

# insert an item into a list
on insertItem:anItem atIndex:theIndex inList:theList
	set theArray to current application's NSMutableArray's arrayWithArray:theList
	theArray's insertObject:anItem atIndex:(theIndex - 1)
	return theArray as list
end insertItem:atIndex:inList:
# set theList to {5, 2, 9, 4, 2, 6, 3}
# set longList to theLib's insertItem:99 atIndex:5 inList:theList
# --> {5, 2, 9, 4, 99, 2, 6, 3}

# remove item from a list
on deleteItem:anItem fromList:theList
	set theArray to NSMutableArray's arrayWithArray:theList
	theArray's removeObject:anItem
	return theArray as list
end deleteItem:fromList:

# remove an item at a particular index
on deleteItemsAtIndexes:theIndexes fromList:theList
	set theArray to NSMutableArray's arrayWithArray:theList
	set theSet to current application's NSMutableIndexSet's indexSet()
	repeat with anIndex in theIndexes
		(theSet's addIndex:(anIndex - 1))
	end repeat
	theArray's removeObjectsAtIndexes:theSet
	return theArray as list
end deleteItemsAtIndexes:fromList:
# set theList to {1, 2, 3, 4, 5, 6, 7, 8, 9}
# theLib's deleteItemsAtIndexes:{3, 5, 7, 1} fromList:theList
# --> {2, 4, 6, 8, 9}

# get index of first occurrence of an item in a list
on getIndexOfItem:anItem inList:aList
	set anArray to NSArray's arrayWithArray:aList
	set ind to ((anArray's indexOfObject:anItem) as number) + 1
	if ind is greater than (count of aList) then
		display dialog "Item '" & anItem & "' not found in list." buttons "OK" default button "OK" with icon 2 with title "Error"
		return 0
	else
		return ind
	end if
end getIndexOfItem:inList:
# set thisList to {"I", "see", "a", "red", "door", "and", "I", "want", "to", "paint", "it", "black"}
# set aNum to its getIndexOfItem:"paint" inList:thisList
# if aNum is not 0 then
# 	-- do something
# end if
# 

  • speaking from personal experience

(Shane Stanley) #15

That’s pretty rare, though. And perhaps more importantly, they tend to support deprecated methods for a long time. There’s soft deprecation and hard deprecation…

That’s true – but it’s another reason to use Script Debugger’s code-completion. If your script includes a use AppleScript version... statement set to a version before the method was introduced, the method won’t appear in code-completion. As of 6.04, this now also goes for any minimum version set in a bundle’s Info.plist.

(Actually, operatingSystemVersion is even more complex – because it returns a struct, and only a handful of structs were bridged before 10.11, it’s not really usable in 10.10 either. Them’s the breaks.)

Or use SD’s Edit -> AppleScriptObjC... -> Copy as Standalone Code :slight_smile:


(Phil Stokes) #16

Ah, nice! I hadn’t spotted that one. :+1:


(Phil Stokes) #17

Right, but there’s two things with that (probably veering off-topic here).

One is that it’s fine when you write original code in SD6, but doesn’t help when you reuse code elsewhere. You (read: me and anyone else with my slapdash coding habits!) really need to keep good notes / comments on version compatibility with reusable code.

The second thing is a sort-of feature request: it can be disconcerting in SD6 when you know what method you want and code completion refuses to find it. My first assumption is that SD6’s code completion isn’t working or responding properly. It only occurs to me after a bit of frustration (or more likely after I look it up in Dash) that its not available. It would be good if CC could throw an alert bubble for a method that gets entered that it can see is a valid method but isn’t valid for that version. I recognise you could only do that once the entire method had been typed in, but it would still be really helpful.

Extending that concept a bit further, a ‘Verify ASObjC code compatibility’ button for an entire script would ameliorate the first problem, too.


#18

Phil,

This is true. This is also true for for iOS and Mac OS developers and has been so for a long time. But it is certainly something that can be managed.

In AppleScript there are a lot of scripts written for a small group, a company, for a family, … For these it is almost always know what the minimum system level is before even starting on a script. For this situation if it runs on the oldest system then you’re good to go.

The main thing is that system versions are not as much of a problem unless you sell software to the public. There are a lot of scripters that create scripts to be used on a known minimum Mac configuration. When I wrote things for companies I always knew the minimum system configuration every time. So I literally ran functional tests on the oldest system level first and then finished my testing with various version levels.

I wrote scripts that interfaced with a lot of UNIX systems and other larger systems that produced output that the Mac worked with. The data configuration was always changing. So I just wrote a script that was easy to change. I added preferences when so the specification of the data being received could be specified and allow both old and new data could be accessed. The point I am making is that system levels and configurations are very manageable. Selling scripts on the open market is when it gets hard. If I’m selling to the public I can just developed something on the oldest system that will be used.

When it comes to Apple deprecating things that is something that all scripters would have to worry about. But again this can managed just like Apple developers do. It’s true you don’t know what will be deprecated but it is not like every year a large percentage of ASObj-C methods are deprecated. Right now I see a lot of methods and constants being deprecated and then brought back with a new name. All that is needed is to check the OS version and then use the old or new version depending on the OS version number. These particular types of changes leave the interface to the new and old way the same.

I’m not sure what your point is here as far as deprecations and minimum system configurations is. Is this a call for caution, a warning of danger or just some thoughts on something. I got the feeling it was a warning of danger but I I’m not sure.

Bill


(Phil Stokes) #19

It was a heads-up for people new to ASObjC. For the most part, you can write AppleScript scripts without ever having to think about dependencies; you loose that innocence once you start getting into ASObjC.


#20

That’s what confuses me. The problem with ASObj-C is that it isn’t documented beyond a few notes here and there and a couple of longer sources. Therefore ASObj-C has a high curve. Shane’s book makes up a considerable portion of the documentation out there and that’s just one book. Learn AppleScript: The Comprehensive Guide to Scripting and Automation on Mac OS X is the only other Applescript book I’ve seen it mentioned in and it has some useful stuff in the last chapter. There was one other book but that book ended with some passing remarks about ASObj-C and was so tiny I couldn’t take it seriously.

That is the whole reason I started the ASObj-C database. It was to get rid of the steep learning curve. Changing languages won’t make a difference when dealing with OS versions when you know the oldest OS version.

Applescript has dependencies. Perhaps not as complicated as those in Objective-C. AS has libraries that need to be present to do certain things, frameworks that have to be “used,” objects need to exist before they can be worked on, … It seems like the same mental process to me. There is just a lot more of it in Objective-C and it is true the ASObj-C dependencies are less familiar to newer users.

If something breaks in a future OS release for ASObj-C then the scripter might have to find something new for a line in the script. But that’s just like scripting additions going bad with a new OS release, Apple deprecating something used in shell script, something called in an application that no longer works in a new version of the application, the code for scripting the interface of an application doesn’t work with a new version of the application, … How is the concept of making changes for new versions of things new to a scripter? It’s been with AppleScript from the beginning.

Bill