Easily save TextEdit documents via AppleScript

Sep 22, '08 07:30:03AM

Contributed by: PizzaCake

I often dump ideas, questions, and answers in TextEdit files which I later use Spotlight to retrieve. Saving lots of these files manually is a chore, so I created an AppleScript to take care of this.

How it works is it takes the first paragraph (a line followed by return) of the document -- typically the title in my writing -- and uses this to name the text file (note some characters like ':' cannot be used in file names), and then saves the text file in your Documents folder. Here's the script:

tell application "TextEdit"
	set documentName to ""
	set paragraphText to paragraph 1 of document 1
	if (count of paragraphs of document 1) = 1 then
		set documentName to paragraphText
	else
		-- get rid of newline character
		set documentName to ((characters 1 thru -2 of paragraphText) as text)
	end if
end tell

tell application "Finder"
	set theDocumentPath to (path to documents folder as text) & (documentName as text) & ".rtfd" as text
	if item (theDocumentPath) exists then -- check if document already exists, avoid overwriting it!
		display alert "Document already exists!"
	else
		try
			tell application "TextEdit" to save document 1 in theDocumentPath
		on error
			display alert "Cannot save " & theDocumentPath as text
		end try
	end if
	tell application "TextEdit" to activate
end tell
[robg adds: To use the script, save it to your user's Library » Scripts » Applications » TextEdit folder (in 10.5), and you can then access it from the Scripts menu within TextEdit. I tested it, and it works as described.]

Comments (6)


Mac OS X Hints
http://hints.macworld.com/article.php?story=20080917031839321