スクスニップ

AppleScriptの断片をここに書く

InDesign 選択された段落に番号を振る(桁数指定) AppleScript

2-4 02 選択された段落に指定した桁数の番号を振る(P.121)

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

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

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

部品作製

f:id:mikomaya:20141112143323p:plain

-- 指定した桁数(0を左に追加)に整形した数(文字列)を返す
on zeroPadding(myNum, pSize)
    set pStr to {}
    repeat pSize times
        set end of pStr to "0"
    end repeat
    set pStr to pStr as string
    set myNum to myNum as string
    set mySize to length of myNum
    if mySize ≥ pSize then
        -- 数値の桁数が多い場合はそのまま返す
        return myNum
    end if
    set fixStr to pStr & myNum
    set fixSize to length of fixStr
    characters (fixSize - pSize + 1) thru (fixSize) of fixStr as string
end zeroPadding

-- オブジェクト内の段落[pFrom]から[pTo]までを選択
-- pToが0の場合は、最終段落まで
-- pToがマイナスの場合は、最終段落 - pTo段落まで
to selectParagraph(myObj, pFrom, pTo)
    tell application "Adobe InDesign CS6"
        tell myObj
            if pTo = 0 then set pTo to number of paragraph
            if pTo < 0 then set pTo to (number of paragraph) + pTo
            select (text from paragraph pFrom to paragraph pTo)
        end tell
    end tell
end selectParagraph

-- 選択された段落に行番号を追加
to addParagraphNumbers2(mySep, pSize)
    tell application "Adobe InDesign CS6"
        set loop to number of paragraph of selection
        repeat with i from 1 to loop
            set myNumber to zeroPadding(i, pSize) of me
            set contents of insertion point 1 of paragraph i of selection to ("" & myNumber & mySep)
        end repeat
    end tell
end addParagraphNumbers2

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

display dialog "桁数を入れてください" default answer "3"
set pSize to text returned of result as number
if pSize < 3 then set pSize to 3

set myPrefix to {}
repeat pSize times
    set end of myPrefix to "0"
end repeat
set myPrefix to myPrefix as string

tell application "Adobe InDesign CS6"
    tell active document
        set myObj to text frame 1
    end tell
end tell

selectParagraph(myObj, 4, -1)
addParagraphNumbers2(" : ", pSize)

実行結果

f:id:mikomaya:20141112160035p:plain

f:id:mikomaya:20141112160037p:plain

f:id:mikomaya:20141112160038p:plain

f:id:mikomaya:20141112160040p:plain