InDesign scripting : lesson 18

ok — that’s enough lollygaggin’ around. let’s get back into it with a simple one. here’s how to shorten a filepath.

way back in lesson 12 you saw how to save a pdf into the same folder as your InDesign file (that script actually created a subfolder to contain the pdf — keeping everything nice and neat).

but sometimes you may want to go further UP the folder hierarchy. so, for example, if your InDesign file is here :

MacGrunt > Users > ThisUser > Documents > InDesign Files > TheDoc.indd

rather than accessing the folder containing the file — “InDesign Files” — you want to access the next one up — “Documents”. here’s how.

you get the file path of an InDesign document like this :

tell application "Adobe InDesign CS4"
  set theFilepath to file path of active document as string
end tell
return theFilepath

resulting in a string like this :

"MacGrunt:Users:ThisUser:Documents:InDesign Files:"

using text item delimiters, we can get the separate parts of that path :

set text item delimiters of AppleScript to {":"}
set theFilepathBits to text items of theFilepath
set text item delimiters of AppleScript to ""
return theFilepathBits

resulting in a list of elements :

{"MacGrunt", "Users", "ThisUser", "Documents", "InDesign Files", ""}

notice the end of the list is an empty item. no doubt some Applescript guru can explain why that happens.

we can then join the relevant bits back together :

set text item delimiters of AppleScript to ":"
set newFilepath to text items 1 thru 4 of theFilepath as string
set text item delimiters of AppleScript to ""
return newFilepath

giving us the string we’re looking for :

"MacGrunt:Users:ThisUser:Documents:"

now, that’s only going to work if your InDesign files are always six levels down in the hierarchy. but what we really want is a way to access the folder that’s one above the InDesign file no matter how deeply the file is buried.

luckily Applescript also lets you count backwards through a list. so, in the above example, “” is text item -1, “InDesign Files” is text item -2, etc.

so, what we need is this :

tell application "Adobe InDesign CS4"
  set theFilepath to file path of active document as string
end tell
set text item delimiters of AppleScript to ":"
set newFilepath to text items 1 thru -3 of theFilepath as string
set text item delimiters of AppleScript to ""
return newFilepath

that’s it — pretty simple, but pretty handy. with this little trick up your sleeve you’ll be throwing files all over the place with Applescript now.

keep grunting.

macgrunt icon