Links Shorten Filenames

Script for Adobe InDesign

More than once I’ve encountered projects using image filenames as a means to convey caption text. This practice leads to some incredibly long filenames. A recent project had filenames so long that once down a few subfolders, the path length exceeded the maximum my Windows server could handle. It was a mess to clean up, which became the reason to create this script.

Or a project’s filenames are long for some other reason. Whether intended as caption text or not, excessively long filenames can be a pain, for the file system, applications, and operators trying to identify one file from another. This script truncates actual filenames (as each appears in Finder or File Explorer) to a reasonable length specified by the user, then update the links in the InDesign layout to the new filenames, all in one operation. As can be imagined, accomplishing this manually, link-by-link, would be time-consuming and error-prone.

  • Truncate filenames to specified maximum and update links
  • Auto-resolves duplicate filenames
  • Adapt open source to customize or create other scripts
Download
Links Shorten Filenames
Help me keep making new scripts by supporting my work. Click the PayPal button to contribute any amount you choose. Thank you. William Campbell

In the case of caption text in filenames, see the Photoshop script Filename to Description. Before shortening filenames with this script, use the related Photoshop script to copy filenames to each file’s metadata, and preserve the caption text before it is truncated.

Also consider the related script Links Remove Number Prefix. For files labeled with numbered prefixes (i.e. chapter numbers or image order), it may be desirable to strip this excess first, then further shorten the filenames.

How-to Video

How to use the script

The user is prompted to enter the maximum length for filenames. This does not include the extension, which remains the same. All links are examined and any filenames that exceed the specified value are truncated, then the new name is tested to ensure a file of the same name does not already exist. If a file does exist, the name is further shortened to allow for a version number appended to the name as a suffix, for example "~2" prior to the file extension. Finally, for any filenames that are modified, the placed graphic is then relinked to the new filename.

Source code

(download button below)

/*

Links Shorten Filenames
Copyright 2023 William Campbell
All Rights Reserved
https://www.marspremedia.com/contact

Permission to use, copy, modify, and/or distribute this software
for any purpose with or without fee is hereby granted.

THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

*/

(function () {

    var title = "Links Shorten Filenames";

    if (!/indesign/i.test(app.name)) {
        alert("Script for InDesign", title, false);
        return;
    }

    // Script variables.
    var count;
    var doc;
    var extension;
    var file;
    var fileNew;
    var fileVersion;
    var i;
    var ii;
    var link;
    var maxLength = 31; // Default max filename length. Set as desired.
    var baseName;
    var nameChanged;
    var nameNew;
    var progress;

    // SETUP

    if (!app.documents.length) {
        alert("Open a document", title, false);
        return;
    }
    doc = app.activeDocument;

    // CREATE PROGRESS WINDOW

    progress = new Window("palette", "Progress", undefined, {
        "closeButton": false
    });
    progress.t = progress.add("statictext");
    progress.t.preferredSize.width = 450;
    progress.b = progress.add("progressbar");
    progress.b.preferredSize.width = 450;
    progress.display = function (message) {
        message && (this.t.text = message);
        this.show();
        this.update();
    };
    progress.increment = function () {
        this.b.value++;
    };
    progress.set = function (steps) {
        this.b.value = 0;
        this.b.minvalue = 0;
        this.b.maxvalue = steps;
    };

    // EXECUTE

    maxLength = Number(prompt("Enter maximum filename length:", maxLength, title));
    if (!maxLength) {
        // User cleared value or pressed ESC.
        return;
    }
    // Last chance to backup data first.
    if (!confirm("WARNING!\nFiles on disk will be renamed and this cannot be undone. Make backup copies of files before proceeding. Are you sure you want to continue?", true, title)) {
        return;
    }
    // Proceed.
    count = 0;
    progress.display();
    try {
        progress.set(doc.links.length);
        for (i = 0; i < doc.links.length; i++) {
            link = doc.links[i];
            progress.increment();
            progress.display(link.name);
            file = new File(link.filePath);
            // Split filename into name and extension.
            baseName = link.name.replace(/\.[^\.]*$/, "");
            extension = String(String(link.name.match(/\..*$/) || "").match(/[^\.]*$/) || "");
            // Transformations to truncate long filenames.
            if (link.name.length > maxLength) {
                // Truncate name portion to maxLength less extension length.
                nameChanged = baseName.slice(0, (maxLength - extension.length - 1));
                // Trim whitespace.
                nameChanged = nameChanged.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, "");
                // Did name change?
                if (nameChanged != baseName) {
                    // Test if new name already exists.
                    nameNew = nameChanged;
                    fileVersion = 1;
                    fileNew = new File(file.path + "/" + nameNew + "." + extension);
                    while (fileNew.exists) {
                        // File exists. Add version suffix.
                        // Shorten nameShort by 2 characters to allow for suffix.
                        fileVersion++;
                        nameNew = nameChanged.substring(0, nameChanged.length - 2) + "~" + fileVersion;
                        fileNew = new File(file.path + "/" + nameNew + "." + extension);
                    }
                    // Rename and relink.
                    if (file.exists) {
                        progress.display(link.name + " -> " + nameNew + "." + extension);
                        file.rename(nameNew + "." + extension);
                        // Loop through all graphics and relink.
                        // Graphic could be placed more than once.
                        for (ii = 0; ii < doc.links.length; ii++) {
                            if (doc.links[ii].name == link.name) {
                                doc.links[ii].relink(file);
                                doc.links[ii].update();
                                count++;
                            }
                        }
                    }
                }
            }
        }
    } finally {
        progress.close();
    }
    alert(count + " links renamed", title, false);

})();
Help me keep making new scripts by supporting my work. Click the PayPal button to contribute any amount you choose. Thank you. William Campbell
Download
Links Shorten Filenames

For help installing scripts, see How to Install and Use Scripts in Adobe Creative Cloud Applications.

IMPORTANT: scripts are developed for the latest Adobe Creative Cloud applications. Many scripts work in CC 2018 and later, even some as far back as CS6, but may not perform as expected, or run at all, when used in versions prior to 2018. Photoshop features Select Subject and Preserve Details 2.0 definitely fail prior to CC 2018 (version 19) as the features do not exist in earlier versions. For best results use the latest versions of Adobe Creative Cloud applications.

IMPORTANT: by downloading any of the scripts on this page you agree that the software is provided without any warranty, express or implied. USE AT YOUR OWN RISK. Always make backups of important data.

IMPORTANT: fees paid for software products are the purchase of a non-exclusive license to use the software product and do not grant the purchaser any degree of ownership of the software code. Author of the intellectual property and copyright holder William Campbell retains 100% ownership of all code used in all software products regardless of the inspiration for the software product design or functionality.