on run {input, parameters}
-- AppleScript to create a new file in Finder
-- Modified for my workflow.
--
-- Author: Martin Juul
-- Copyright (c) 2018 Martin Juul
-- Released under the MIT License
--
-- References:
-- - http://apple.stackexchange.com/a/129702
-- - http://stackoverflow.com/a/6125252/2530295
-- - http://www.russellbeattie.com/blog/fun-with-the-os-x-finder-and-applescript
-- - http://applescript.bratis-lover.net/library/string/
-- - https://gist.github.com/rarylson/5d20fc96335851365a02
try
tell application "Finder" to set the this_folder ¬
to (folder of the front window) as alias
set on_desktop to false
on error -- no open folder windows
set the this_folder to path to desktop folder as alias
set on_desktop to true
end try
set filename_and_ext to text returned of (display dialog ¬
"Create file named:" default answer "Untitled.txt")
-- Split filename and extension if it exists
set file_name to my leftStringFromRight(filename_and_ext, ".")
set file_ext to my rightStringFromRight(filename_and_ext, ".")
-- Check if file exists
tell application "System Events"
set file_list to get the name of every disk item of this_folder
end tell
set new_file to filename_and_ext
set x to 1
repeat
if new_file is in file_list then
set new_file to file_name & " (" & x & ")." & file_ext
set x to x + 1
else
exit repeat
end if
end repeat
-- Create and select the new file
tell application "Finder"
activate
set the_file to make new file at folder this_folder with properties {name:new_file}
if on_desktop is false then
reveal the_file
else
select window of desktop
set selection to the_file
delay 0.1
end if
end tell
return input
end run
-- leftStringFromRight by: ljr @ bratis-lover
on leftStringFromRight(str, del)
local str, del, oldTIDs
set oldTIDs to AppleScript's text item delimiters
try
set str to str as string
if str does not contain del then return str
set AppleScript's text item delimiters to del
set str to str's text items 1 thru -2 as string
set AppleScript's text item delimiters to oldTIDs
return str
on error eMsg number eNum
set AppleScript's text item delimiters to oldTIDs
error "Can't leftStringFromRight: " & eMsg number eNum
end try
end leftStringFromRight
-- rightStringFromRight by: ljr @ bratis-lover
-- modified by me so it returns empty string if delimiter is not found.
on rightStringFromRight(str, del)
local str, del, oldTIDs
set oldTIDs to AppleScript's text item delimiters
try
set str to str as string
if str does not contain del then return ""
set AppleScript's text item delimiters to del
set str to str's last text item
set AppleScript's text item delimiters to oldTIDs
return str
on error eMsg number eNum
set AppleScript's text item delimiters to oldTIDs
error "Can't rightStringFromRight: " & eMsg number eNum
end try
end rightStringFromRight