MacOS – AppleScript to Resize Finder Columns

applescriptfindermacos

Weary of the Finder's sloppy, semi-legible sizing of list view columns, I'm attempting to code an AppleScript solution. Omissions and bugs in the Finder's dictionary make this (to indulge in understatement) challenging. The goal is to have any window display a minimalist list view with a single keystroke, with all columns set to the minimum width that avoids truncation and the window itself sized to its content. Something along these lines…

minimal finder view

The primary difficulties I've encountered so far are in the column class of list view options of Finder window.

  • visible doesn't accurately reflect the columns' actual state
  • setting visible has no effect
  • width can be read but setting it has no effect

Nor does it help that the Finder's zoom button hasn't done anything sane or useful since cell phones were the size of a shoebox.

Has anyone attempted a similar project or one that overcame any of the difficulties noted above? One hates to resort to the semi-reliable inelegance of GUI scripting.

Best Answer

I have tested the following script (written to address another question here-- this one--Is it possible to change a Finder List View column width in AppleScript?

tell application "Finder"
    activate
    set the_window to window 1
    set current view of the_window to list view
    set the_options to list view options of the_window
    set the_name_column to first column of the_options whose name is name column
    set the_items to name of every item of the_window
    -- get the longest name (count of characters)
    set longest_name to 0
    repeat with I from 1 to count of the_items
        --check for invisible files, which we don't need to consider
        if character 1 of item I of the_items is not "." then
            if (count of characters of item I of the_items) > longest_name then
                set longest_name to count of characters of item I of the_items
            end if
        end if
    end repeat
    -- this only works if the text size is 12. The multiplier 7.5 could be changed
    -- if the text size is something else. 
    set desired_width to longest_name * 7.5
    set width of the_name_column to desired_width
    -- we have to close and reopen the window in order to see any changes.
    -- there might be a "refresh window" command but I don't know it.
    set the_target to target of the_window
    close the_target
    open the_target
end tell

That script will set the width of the Name column, in a window viewed as list, to be about as big as it needs to be in order to fit the longest name of an item in the window. It works (for me) in macOS 10.11.6 and 10.12.6.

The key is recognize that you don't "set the width of the name column of window 1." Rather, you "set the width of the name column of the list view options of window 1." That's pseudo-code but it tells the story. See the script for details.