Nested Tell Blocks

To further improve script readability and understanding, tell blocks can contain other tell blocks that target scriptable elements or objects belonging to the scriptable element or object targeted in the outermost tell block. For example, the Desktop Setup script can be rewritten so that the actions targeting the front window are enclosed within their own tell blocks within the outer Finder tell block, as shown in the following script:

Click to open example in the Script Editor applicationThe Desktop Setup script re-written to use nested tell blocks.
tell application "Finder"
 close every window
 open home
 tell the front Finder window
 set toolbar visible to true
 set the sidebar width to 135
 set the current view to column view
 set the bounds to {36, 116, 511, 674}
 end tell
 open folder "Documents" of home
 tell the front Finder window
 set toolbar visible to false
 set the current view to flow view
 set the bounds to {528, 116, 1016, 674}
 end tell
 select the last Finder window
end tell

The technique of placing tell blocks within other tell blocks is referred to as nesting tell blocks and is found quite often in scripts. And, since scripts are read from top to bottom and from left to right, the use of tell blocks makes it very easy to quickly see how a script is designed.

For example, the previous script starts with two commands to the Finder followed by four commands to the front Finder window followed by a single command to the Finder followed by four commands to the front Finder window again and then finishes with a single command to the Finder.

Since you’ll often edit your scripts later (perhaps a long time later), it’s important to write your scripts in a manner that is easy to understand and review. Using tell blocks and nested tell blocks in your scripts enables you to write scripts that are readable and that make sense to yourself and others. You can use as many nested tell blocks as you like in your scripts, just remember:

If you begin a tell block, you must end the tell block with an end tell statement.

If you entered the original version Desktop Setup script in the Script Editor, edit it now to match the version with the nested tell blocks. Be sure to remove the possessive phrase of the front Finder window when you create the nested tell blocks. The function played by that phrase in defining the containment hierarchy of the front Finder window object is now played by the nested tell statement, tell the front Finder window.

Notice there are two nested tell blocks addressing the front Finder window in the Desktop Setup script. Why? Shouldn’t the second nested tell block be addressing the second Finder window?

No, when the second Finder window is opened, it automatically becomes the frontmost Finder window in the stack of open Finder windows. Therefore, it is now the front Finder window and can be targeted in the same manner as the previous window.