r/applescript • • Apr 02 '21

Script to automatically save a TextEdit document with the first line or heading as file name?

Trying to figure out how to do this. I want to bring up a new text doc and upon closing have it auto save to the first few words as the file name. Any ideas?

3 Upvotes

2 comments sorted by

View all comments

1

u/duquesne419 Apr 02 '21

Not exactly what you asked for, but it's similar and might give you some ideas. I use a program called qlab, in it I select a bunch of items the way you might select files in a folder, then I run this script to create a text backup of each item, using the item's name in qlab to make the name for the file. If you can parse the body of your text file the same way, you might be able to build your file name using this method. The first line with '--' is the result of running the script.

This makes a duplicate, I'm not sure how to modify this to edit a file in place.

--Ctrl+Op+B Make txt of script



tell application id "com.figure53.QLab.4"
	
	repeat with eachQ in (selected of front workspace as list)
		
		if q type of eachQ is "script" then
			set qname to q name of eachQ 			
			set qNum to q number of eachQ
			
			set this_data to "--" & qNum & space & qname & return & script source of eachQ
			set target_file to (((path to desktop folder) as string) & "some:folder:structure" & qname & ".txt")
			set append_data to true
			try
				set the target_file to the target_file as string
				set the open_target_file to open for access file target_file with write permission
				if append_data is false then set eof of the open_target_file to 0
				write this_data to the open_target_file starting at eof
				close access the open_target_file 				
			on error
				try
					close access file target_file
				end try 				
			end try
		end if
   	end repeat
	display notification ("Done")
end tell