Create a new folder in the current list-view directory

Nov 25, '08 07:30:04AM

Contributed by: Anonymous

I work almost exclusively in Finder's List View, which has an annoying folder creation "feature" that I dislike. Once you've used the Right Arrow to drill down into a few subfolders, when you hit Command-Shift-N to create a new folder, that folder will be created at the root folder of the Finder's current view, instead of in the folder you're looking at.

What I wanted to do was select any folder, press a keyboard combo, and have a new folder created inside that currently-selected folder. Similarly, selecting a file and hitting a shortcut would create a new folder where that file is located. So I set to work with AppleScript; here's the code

try
  tell application "Finder"
    set selectedItem to selection
    set currentPath to ((the first item of the selectedItem) as alias)
    set parentPath to ""
    
    if (currentPath as string) ends with ":" then
      -- it is a folder
      set the parentPath to currentPath
    else
      -- it is a file
      set {od, AppleScript's text item delimiters} to {AppleScript's text item delimiters, ":"}
      set the parentPath to (text items 1 thru -2 of (currentPath as string)) as string
      set AppleScript's text item delimiters to od
    end if
    
    set newFolder to (my createFolder(parentPath))
    
  end tell
on error -- no folder or file is selected
  tell application "Finder"
    set the currentPath to (folder of the front window as alias)
    set parentFolder to currentPath
    
    set newFolder to (my createFolder(currentPath))
    
  end tell
end try


on createFolder(folderLocation)
  tell application "Finder"
    set thisFolder to make new folder at folderLocation
    
    set selection to thisFolder
    tell application "System Events"
      keystroke return
      quit -- if i don't do this system events seems to hang???
    end tell
    return thisFolder
  end tell
end createFolder
(Please note: I'm no uber-scripter, so there may be simpler ways of doing this.) There does seem to be a bug where Finder will not select the newly created folder. Also, to make this work via the keyboard, you'll want to use something like Spark to hook up a keyboard shortcut to this script.

[robg adds: I tested this using Butler, and it worked as described. This much older hint explained how to create a new file in the currently-selected folder via AppleScript.]

Comments (14)


Mac OS X Hints
http://hints.macworld.com/article.php?story=20081119025327978