AppleScript: Clipboard to text file on Desktop

Clipping files created by dragging a text selection to the desktop are very useful, but sometimes it’s more beneficial to create a text file. Here’s an AppleScript that does that. The script is most conveniently used by activating it with a keyboard shortcut or other shortcut rather than having to find it in your Script menu. One way to make it quickly accessible is to place it in the toolbar of Finder windows. The way I run it is to use ⇧⌃⌥L (Shift-Ctrl-Opt L) in Keyboard Maestro. You could also put it into the Script Menu and launch it using Daniel Jalkut’s FastScripts, or you could even create a System Service from the AppleScript using Automator and configure the keyboard trigger in the Shortcuts tab of the Keyboard sysprefpane (System Preferences> Keyboard). Whatever way you choose to run it, all you need to do is make sure the text you want turned into a file is copied to your clipboard first. The Finder window toolbar and Automator System Service methods are built into the Mac system and are completely free. Keyboard Maestro and FastScripts are commercial automation solutions, but both are well worth the investment.

 

property temppath : "/private/tmp/"

property startnum : 0

property clipname : "clip"

property add_on : ".txt"

activate

set clipname to (text returned of (display dialog "Enter a description of the clipboard text that will be used to name the file:" default answer clipname))

set rootpath to ((path to desktop) as Unicode text)

set thepathname to rootpath & clipname

set pos_filepath to POSIX path of rootpath as Unicode text

set dest_file to (quoted form of (temppath & clipname & add_on))

do shell script "pbpaste >" & space & dest_file

tell application "Finder"

set basename to clipname

repeat

try

set name_target to alias (rootpath & clipname & add_on) --file name is already taken at destination if no error occurs.

set startnum to startnum + 1

set clipname to text returned of (display dialog"A file with that name already exists. You may enter a new name or cancel."default answer (basename & startnum))

on error _error

set startnum to 0

if _error contains clipname then --if target is clear and source file can be copied from temp directory

tell me to do shell script"ditto" & space & dest_file & space & (quoted form of (pos_filepath & clipname & add_on))

exit repeat

else -- if action is cancelled by user

exit repeat

end if

end try

end repeat

end tell
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s