スクスニップ

AppleScriptの断片をここに書く

InDesign 行内の()で囲まれた文字列を削除する AppleScript

2-3 04 選択されたテキストフレーム内の「(」と「)内の文字」を削除する(P.118)

組版時間を半減する! InDesign自動処理実例集

組版時間を半減する! InDesign自動処理実例集

=== 書籍の JavaScriptAppleScript で書き直してみます ===

部品作製

f:id:mikomaya:20141112133257p:plain

-- オブジェクト内の[pIdx]行目のテキストの[cFrom]文字〜[cTo]文字を削除する
on removeStr(myObj, pIdx, cFrom, cTo)
    tell application "Adobe InDesign CS6"
        tell myObj
            delete text from character cFrom to character cTo of paragraph pIdx
        end tell
    end tell
end removeStr

-- JavaScript の indexOf メソッドを
-- AppleScript で実装する
-- 文字列内にある特定の文字列の開始位置を返す(出現回数の引数を追加)
on textIndexOf(myStr, myPat, myCount)
    set m to 0
    set myPat to every character of myPat
    set sLen to length of myStr
    set pLen to length of myPat
    
    if sLen < pLen then return m
    set loop to sLen - pLen + 1
    repeat with i from 1 to loop
        set iStr to characters i thru (i + pLen - 1) of myStr
        if iStr is myPat then
            set m to m + 1
            if m = myCount then
                return i
            end if
        end if
    end repeat
    return 0
end textIndexOf

部品が揃ったので、まとめ

【注意】スクリプトの書き方を間違えると、 内側のリピート文が無限ループに落ちる可能性がある。

set startMark to "("
set endMark to ")"
tell application "Adobe InDesign CS6"
    set myTF to text frame 1 of document 1
    tell myTF
        set loop to number of paragraphs
        --行数分繰り返す
        repeat with i from 1 to loop
            set myStr to paragraph i
            set startPoint to textIndexOf(myStr, startMark, 1) of me
            -- 行内に"("がある間繰り返す
            repeat
                --log startPoint
                if startPoint > 0 then
                    set endPoint to textIndexOf(myStr, endMark, 1) of me
                    if endPoint is 0 then exit repeat
                    -- 文字の削除
                    --delete text from character startPoint to character endPoint of paragraph i
                    removeStr(myTF, i, startPoint, endPoint) of me
                    set myStr to paragraph i
                    set startPoint to textIndexOf(myStr, startMark, 1) of me
                    if startPoint < 1 then exit repeat
                else
                    -- 次の行へ
                    exit repeat
                end if
            end repeat
        end repeat
    end tell
end tell

実行結果

f:id:mikomaya:20141112133308p:plain