This repository has been archived by the owner on Oct 22, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
ttab
executable file
·649 lines (559 loc) · 29.8 KB
/
ttab
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
#!/usr/bin/env bash
# see https://www.npmjs.com/package/ttab#manual-installation
# via http://stackoverflow.com/questions/7171725/open-new-terminal-tab-from-command-line-mac-os-x
#!/usr/bin/env bash
kTHIS_HOMEPAGE='https://github.com/mklement0/ttab'
kTHIS_NAME=${BASH_SOURCE##*/}
kTHIS_VERSION='v0.6.1' # NOTE: This assignment is automatically updated by `make version VER=<newVer>` - DO keep the 'v' prefix.
unset CDPATH # To prevent unexpected `cd` behavior.
# --- Begin: STANDARD HELPER FUNCTIONS
die() { echo "$kTHIS_NAME: ERROR: ${1:-"ABORTING due to unexpected error."}" 1>&2; exit ${2:-1}; }
dieSyntax() { echo "$kTHIS_NAME: ARGUMENT ERROR: ${1:-"Invalid argument(s) specified."} Use -h for help." 1>&2; exit 2; }
# SYNOPSIS
# openUrl <url>
# DESCRIPTION
# Opens the specified URL in the system's default browser.
openUrl() {
local url=$1
open "$url" || { echo "Cannot locate or failed to open default browser; please go to '$url' manually." >&2; return 1; }
}
# Prints the embedded Markdown-formatted man-page source to stdout.
printManPageSource() {
sed -n -e $'/^: <<\'EOF_MAN_PAGE\'/,/^EOF_MAN_PAGE/ { s///; t\np;}' "$BASH_SOURCE"
}
# Opens the man page, if installed; otherwise, tries to display the embedded Markdown-formatted man-page source; if all else fails: tries to display the man page online.
openManPage() {
local pager embeddedText
if ! man 1 "$kTHIS_NAME" 2>/dev/null; then
# 2nd attempt: if present, display the embedded Markdown-formatted man-page source
embeddedText=$(printManPageSource)
if [[ -n $embeddedText ]]; then
pager='more'
command -v less &>/dev/null && pager='less' # see if the non-standard `less` is available, because it's preferable to the POSIX utility `more`
printf '%s\n' "$embeddedText" | "$pager"
else # 3rd attempt: open the the man page on the utility's website
openUrl "${kTHIS_HOMEPAGE}/doc/${kTHIS_NAME}.md"
fi
fi
}
# Prints the contents of the synopsis chapter of the embedded Markdown-formatted man-page source for quick reference.
printUsage() {
local embeddedText
# Extract usage information from the SYNOPSIS chapter of the embedded Markdown-formatted man-page source.
embeddedText=$(sed -n -e $'/^: <<\'EOF_MAN_PAGE\'/,/^EOF_MAN_PAGE/!d; /^## SYNOPSIS$/,/^#/{ s///; t\np; }' "$BASH_SOURCE")
if [[ -n $embeddedText ]]; then
# Print extracted synopsis chapter - remove backticks for uncluttered display.
printf '%s\n\n' "$embeddedText" | tr -d '`'
else # No SYNOPIS chapter found; fall back to displaying the man page.
echo "WARNING: usage information not found; opening man page instead." >&2
openManPage
fi
}
# Indicate by exit code whether the OS version is 10.13 (High Sierra) or above.
isHighSierraOrAbove() { # High Sierra == macOS 10.13
(( $(sw_vers -productVersion | awk -F. '{ print $2 }') >= 13 ))
}
# --- End: STANDARD HELPER FUNCTIONS
# --- PROCESS STANDARD, OUTPUT-INFO-THEN-EXIT OPTIONS.
case $1 in
--version)
# Output version number and exit, if requested.
echo "$kTHIS_NAME $kTHIS_VERSION"$'\nFor license information and more, visit '"$kTHIS_HOMEPAGE"; exit 0
;;
-h|--help)
# Print usage information and exit.
printUsage; exit
;;
--man)
# Display the manual page and exit, falling back to printing the embedded man-page source.
openManPage; exit
;;
--man-source) # private option, used by `make update-doc`
# Print raw, embedded Markdown-formatted man-page source and exit
printManPageSource; exit
;;
--home)
# Open the home page and exit.
openUrl "$kTHIS_HOMEPAGE"; exit
;;
esac
# --- MAIN BODY
# Undocumented DEBUGGING SUPPORT: if the very first argument is --dry-run, we print out the synthesized AppleScript rather than executing it.
printScript=0 dryRun=0
{ [[ $1 == '--dry-run' ]] && { dryRun=1; shift; }; } || { [[ $1 == '--print-script' ]] && { printScript=1; shift; }; }
# Parse options
dirAbs=''
doNotChangeDir=0
tabTitle=''
settingsName=''
inBackground=0
targetTermSpecified=0
inNewWin=0
cls=0
terminalApp="$TERM_PROGRAM" # default to the terminal program that is running this script
while getopts ':wgGqs:t:d:a:' opt; do # $opt will receive the option *letters* one by one; a trailing : means that an arg. is required, reported in $OPTARG.
[[ $opt == '?' ]] && dieSyntax "Unknown option: -$OPTARG"
[[ $opt == ':' ]] && dieSyntax "Option -$OPTARG is missing its argument."
case "$opt" in
w)
inNewWin=1
;;
s)
settingsName=$OPTARG
;;
t)
tabTitle=$OPTARG
;;
d)
dir=$OPTARG
[[ -z $dir ]] && doNotChangeDir=1
(( doNotChangeDir )) || { dirAbs=$(cd -- "$dir" 2>/dev/null && echo "$PWD") || die "No such directory: $dir"; }
;;
a)
terminalApp=$OPTARG
targetTermSpecified=1
;;
g)
inBackground=1
;;
G)
inBackground=2
;;
q)
cls=1
;;
*) # An unrecognized switch.
dieSyntax "DESIGN ERROR: unanticipated option: $opt"
;;
esac
done
shift $((OPTIND - 1)) # Skip the already-processed arguments (options).
# All remaining arguments, if any, make up the command to execute in the new tab/window.
# Determine the terminal application that was explicitly specified or happens to be running this script.
# Currently, the only programs supported are the standard Terminal.app and iTerm.app (iTerm2).
iTerm=0
shopt -s nocasematch # we want to match the application name case-INSensitively.
case $terminalApp in
''|'Apple_Terminal'|'Terminal'|'Terminal.app')
# Note: 'Apple_Terminal' is what $TERM_PROGRAM contains when running from Terminal.app
# Use standard Terminal.app application.
;;
'iTerm'|'iTerm.app'|'iTerm2'|'iTerm2.app')
# Note: 'iTerm.app' is what $TERM_PROGRAM contains when running from iTerm.app
iTerm=1
;;
*)
# If an unknown terminal is specified, we issue a warning and fall back to Terminal.app
echo "WARNING: '$terminalApp' is not a supported terminal application; defaulting to Terminal.app." >&2
;;
esac
shopt -u nocasematch
# Set target-terminal-app-appropriate variables used later.
if (( iTerm )); then
terminalApp='iTerm' # will be used with `activate application`
# Note: iTerm2's AppleScript syntax changed fundamentally in v3 (for the better, but incompatibly so),
# so we need to distinguish versions below.
# $iTermOld reflects a pre-v3 version.
[[ $(osascript -e 'version of application "iTerm"') =~ ^(1|2) ]] && iTermOld=1 || iTermOld=0
else # Terminal.app
terminalApp='Terminal' # will be used with `activate application`
fi
# To be safe, clear any pre-existing variables with names matching those we'll be using below.
for n in ${!CMD_*}; do unset $n; done
# Note: We use *menu-based GUI scripting* rather than *sending keystrokes via CMD_NEWTAB_1='tell application "System Events" to keystroke "t" using {command down}'
# !! We try to be locale-independent, so we don't use menu-item command *names*; this requires us to make the following ASSUMPTIONS, which we expect to hold in the future:
# - the new *window* commands are assumed to be in a *submenu* of the *1st command* ('New Window > ...') of the Shell menu.
# - the new *tab* commands are assumed to be in a *submenu* of the *2nd command* ('New Tab > ...') of the Shell menu.
# (a) compared to sending a keystroke, this is more robust and predictable; with sending a keystroke, the shell command to execute is *sometimes* sent to the *previous* tab, as the keystroke may not have been processed yet.
# In the default case, the GUI scripting finds the command by its keyboard shortcut so as to work locale-independently; it does, however, make the following assumptions (other than the pretty safe assumption that the command is in the 3rd menu from the left, the "Shell" menu in English):
# (b) it also allows us to create new tabs *with specific settings*, by finding the menu item by *name* (settings names are locale-*in*dependent, fortunately)
# Using this is preferable to trying to apply settings *after* tab creation with `set current settings of selected tab ...`, as the latter only applies *visual* attributes, not *behavioral* (such as what to do when the shell exits)
if (( inNewWin )); then # create the tab in a NEW WINDOW
if (( iTerm )); then
if (( iTermOld )); then # OLD iTerm syntax (v2-)
# Note: Passing an empty $settingsName is accepted as specifying the default profile.
CMD_NEWTAB_1='tell application "iTerm" to launch (make new terminal) session "'"$settingsName"'"'
if (( inBackground == 2 )); then # For use with -G: commands for saving and restoring the previous state within iTerm
CMD_SAVE_ACTIVE_TAB='set prevTerm to current terminal'
CMD_REACTIVATE_PREV_TAB='set current terminal to prevTerm'
fi
else # NEW iTerm syntax (introduced in v3)
if [[ -n $settingsName ]]; then
CMD_NEWTAB_1='create window with profile "'"$settingsName"'"'
else
CMD_NEWTAB_1='create window with default profile'
fi
if (( inBackground == 2 )); then # For use with -G: commands for saving and restoring the previous state within iTerm
CMD_SAVE_ACTIVE_TAB='set prevWin to current window'
# !! Sadly, neither `set current window to` nor `set frontmost of <window> to true` work, so we must use GUI scripting.
CMD_REACTIVATE_PREV_TAB='tell application "System Events" to perform action "AXRaise" of window (name of prevWin) of application process "iTerm2"'
fi
fi
else # Terminal.app
if [[ -n $settingsName ]]; then
CMD_NEWTAB_1='tell application "System Events" to tell menu 1 of menu item 1 of menu 1 of menu bar item 3 of menu bar 1 of application process "Terminal" to click menu item "'"$settingsName"'"'
CMD_NEWTAB_2='set newTab to selected tab of front window'
else
CMD_NEWTAB_1=''
CMD_NEWTAB_2='set newTab to do script' # note that running `do script` without arguments (i.e., without a suffix specifying the target window (e.g., 'in front window')) creates a *new* window.
fi
if (( inBackground == 2 )); then # For use with -G: commands for saving and restoring the previous state within Terminal
CMD_SAVE_ACTIVE_TAB='set prevWin to front window'
CMD_REACTIVATE_PREV_TAB='set frontmost of prevWin to true' # Note that while *Terminal.app*'s windows have a `frontmost` property that allows their activation within the app, most other (all other?) apps' windows do not.
fi
fi
else # Create the new tab in the CURRENT WINDOW (unlike `do shell script` with no target for creating a new *window*, `do shell script in front window` simply executes in the *current* tab, and there's no direct way to target a new one).
if (( iTerm )); then
if (( iTermOld )); then # OLD iTerm syntax (v2-)
# Note: Passing an empty $settingsName is accepted as specifying the default profile.
CMD_NEWTAB_1='tell application "iTerm" to launch (current terminal) session "'"$settingsName"'"'
if (( inBackground == 2 )); then # For use with -G: commands for saving and restoring the previous state within iTerm
CMD_SAVE_ACTIVE_TAB='set prevSess to current session of current terminal'
CMD_REACTIVATE_PREV_TAB='select prevSess'
fi
else # NEW iTerm syntax (introduced in v3)
if [[ -n $settingsName ]]; then
CMD_NEWTAB_1='tell current window to create tab with profile "'"$settingsName"'"'
else
CMD_NEWTAB_1='tell current window to create tab with default profile'
fi
if (( inBackground == 2 )); then # For use with -G: commands for saving and restoring the previous state within iTerm
CMD_SAVE_ACTIVE_TAB='set prevTab to current tab of current window'
CMD_REACTIVATE_PREV_TAB='select prevTab'
fi
fi
else # Terminal.app
if [[ -n $settingsName ]]; then
CMD_NEWTAB_1='tell application "System Events" to tell menu 1 of menu item 2 of menu 1 of menu bar item 3 of menu bar 1 of application process "Terminal" to click menu item "'"$settingsName"'"'
else
CMD_NEWTAB_1='tell application "System Events" to tell menu 1 of menu item 2 of menu 1 of menu bar item 3 of menu bar 1 of application process "Terminal" to click (first menu item whose value of attribute "AXMenuItemCmdChar" is "T" and value of attribute "AXMenuItemCmdModifiers" is 0)'
fi
CMD_NEWTAB_2='set newTab to selected tab of front window'
if (( inBackground == 2 )); then # For use with -G: commands for saving and restoring the previous state within Terminal
if isHighSierraOrAbove; then
# !! In 10.13 (High Sierra), Terminal.app switched to treating tabs like individual *windows*.
CMD_SAVE_ACTIVE_TAB='set prevTab to front window'
CMD_REACTIVATE_PREV_TAB='set frontmost of prevTab to true'
else
CMD_SAVE_ACTIVE_TAB='set prevTab to (selected tab of front window)'
CMD_REACTIVATE_PREV_TAB='set selected of prevTab to true'
fi
fi
fi
fi
# Define the command that *synchronously* actives iTerm / Terminal.
# Note that this is neeeded both with and without -g / -G:
# * With -g / -G, unfortunately, the terminal app must still be activated briefly
# in order for GUI scripting to work correctly, with the previously active
# application getting reactivated afterward.
# * With foregound operation, we also activate explicitly, so as to support
# invocation from helper apps such as Alfred where the terminal may be
# created implicitly and not gain focus by default.
# !! On 10.10+, activate is no longer *synchronous*, so we must wait until Terminal is truly activated (frontmost)
CMD_ACTIVATE='if not frontmost then
activate
repeat until frontmost
delay 0.1
end repeat
end if'
# For use with -g and -G: commands for saving and restoring the previous application
if (( inBackground )); then
CMD_SAVE_ACTIVE_APPNAME='set prevAppPath to path to frontmost application as text'
CMD_REACTIVATE_PREV_APP='activate application prevAppPath'
fi
# Optional commands that are only used if the relevant options were specified.
quotedShellCmds=''
shellCmdTokens=( "$@" )
if (( ${#shellCmdTokens[@]} )); then # Shell command(s) specified.
if (( ${#shellCmdTokens[@]} == 1 )); then # Could be a mere command name like 'ls' or a multi-command string such as 'git bash && git status'
# If only a single string was specified as the command to execute in the new tab:
# It could either be a *mere command name* OR a *quoted string containing MULTIPLE commands*.
# We use `type` to determine if it is a mere command name / executable in the
# current dir., otherwise we assume that the operand is a multi-command string
# in which case we must use `eval` to execute it.
# Note: Blindly prepending `eval` would work in MOST, but NOT ALL cases,
# such as with commands whose names happen to contain substrings
# that look like variable references (however rare that may be).
([[ -n $dirAbs ]] && cd "$dirAbs"; type "${shellCmdTokens[0]}" &>/dev/null) || shellCmdTokens=( 'eval' "${shellCmdTokens[@]}" )
fi
# The tricky part is to quote the command tokens properly when passing them to AppleScript:
# Quote all parameters (as needed) using printf '%q' - this will perform backslash-escaping.
# This will allow us to not have to deal with double quotes inside the double-quoted string that will be passed to `do script`.
quotedShellCmds=$(printf ' %q' "${shellCmdTokens[@]}")
# Note: $quotedShellCmds now has a leading space, but that's benign (a *trailing* space, by contrast, would be a problem with iTerm's `write <session> text ...` command)
# !! [AUTO-DERIVING A TAB TITLE DISABLED - there's ultimately no heuristic that's guaranteed to result in a meaningful title. Let users specify a title explicitly, if needed. ]
# # If no title was specified, derive it from the command specified.
# if [[ -z $tabTitle ]]; then # no explicit title specified
# # Use the command's first (meaningful) token as the tab title.
# i=0
# [[ ${shellCmdTokens[i]} =~ ^exec|eval$ ]] && (( ++i ))
# [[ ${shellCmdTokens[i]} == cd ]] && (( ++i ))
# tabTitle=$(printf %s "${shellCmdTokens[i]}" | tr -d '\\"')
# fi
fi # if (( ${#shellCmdTokens[@]} )
# Note: The desired behavior is to ALWAYS OPEN A TAB IN THE DIRECTORY THE CALLER
# CONSIDERS CURRENT, whether the new tab is being opened in the current or
# a new window (unless a target dir. is explicitly specified with -d <dir>).
# Terminal and iTerm have different default behaviors, so we need to account for
# that:
# * When opening a tab in a new *window*, both Terminal and iTerm default to the *home* dir.
# * When opening a new in the current window,
# * Terminal: the *caller's currrent dir., as known to Terminal* (see below) is used.
# Also, to be safe, if a target terminal is explicitly specified, we also
# default to issuing a `cd` command, because it might be a different terminal than the current one.
if (( iTerm || targetTermSpecified )); then
# iTerm2 always defaults to the home dir., so we must always add an explicit `cd` command to ensure that the current dir. is used.
if [[ -z $dirAbs ]]; then
dirAbs=$PWD
fi
else
# While Terminal.app does default to the caller's current dir. when creating a tab
# in the *current* window, it doesn't necessarily know the *immediate caller's* true $PWD,
# so we have to compensate for that:
# Terminal.app only knows the working directory of the *top-level* shell running in each tab (as it defines an aux. function,
# update_terminal_cwd(), that is called via $PROMPT_COMMAND every time the prompt is displayed).
# Thus, when this script is invoked inside another script, it is the *top-level* shell's working directory that is invariably used by
# Terminal, even if the invoking script has changed the working directory. Since this is counter-intuitive, we compensate here
# by explicitly setting the working directory to the invoking script's with a prepended 'cd' command.
# $SHLVL tells us the nesting level of the current shell:
# 1 == top-level shell; since this script itself runs in a subshell (2, if invoked directly from the top-level shell), we can safely assume
# that another *script* has invoked us, if $SHLVL >= 3.
if [[ -z $dirAbs && ($SHLVL -ge 3 || $inNewWin -eq 1) ]]; then
dirAbs=$PWD
fi
fi
# Prepend the 'cd' command, if specified or needed and unless suppress.
if [[ $doNotChangeDir -eq 0 && -n $dirAbs ]]; then
quotedCdCmd=$(printf 'cd %q' "$dirAbs")
if [[ -n $quotedShellCmds ]]; then
quotedShellCmds="$quotedCdCmd;$quotedShellCmds"
else
quotedShellCmds=$quotedCdCmd
fi
fi
# Append the 'clear' command, if requested.
if (( cls )); then
if [[ -n $quotedShellCmds ]]; then
quotedShellCmds="$quotedShellCmds && clear"
else
quotedShellCmds='clear'
fi
fi
# Synthesize the full shell command.
if [[ -n $quotedShellCmds ]]; then
# Pass the commands as a single AppleScript string, of necessity double-quoted.
# For the benefit of AppleScript
# - embedded backslashes must be escaped by doubling them
# - embedded double quotes must be backlash-escaped
quotedShellCmdsForAppleScript=${quotedShellCmds//\\/\\\\}
quotedShellCmdsForAppleScript=${quotedShellCmdsForAppleScript//\"/\\\"}
if (( iTerm )); then
if (( iTermOld )); then # OLD iTerm syntax (v2-)
CMD_CUSTOM="write (current session of current terminal) text \"${quotedShellCmdsForAppleScript}\""
else # NEW iTerm syntax (introduced in v3)
CMD_CUSTOM="tell current session of current window to write text \"${quotedShellCmdsForAppleScript}\""
fi
else
CMD_CUSTOM="do script \"${quotedShellCmdsForAppleScript}\" in newTab"
fi
fi
if [[ -n $tabTitle ]]; then # custom tab title specified
# For the benefit of AppleScript
# - embedded backslashes must be escaped by doubling them
# - embedded double quotes must be backlash-escaped
tabTitle=${tabTitle//\\/\\\\}
tabTitle=${tabTitle//\"/\\\"}
if (( iTerm )); then
if (( iTermOld )); then # OLD iTerm syntax (v2-)
CMD_TITLE="tell current session of current terminal to set name to \"$tabTitle\""
else # NEW iTerm syntax (introduced in v3)
CMD_TITLE="tell current session of current window to set name to \"$tabTitle\""
fi
else # Terminal.app
CMD_TITLE="set custom title of newTab to \"$tabTitle\""
fi
fi
# Now, synthesize the entire AppleScript
# !! At least on 10.10, the commands to save the active application and to reactivate it later must be OUTSIDE of the tell application "Terminal" block to work.
read -d '' -r script <<EOF
$CMD_SAVE_ACTIVE_APPNAME
tell application "$terminalApp"
$CMD_ACTIVATE
$CMD_SAVE_ACTIVE_TAB
$CMD_NEWTAB_1
$CMD_NEWTAB_2
$CMD_TITLE
$CMD_CUSTOM
$CMD_REACTIVATE_PREV_TAB
end tell
$CMD_REACTIVATE_PREV_APP
return
EOF
(( dryRun || printScript )) && { printf %s "$script"; (( dryRun )) && exit; }
# Execute the synthesized AppleScript.
# Note: By using `exec` we pass `osascript`'s exit code through and
# END EXECUTION HERE, so that that the `: <<...` here-doc for the man page
# below doesn't reset the exit code to 0.
exec osascript <<<"$script"
####
# MAN PAGE MARKDOWN SOURCE
# - Place a Markdown-formatted version of the man page for this script
# inside the here-document below.
# The document must be formatted to look good in all 3 viewing scenarios:
# - as a man page, after conversion to ROFF with marked-man
# - as plain text (raw Markdown source)
# - as HTML (rendered Markdown)
# Markdown formatting tips:
# - GENERAL
# To support plain-text rendering in the terminal, limit all lines to 80 chars.,
# and, for similar rendering as HTML, *end every line with 2 trailing spaces*.
# - HEADINGS
# - For better plain-text rendering, leave an empty line after a heading.
# marked-man will remove it from the ROFF version.
# - The first heading must be a level-1 heading containing the utility
# name and very brief description; append the manual-section number
# directly to the CLI name; e.g.:
# # foo(1) - does bar
# - The 2nd, level-2 heading must be '## SYNOPSIS' and the chapter's body
# must render reasonably as plain text, because it is printed to stdout
# when `-h`, `--help` is specified:
# Use 4-space indentation without markup for both the syntax line and the
# block of brief option descriptions; represent option-arguments and operands
# in angle brackets; e.g., '<foo>'
# - All other headings should be level-2 headings in ALL-CAPS.
# - TEXT
# - Use NO indentation for regular chapter text; if you do, it will
# be indented further than list items.
# - Use 4-space indentation, as usual, for code blocks.
# - Markup character-styling markup translates to ROFF rendering as follows:
# `...` and **...** render as bolded (red) text
# _..._ and *...* render as word-individually underlined text
# - LISTS
# - Indent list items by 2 spaces for better plain-text viewing, but note
# that the ROFF generated by marked-man still renders them unindented.
# - End every list item (bullet point) itself with 2 trailing spaces too so
# that it renders on its own line.
# - Avoid associating more than 1 paragraph with a list item, if possible,
# because it requires the following trick, which hampers plain-text readability:
# Use ' <space><space>' in lieu of an empty line.
####
: <<'EOF_MAN_PAGE'
# ttab(1) - open a new Terminal.app / iTerm.app tab or window
## SYNOPSIS
Opens a new terminal tab or window in OS X's Terminal application or iTerm2.
ttab [-w] [-s <settings>] [-t <title>] [-q] [-g|-G] [-d <dir>] [<cmd> ...]
-w open new tab in new terminal window
-s <settings> assign a settings set (profile)
-t <title> specify title for new tab
-q clear the new tab's screen
-g create tab in background (don't activate Terminal/iTerm)
-G create tab in background and don't activate new tab
-d <dir> specify working directory; -d '' disables inheriting
the current dir.
-a Terminal|iTerm2 open tab or window in Terminal.app / iTerm2
<cmd> ... command to execute in the new tab
"<cmd> ...; ..." multi-command command line (passed as single operand)
Standard options: `--help`, `--man`, `--version`, `--home`
## DESCRIPTION
`ttab` opens a new Terminal or iTerm2 tab with a variety of options,
including executing a command in the new tab, assigning a title and working
directory, and opening the tab in a new window.
Note: iTerm2 support is experimental in that it is currently not covered by
the automated tests run before every release.
IMPORTANT: **Terminal/iTerm2 must be allowed assistive access** in order
for this utility to work, which requires one-time authorization with
administrative privileges. If you get error messages instead of being prompted,
authorize the application via
System Preferences > Security & Privacy > Privacy > Accessibility.
The new tab will run a login shell (i.e., load the user's shell profile)
and by default inherit the working directory from the parent shell.
When specifying a command to execute in the new tab, quoted parameters are
handled properly and there's no need to quote the command as a whole,
provided it is a *single* command.
Prefix such a single command with `exec` to exit the shell after the command
terminates. If the tab's settings are configured to close tabs on termination
of the shell, the tab will close automatically.
To specify *multiple* commands, pass them as a *single, quoted string*.
Use `exit` as the last command to automatically close the tab when the
command terminates, assuming the tab's settings are configured to close the
tab on termination of the shell.
Precede `exit` with `read -rsn 1` to wait for a keystroke first.
## OPTIONS
* `-w`
creates the new tab in a new window rather than in the front
window.
* `-s <settings>`
specifies the settings set (profile) to apply to the new tab, determining
the appearance and behavior of the new tab.
o Terminal: settings sets are defined in Preferences > Profiles;
name matching is case-*in*sensitive, and specifying nonexistent settings
causes an error.
o iTerm2: profiles are defined in Preferences > Profiles; name matching
is case-*sensitive*, and specifying a nonexistent profile causes an error.
* `-t <title>`
specifies a custom title to assign to the new tab; otherwise, if a
command is specified, its first token will become the new tab's title.
CAVEAT: As of iTerm2 v3.0.9, choosing a title that exactly matches the
settings name specified with `-s` causes the title to be ignored.
* `-d <dir>`
explicitly specifies a working directory for the new tab; by default, the
invoking shell's working directory is inherited (even if `-w` is also
specified) - use `-d ''` to disable.
* `-q`
(*q*uiet) issues a `clear` command after opening the new tab.
Note that output will temporarily be visible while the tab is being opened;
also, clearing is not performed if any command passed reports an overall
nonzero exit code, so as to allow failures to be examined.
* `-g`
(back*g*round) causes Terminal/iTerm2 not to activate, if it isn't the
frontmost application); within the application, however, the new tab will
become the active tab; useful in scripts that launch other applications and
don't want Terminal/iTerm2 to steal focus later.
* `-G`
causes Terminal/iTerm2 not to activate *and* the active element within
the application not to change; i.e., the active window and tab stay the
same. If Terminal/iTerm2 happens to be frontmost, the new tab will
effectively open in the background.
NOTE: With `-g` or `-G` specified, for technical reasons, Terminal/iTerm2 /
the new tab will still activate *briefly, temporarily* in most scenarios.
* `-a Terminal` or `-a iTerm2`
explicitly specifies the terminal application to use; by default, the
terminal application from which this utility is run is implied, if
supported, with Terminal used as the fallback.
This options is useful for calling this utility from non-terminal
applications such as Alfred (https://www.alfredapp.com/).
## STANDARD OPTIONS
All standard options provide information only.
* `-h, --help`
Prints the contents of the synopsis chapter to stdout for quick reference.
* `--man`
Displays this manual page, which is a helpful alternative to using `man`,
if the manual page isn't installed.
* `--version`
Prints version information.
* `--home`
Opens this utility's home page in the system's default web browser.
## LICENSE
For license information and more, visit this utility's home page by running
`ttab --home`.
## EXAMPLES
# Open new tab in current terminal window:
ttab
# Open new tab in new terminal window:
ttab -w
# Open new tab with title 'Green' using settings (profile) 'Grass':
ttab -t Green -s Grass
# Open new tab and execute a command in it:
ttab ls -l "$HOME/Library/Application Support"
# Open new tab with specified working dir. and execute a command in it:
ttab -d "$HOME/Library/Application Support" ls -l
# Execute a command and exit.
# If configured via the default profile, also close the tab.
ttab exec /path/to/someprogram arg1 arg2
# Pass a multi-command string as a single, quoted string, wait for a
# keystroke, then exit.
ttab 'ls "$HOME/Library/Application Support";
echo Press any key to exit; read -rsn 1; exit'
# Create a new tab explicitly in iTerm2.
ttab -a iTerm2 echo "Hi from iTerm2."
EOF_MAN_PAGE