Coercion issue

Good Morning All,
I’ve been migrating my scripts from OS 9.2 to 10.3.3. Things have been going very well.
I do, however, have one that’s beating me up. It is a droplet that is activated when dropping an Excel document on it. The script needs the path to the Excel doc for other processes within the script. It starts:

 on open x
	set docPath to x
	set pathName to docPath as string

Somwhere along the way this coercion from an alias to a string something gets mucked up.  If I comment out the open handler and type the actual path into the script, it works fine. However, if I let the script do the coercion, it gets wacked. I never had an issue with this in OS 9.2.

Any insight would be greatly appreciated.

You may want to try

set pathName to (docPath as unicode text) as text

or something like that (I forget the exact syntax but it’s close).

I appreciate the reply, but that didn’t get it.
Thang Q

You can try this:

on open {docPath}

--> docPath is an alias, eg: alias "path:to:doc"
--> if you need it as simple text, just uncomment the following line:

-- set docPath to docPath as text --> "path:to:doc"


Hm, well, ‘x’ in the above is actually a list. If just one item is dropped, then it should be a list of one item. However, the “as string” coercion should coerce a single-item list just as easily as it coerces the item itself.

dant is probably right. There may be a Unicode problem involved. In fact, I have now come to the conclusion that 99.997 percent of all OS9-OSX crossover problems are Unicode problems.

P.S. Still waiting for Apple to implement an “as plain text” coercion. The problem
isn’t going to go away by just pretending it doesn’t exist.

  1. You’re actually coercing from a list to a string. If x contains only one alias, then the result of the coercion will be a path string. If x contains more than one alias, the result will be a string consisting of several path strings run together.

  2. In recent versions of OS X, the result of coercing an alias (or a list of aliases) to string is Unicode text. There are still parts of the system, and some applications, that can only understand plain text. Any text you type into the script is plain text, which is probably why that does work with whatever you’re doing in your script.

If you’re only using Latin characters, punctuation, and digits in your folder and file names, you can convert to plain text like this:

on open x

  set docPath to item 1 of x
  set pathName to docPath as string
  -- Unofficial hack
    set pathName to «class ktxt» of (pathName as record)
  end try

Right, it’s called the um, er… the “Knapp coercion.” Yeah, that’s the ticket. :wink:

That coercion to plain text was the ticket.

Er … Yes. I’m sure Richard 23 would have called it something like that. :wink:

R23 abandoned the AppleScript ship, which gives me every right to take credit for his work. :wink:

P.S. I’m getting ready to release an extraordinary new series of AppleScripts that I’ve just written:


I’ve got a million of these… :wink:

P.P.S Why didn’t MacScripter tell me when this thread was updated like it usually does?

Charles Ives stopped composing sometime in his fifties and is, moreover, now dead. Maybe I could take credit for his Fourth Symphony! Gosh! My Mum would be so proud. It’s one of her favourites. :slight_smile:

Extraordinary indeed. But I think you’ve mispelt “Krapp”. :wink:

Actually, until Mac OS X Arcturan Megamoggie comes out, what the world really needs at the moment is a KnappSort substitute for the Finder’s ‘sort’ command. It should take a reference to a bunch of Finder items, and a ‘sort by’ parameter - then sort the items by that parameter. Sorts by number or date should be arranged highest to lowest; string sorts should be alphanumeric in the new Finder style, arranged lowest to highest. Additionally, where two or more items have the same size, modification date, creator type, etc., they should be subsorted by name in the manner described above. The results should be returned to the script virtually instantaneously. I’d write it myself, of course, but I’m - er - a little busy at the moment. 8)

Perhaps it only notifies when something interesting or on-topic is added. :wink:

I neglected to mention that I’ve discovered a way to “overflow” the date object… :wink:


As a matter of fact, as soon as my Brand New Apple iBook arrives!!! I intend to release my VasSortLib. It will be the first of a series of Vanilla AppleScript libraries that I intend to get off my chest, after which, I hope to be rid of this silly language forever. :wink:

Here is the API:

isort( list, startIndex, endIndex )
qsort( list, startIndex, endIndex )
csort( list, startIndex, endIndex, sortsBeforeHandlerOrScriptObject )

      ItemSort( list )
CustomItemSort( list, sortsBeforeHandlerOrScriptObject )

    DateSort( list, dateParseParam )
AlphaNumSort( list )

ItemShuffle( list )

GetSortOrder( list )
SetSortOrder( list, indices, paramOneIsListOfListsBoolean )

FolderSort( folder-spec, nestedContentsBoolean, sortByParam )
SystemSort( alias list,  nestedContentsBoolean, sortByParam )

script ByLength's   sortsBefore( item1, item2 )
script ByIndex's    sortsBefore( item1, item2 )
script ByIndices's  sortsBefore( item1, item2 )
script BySource's   sortsBefore( item1, item2 )
script ByClass's    sortsBefore( item1, item2 )
script ByAnything's sortsBefore( item1, item2 )

isort() and qsort() are implementations of insertion-sort
and quick-sort that Nigel and I recently hammered out. csort()
is a version of qsort() that takes a comparison handler, or
a script object with a comparison handler called sortsBefore().
Their terse names are not meant to suggest that they are
“internal” handlers, but simply that they are the “primary”
handlers upon which all the other handlers are based. For
speed, these three handlers also implement less error-checking
than the other handlers in the library.

ItemSort() is the basic sort, requiring that all items of
the list be compariable via AppleScript’s less than and greater
than operators, < >.

CustomItemSort() implements csort() without having to specify
a starting and ending index, (and with better error-checking).

DateSort() is a handler for the common problem of sorting
date-strings that come in a variety of formats, (not all of
which are automatically recognized by AppleScript’s
‘date (“date string”)’ coercion).

AlphaNumSort() is for sorting strings containing numbers,
such that “abc2def” would come before “abc20def”, etc.

ItemShuffle() is a quick randomizing sort.

GetSortOrder() returns indices into the list, indicating
the sort order, if you were to sort the list:
{“b”, “c”, “a”} → {2, 3, 1}

SetSortOrder() takes as its first parameter either a single
list to sort, or a list of lists to sort, based on an indice
list, (perhaps created by GetSortOrder()).

FolderSort() and SystemSort() will implement something along
the lines of what you suggest. There are two handlers because
it is easier and faster to start with a folder of items to
sort than it is to take a list of system items that might
have come from anywhere, even from two or more different volumes.

P.S. Why do the “code” blocks in BBCode not use monospaced fonts. I don’t understand what the point of marking something “code” is if it doesn’t make it look like code, (and especially if it doesn’t let it line up and align like code).

Not to mention syntax coloring (as in other no-phpbb boards PHP and such).
BTW, could you ellaborate a bit “SystemSort”? (smells interesting)

It probably needs a better name. :slight_smile:

Like I was saying, if the task at hand is to sort the contents of a folder, then you can use Finder “whose” statements, the “list folder” osax command, etc., to get things that you need with very few statements. Whereas if your starting point is simply a list of files and folders that could have come from anywhere:

set a to {}
set a's end to choose file
set a's end to choose file
set a's end to choose folder

it is more difficult to sort them by some property, because you then have to treat each one as a seperate entity.

Poor Arthur, you’re a bit late… :stuck_out_tongue:

From the List library at AppleMods:

sortList(lst) -- sort a list
	lst : list -- list of simple, directly comparable values (integers/reals/string/Unicode text/date)
	Result : list

sortListOfLists(lst, idxList) -- sort a list of lists by specified items of sublists
	lst : list of lists -- list of sublists to sort
	idxList : list -- a list of one or more integers indicating which item(s) in sublists to sort on
	Result : list of lists

powerSort(lst, evaluatorsList, groupingToDepth) -- sort a list with complex weightings and optional grouping of results [1]
	lst : list -- list of values to sort
	evaluatorsList : list of scripts -- list of one or more SortEvaluator objects (see OBJECTS, SortEvaluator)
	groupingToDepth : integer -- sub-group results to a given depth

unsortList(lst) -- randomly rearrange a list
	lst : list
	Result : list

Also, the FinderExtras library has some routines for sorting Finder references, while the Date library has a nice date string parser that’s very useful in sorting date strings:

property _Loader : run application "LoaderServer"


property _Date : missing value
property _List : missing value

on __load__(loader)
	set _Date to loader's loadLib("Date")
	set _List to loader's loadLib("List")
end __load__


__load__(_Loader's makeLoader())

on sortDateStrings(lst, formatStr)
	set dateParser to _Date's makeParser(formatStr)
	script DateStringEval
		property reverseSort : false
		on eval(str)
			return dateParser's parseText(str)'s first item
		end eval
	end script
	return _List's powerSort(lst, DateStringEval, 0)
end sortDateStrings

sortDateStrings({"4 Feb 2003", "17 Jul 2002", "16 Jul 2004"}, "d mmm yyyy")
--> {"17 Jul 2002", "4 Feb 2003", "16 Jul 2004"}

The MacPython community certainly has room for good application scripting evangelists…

Has, I do hope you’ll forgive me for offering my own sorting routines. :slight_smile:

(Besides which, I suspect [though have not yet tested] that my and Nigel’s offering is slighter better in the speed department). :slight_smile:

I’m sure they do, but I think I’ll wait for Mark Alldritt to update JavaScriptOSA for better scripting under OS X. In the meantime, I’m busy checking out Konfabulator, Cocoa, and believe it or not, I’ve been reading about awk and sed… :slight_smile:

Well it ain’t on my time so no skin off my nose… just thought you’d appreciate a heads-up vis-a-vis reinventing wheels and that… :stuck_out_tongue:

Given I can pick up Python, Perl or just about any other scripting language mentionable and get at least 10x the performance of AS for 1% of the effort, you’ll forgive me for not looking sufficiently impressed at a few percentage speed boost over my own efforts, which were in any case geared primarily to robustness and ease of maintenance and use. (The basic quicksort trades a few percent raw speed for immunity to stack overflows, for example.)

Is Mark still working on JavaScript OSA? (Mmm… wonder why he doesn’t open source it?) You might suggest he drop me a note if he is; I can supply a spec for implementing a nice appscript-style API if he’s interested. (Will trade for info on implementing OSA support.:slight_smile:

BTW, if you’re learning awk and sed you might also try Perl which draws ideas from both. It also has an Apple Event Manager bridge, Mac::Glue, although I’ve not used it myself so can’t really say how good it is. Both Perl and Python also have Cocoa bridges, allowing Cocoa programming without having to use Obj-C. (Ruby also has a Cocoa bridge, though currently lacks AEM support.)