Create New Text File in Folder on OSX Lion

I’ve been wanting to find a solution to create a new text file in a folder on Mac OSX for a while… ages actually. Some people don’t seem to need this, but I do it all the time — I’ve got a folder open and I want to add a quick note to the folder.

I’ve search and tried a few different solutions in the past — this MacWorld solution works, but you have to have a document already in the folder to control-click. What if it’s a blank folder?

I’ve recently become an enormous fan of Alfred. Why not use Alfred to create a hotkey to run an Applescript which does this?

Another approach is to create an extension which runs a shell script, but that’s not my thing — I also couldn’t work out how to use the current folder in the shell script.

After lots of trial, error and Googling, I had something which I thought should have worked but I kept getting permissions errors. I posted to MacScripter and very soon had two working versions from Yvan Keonig (who is the MAN at AppleScript by the way).

This is the version I’m using (the second version) which Time/Date stamps the blank file — otherwise if there was a file called “untitled.txt” in the folder it would get rewritten. I used it by creating a hotkey to launch it but you could probably just as easily add it as an extension to Alfred:

on run
	my activateGUIscripting()
	tell application "Finder" to set myFolder to (folder of the front window) as text
	tell application "TextEdit"
		activate
		make new document
		tell application "System Events" to tell process "TextEdit" to tell menu bar 1 to tell menu bar item 5 to tell menu 1 to tell menu item -1
			if enabled then
				".rtf"
			else
				".txt"
			end if
		end tell
		save document 1 in file (myFolder & my dateTimeStamp() & result)
	end tell
end run

--=====

on dateTimeStamp()
	return (do shell script "date +_%Y-%m-%dT%H.%M.%S")
end dateTimeStamp

--=====

on activateGUIscripting()
	(* to be sure than GUI scripting will be active *)
	tell application "System Events"
		if not (UI elements enabled) then set (UI elements enabled) to true
	end tell
end activateGUIscripting

--=====

Thanks Yvan!

Btw, there’s also another solution by Jonas Wisser which is pretty cool — it’s called New Text File Here. If you use it with Alfred, you’ll get an extra step “Press Run to run this script or Quit to quit.”… slightly annoying. But it does let you title the file first— this could be a handy feature for some.

Problem solved!

Edit: The reason I was always getting the dialogue “Press Run to run this script or Quit to quit.” was because my Alfred hotkey contained the control key — the final post in this thread confirms that when the control key is held when running a script, you get that dialogue. I changed my Alfred hotkey and voila! no dialogue. These are both excellent solutions—question is, which works best for you?

Leave a Comment