What's the simplest way to save a TextEdit doc into a plain text doc?

OK this seems super simple, but I just can’t get it to work:

I’ve got a script that creates an open file in TextEdit. What’s the most elegant and straightforward way I can script it to save this doc as a plain text file rather than RTF? I’ve tried various things but nothing seems to quite work.

Hi Joe,

maybe it’s not necessary to use TextEdit.
With this subroutine you can create and write into a plain text file:

write_to_file from "this is a test" into ((path to desktop as string) & "test") without append

on write_to_file from |data| into target given append:append --target is a path string
		set open_target_file to open for access file target with write permission
		if append is false then set eof of open_target_file to 0
		write |data| to open_target_file starting at eof
		close access open_target_file
		return true
	on error
			close access file target
		end try
		return false
	end try
end write_to_file

Thanks, Stefan, that worked very nicely. But is there a way let the user decide where to save the file? (This is why I thought I had to use TextEdit.)

Ideally, I want to prompt the user to save the file where they want it to go, but I’ll use a default file name with “.txt” at the end in the save dialog.

No problem

write_to_file from "this is a test" into ((choose file name default name "test.txt") as string) without append

Ooh ooh almost there! But the script won’t compile with the “without append” added (Syntax error: expected “into”, variable name, class name, other parameter name or property but found command name). And when I take those two words out it seems to do the trick but the script errors out and says “can’t continue write_to_file”.

Any thoughts? I really appreciate all the help.

I’ve just posted the line which must be changed,
of course it works only with the subroutine included

Whoops. I did have the subroutine but I put the subroutine call in the wrong place. Everything works great now. Thanks again.