(*

“cd” to directory to Finder window

By: Joe Szedula

The best way to use this Applescript is to place it in the Finder window toolbar. When clicked, it will open a new terminal window (if none is open) and change the directory. If one or more files/folders are dragged to the icon, terminal windows are opened and the directories changed to the folder or the folder containing the file. This Applescript have been tested with Mac OS X 10.3.9. & 10.4.x

*)
global theDelay, TerminalIsOpen, newWindow

-- script was opened by click in toolbar
on run
   isTerminalOpen()
   tell application "Finder"
      set the theList to selection
      if (count of theList) is 0 then
         try
            set theList to {(folder of the front window) as alias}
         on error
            set theList to {path to desktop folder as alias}
         end try
      end if
   end tell
   set newWindow to false -- don't create a window unless needed
   open (theList)
end run

-- script run by draging file/folder to icon
on open (theList)
   isTerminalOpen()
   set newWindow to false -- don't create a window unless needed
   repeat with thePath in theList
      set thePath to thePath as string
      if not (thePath ends with ":") then
         set x to the offset of ":" in (the reverse of every character of thePath) as string
         set thePath to (characters 1 thru -(x) of thePath) as string
      end if
      CD_to(thePath)
   end repeat
   return
end open

-- cd to the desired directory in terminal
on CD_to(theDir)
   set theDir to quoted form of POSIX path of theDir as string
   tell application "Terminal"
      if TerminalIsOpen then activate -- activating when launching creates 2 windows
      
      if ((count of the window) = 0) or (the busy of window 1) or newWindow then
         tell application "System Events"
            if TerminalIsOpen then
               keystroke "n" using command down
            else
               set TerminalIsOpen to true
            end if
         end tell
      end if
      delay theDelay -- without delay "cd" is sometimes lost
      set theDelay to 1 -- now use short delay
      activate
      do script "cd " & theDir in window 1
   end tell
   set newWindow to true -- always create window for any other files/folders
end CD_to

-- see if application is open
on isTerminalOpen()
   tell application "Finder"
      set theResult to (process "Terminal" exists)
   end tell
   if (theResult) then
      set theDelay to 1
      set TerminalIsOpen to true
   else
      set theDelay to 3
      set TerminalIsOpen to false
   end if
end isTerminalOpen