For some reason Finder on Mac doesn't come with create new file functionality. The fastest way I've found to create a new file is to drag the finder path into Terminal and create a file there... which is super annoying
I wrote an apple script to automatically create a new file and bound it to a shortcut. It works perfectly, except that I can't figure out how to open the new file from within the applescript. I'm pretty sure the error stems from POSIX / UNIX paths but couldn't find a way to get this to work even when I put POSIX next to file, currentDir etc.
Here's my script:
set file_name to display dialog "File Name" default answer "untitled" with icon note buttons {"Cancel", "Continue"} default button "Continue"
set file_name to (text returned of file_name)
tell application "Finder"
set theWin to window 1
set currentDir to POSIX path of (target of theWin as alias)
make new file at (the target of the front window) as alias with properties {name:file_name}
set currentPath to (currentDir & file_name) as string
open file currentPath
end tell
The script creates the file, then errors out saying it can't find the file to open it.
I cleaned up the code a bit and got rid of unnecessary lines.
set fileName to text returned of (display dialog "File Name" default answer ¬
"untitled" with icon note buttons {"Cancel", "Continue"} default button 2)
tell application "Finder" to set newFile to (make new file at Finder window 1 ¬
with properties {name:fileName}) as alias
delay 0.1
do shell script "open -e " & quoted form of POSIX path of newFile
Note: If you're trying to use open -a
instead of open -e
... And you were getting error messages, try using open -b
. This option allows you to open the files with the application by using the application's bundle identifier to identify the application to use.
For example, if I want to open the files with Visual Studio Code.app by using it's bundle identifier... The do shell script
command would look like this...
do shell script "open -b com.microsoft.VSCode " & quoted form of POSIX path of newFile
If you do not know how to get the bundle identifier for the application to use when opening the file, this following AppleScript code allows you to choose an application then copies it's bundle identifier to the clipboard. Then just go back and paste that into the do shell script "open -b "
command.
activate
set chosenApp to name of (choose application with title ¬
"Choose App" with prompt "Choose App")
delay 0.1
tell application chosenApp to set appID to id
set the clipboard to appID
Be sure to grant Terminal.app the appropriate permissions in System Prefs.