Applescript (osascript): opening split panes in iTerm 2 and performing commands

前端 未结 6 1247
生来不讨喜
生来不讨喜 2021-01-05 01:14

The following works to open two tabs in iTerm 2.

I can\'t seem to figure out how to get this to using split panes instead.

I\'ve tried appl

6条回答
  •  一整个雨季
    2021-01-05 01:59

    Update: iTerm2 v3 has much-improved, but incompatible AppleScript support - see https://www.iterm2.com/documentation-scripting.html

    To provide some background to @Joel's own answer:

    iTerm 2's AppleScript support (as of iTerm 2 v1.0.0.201306220):

    • is incomplete: there is no support to script split panes - hence the OP is resorting to the suboptimal technique of sending keystrokes.

    • exhibits some bizarre behavior: when compiling (in AppleScript Editor) a tell "System Events" ... statement inside a tell application "iTerm" block, the prefix i term application is inexplicably inserted before the "System Events" - since the code below is not precompiled, this prefix is not included so as to avoid problems in the future.

    • has bugs / is inconsistent with its dictionary: what the dictionary describes as the exec command - which doesn't actually work - is in reality fulfilled by the write text command: it executes the argument passed or - if the argument has a trailing space - simply "types" the argument without submitting it.

    Here's the solution with split panes based on the workaround (sending keystrokes) - a bash script invoking AppleScript code via osascript:

    Limitations, due to panes not being part of the dictionary:

    • the other pane that is opened cannot be named
    • no command can be sent to the other pane
    #!/usr/bin/env bash
    
    projectFolder="$HOME/Desktop" # example
    osascript <<-EOF
      tell application "iTerm"
        tell (make new terminal) # Create a new pseudo terminal...
          tell (launch session "Default session") # ... and open a session (window)
            # Name the new window (its original pane).
            set name to "Server"
            # Execute the 'cd' command in the original pane.
            write text "cd '$projectFolder'"
            # Create a new split pane, horizontally, by sending ⌘⇧-D 
            tell application "System Events" to keystroke "d" using {shift down, command down}
              # !! Note: We canNOT:
              #  - name this pane separately
              #  - execute a command in it.
            # Return to the original pane, by sending ⌘-[ 
            tell application "System Events" to keystroke "[" using {command down}
          end tell
        end tell
      end tell
    EOF
    

提交回复
热议问题