AppleScripts snippets thread

Discussion in 'Mac Programming' started by moonman239, Jan 8, 2013.

  1. moonman239, Jan 8, 2013
    Last edited: Jan 14, 2013

    moonman239 macrumors 68000

    Mar 27, 2009
    The purpose of this thread is for other people to post snippets of AppleScript code that other people might find useful.

    Here's a snippet from a script I'm working on:
    UPDATE: I just finished it. Here's the final result:
    on separateItemsIntoCategories(theContent, theCategories, categoryID)
    	set oldDelims to AppleScript's text item delimiters
    	set theDelims to {}
    	repeat with X from 1 to count of theCategories
    		set delim to (item X of theCategories) & categoryID
    		copy delim to end of theDelims
    	end repeat
    	set AppleScript's text item delimiters to theDelims
    	set categorizedContent to rest of (every text item of theContent)
    	set AppleScript's text item delimiters to oldDelims
    	return categorizedContent
    end separateItemsIntoCategories
    This function takes a string of categorized entries and returns a list, with each entry of the list representing a separate category. categoryID refers to a string following the category name that tells the script that the information below the category header is in a different category. (Warning: The function may return a string with leading and/or trailing spaces, depending on whether there are any spaces between the items and the category names.)

    For example, let's say I build a script that sorts today's meals into four categories: breakfast, lunch, dinner, and desert.

    I set theContent to "Breakfast: Pancakes with syrup Lunch: A tuna fish sandwich Dinner: A salmon Dessert: Brownies"
    I then set theCategories to {"breakfast","lunch","dinner","dessert"} and categoryID to ":" (since the items in each category follow a :.)
    The function gives me {" Pancakes with syrup "," A tuna fish sandwich "," A salmon"," Brownies"}

    It would be cool if someone could make a snippet that, if AppleScript comes across an error, will cause the script to present the error message to the developer and offer to send the whole code to a Website or something so a human or computer can look at the code and help the developer fix the issue. Perhaps, if a computer gets the code and no typos there, the computer will try to figure out what the developer wants the script to do and offer a solution.
  2. moonman239 thread starter macrumors 68000

    Mar 27, 2009
    I just updated my snippet. It is much simpler and free from any flaws that I care about, one of which being that AppleScript split some text that I did not want it to split. Note: The snippet is not compatible with any version of the Mac OS older than 10.6, because OS versions prior to 10.6 do not support having multiple text item delimiters.

Share This Page