見出し画像

選択したテキストを書式を保持したまま、クリップボードのテキストで置換するスクリプト

いわゆる「さしかえペースト」を実現するスクリプトです。

  • グループ内のテキストにも適用できる

  • エリア内テキストにも適用できる

  • テキスト以外のオブジェクトを選択していても実行できる

// スクリプトの説明:
// このスクリプトは、Illustratorでアクティブなレイヤーに対して、クリップボードのテキストを
// 選択しているテキストフレームに適用します。選択がない場合は新しいテキストフレームを
// 作成し、元の位置に配置します。

// 作成日:2024年11月3日

(function () {
    var activeDoc = app.activeDocument;
    var selection = activeDoc.selection;
    var activeLayer = activeDoc.activeLayer;

    mainProcess();

    // メイン処理
    function mainProcess() {
        // クリップボードにテキストがあるか確認
        app.paste();
        var pastedTextFrame = activeLayer.textFrames[0];
        
        if (!pastedTextFrame || !pastedTextFrame.contents) {
            alert("クリップボードにテキストがありません。");
            return;
        }

        var pastedBounds = pastedTextFrame.geometricBounds;
        var pastedContents = pastedTextFrame.contents;

        // 一時的に作成したテキストフレームを削除
        pastedTextFrame.remove();

        if (selection.length === 0) {
            createNewTextFrame(pastedBounds, pastedContents);
        } else {
            for (var i = 0; i < selection.length; i++) {
                processObject(selection[i], pastedContents);
            }
        }
    }

    // 新規テキストフレームを作成し、元の位置に配置する関数
    function createNewTextFrame(originalBounds, textContents) {
        var newTextFrame = activeLayer.textFrames.add();
        newTextFrame.contents = textContents;

        var newBounds = newTextFrame.geometricBounds;
        var deltaX = originalBounds[0] - newBounds[0];
        var deltaY = originalBounds[1] - newBounds[1];

        newTextFrame.translate(deltaX, deltaY);
    }

    // オブジェクトがテキストフレームかグループかを判定し、再帰的に処理する関数
    function processObject(target, textContents) {
        if (target.typename === "TextFrame") {
            target.contents = textContents;
        } else if (target.typename === "GroupItem") {
            processGroup(target, textContents);
        }
    }

    // グループ内のすべてのオブジェクトを再帰的に処理する関数
    function processGroup(group, textContents) {
        for (var i = 0; i < group.pageItems.length; i++) {
            processObject(group.pageItems[i], textContents);
        }
    }
})();

ダウンロード

スクリプトファイル

Keyboard Maestroマクロ

ここから先は

0字 / 1ファイル

¥ 100

期間限定!Amazon Payで支払うと抽選で
Amazonギフトカード5,000円分が当たる

定期マガジンを購読されるとサンプルファイルをダウンロードいただけます。 https://note.com/dtp_tranist/m/mebd7eab21ea5