This commit is contained in:
Joe Lillibridge 2024-10-29 18:12:34 -05:00
parent 860848da23
commit 15e48d1c97
No known key found for this signature in database
35 changed files with 4004 additions and 3 deletions

40
.SpaceVim.d/init.toml Normal file
View File

@ -0,0 +1,40 @@
#=============================================================================
# basic.toml --- basic configuration example for SpaceVim
# Copyright (c) 2016-2023 Wang Shidong & Contributors
# Author: Wang Shidong < wsdjeg@outlook.com >
# URL: https://spacevim.org
# License: GPLv3
#=============================================================================
# All SpaceVim option below [option] section
[options]
# set spacevim theme. by default colorscheme layer is not loaded,
# if you want to use more colorscheme, please load the colorscheme
# layer
colorscheme = "gruvbox"
colorscheme_bg = "dark"
# Disable guicolors in basic mode, many terminal do not support 24bit
# true colors
enable_guicolors = false
# Disable statusline separator, if you want to use other value, please
# install nerd fonts
statusline_separator = "nil"
statusline_iseparator = "bar"
buffer_index_type = 4
windows_index_type = 3
enable_tabline_filetype_icon = false
enable_statusline_mode = false
statusline_unicode = false
# Enable vim compatible mode, avoid changing origin vim key bindings
vimcompatible = true
# Enable autocomplete layer
[[layers]]
name = 'autocomplete'
auto_completion_return_key_behavior = "complete"
auto_completion_tab_key_behavior = "cycle"
[[layers]]
name = 'shell'
default_position = 'top'
default_height = 30

View File

@ -0,0 +1,23 @@
board_manager:
additional_urls: []
daemon:
port: "50051"
directories:
data: /Users/joelillibridge/Library/Arduino15
downloads: /Users/joelillibridge/Library/Arduino15/staging
user: /Users/joelillibridge/Documents/Arduino
library:
enable_unsafe_install: false
logging:
file: ""
format: text
level: info
metrics:
addr: :9090
enabled: true
output:
no_color: false
sketch:
always_export_binaries: false
updater:
enable_notification: true

1
.bashrc Normal file
View File

@ -0,0 +1 @@
[ -f ~/.fzf.bash ] && source ~/.fzf.bash

View File

@ -0,0 +1,36 @@
# This is the 1Password SSH agent config file, which allows you to customize the
# behavior of the SSH agent running on this machine.
#
# You can use it to:
# * Enable keys from other vaults than the Private vault
# * Control the order in which keys are offered to SSH servers
#
# EXAMPLE
#
# By default, all keys in your Private vault(s) are enabled:
#
# [[ssh-keys]]
# vault = "Private"
#
# You can enable more keys by adding more `[[ssh-keys]]` entries.
# For example, to first enable item "My SSH Key" from "My Custom Vault":
#
# [[ssh-keys]]
# item = "My SSH Key"
# vault = "My Custom Vault"
#
# [[ssh-keys]]
# vault = "Private"
#
# You can test the result by running:
#
# SSH_AUTH_SOCK=~/Library/Group\ Containers/2BUA8C4S2C.com.1password/t/agent.sock ssh-add -l
#
# More examples can be found here:
# https://developer.1password.com/docs/ssh/agent/config
[[ssh-keys]]
vault = "Private"
[[ssh-keys]]
item = "SSH Key (target github)"
vault = "Target"

View File

@ -0,0 +1,26 @@
# The Fuck settings file
#
# The rules are defined as in the example bellow:
#
# rules = ['cd_parent', 'git_push', 'python_command', 'sudo']
#
# The default values are as follows. Uncomment and change to fit your needs.
# See https://github.com/nvbn/thefuck#settings for more information.
#
# rules = [<const: All rules enabled>]
# exclude_rules = []
# wait_command = 3
# require_confirmation = True
# no_colors = False
# debug = False
# priority = {}
# history_limit = None
# alter_history = True
# wait_slow_command = 15
# slow_commands = ['lein', 'react-native', 'gradle', './gradlew', 'vagrant']
# repeat = False
# instant_mode = False
# num_close_matches = 3
# env = {'LC_ALL': 'C', 'LANG': 'C', 'GIT_TRACE': '1'}
# excluded_search_path_prefixes = []

18
.config/zed/settings.json Normal file
View File

@ -0,0 +1,18 @@
// Zed settings
//
// For information on how to configure Zed, see the Zed
// documentation: https://zed.dev/docs/configuring-zed
//
// To see all of Zed's default settings without changing your
// custom settings, run `zed: open default settings` from the
// command palette (cmd-shift-p / ctrl-shift-p)
{
"vim_mode": true,
"ui_font_size": 16,
"buffer_font_size": 16,
"theme": {
"mode": "system",
"light": "One Light",
"dark": "One Dark"
}
}

53
.config/zsh/aliases Normal file
View File

@ -0,0 +1,53 @@
# aliases
alias more=less
alias mroe=less
alias tk=take
alias top10="print -l -- \${(o)history%% *} | uniq -c | sort -nr | head -n 10"
alias zsh-plugins="ls \$ZPLUGINDIR"
# git aliases
alias g=git
alias gi=git
alias gg='git grep'
alias gs='git status'
alias gd='git diff'
# YADM aliases
alias y="yadm"
alias ys="y status"
alias ysu="ys -u"
alias yg='y grep'
alias yd='y diff'
# Homebrew aliases
alias b="brew"
alias bi="b info"
alias bin="b install"
alias bs="b search"
alias bv="brew-visit" # points to the function below because I'm complicated
# These depend on some installed packages, so just to be safe
alias ls="ls -F"
[[ "$(command -v lsd)" ]] && alias ls="lsd -F"
[[ "$(command -v bat)" ]] && alias cat="bat"
[[ "$(command -v htop)" ]] && alias top="htop"
[[ "$(command -v duf)" ]] && alias df="duf"
# Toggle hidden files in Finder
alias showhidden='defaults write com.apple.finder AppleShowAllFiles TRUE; killall Finder'
alias hidehidden='defaults write com.apple.finder AppleShowAllFiles FALSE; killall Finder'
# For passing github token to gh
alias gh="op plugin run -- gh"
system_type=$(uname -s)
if [ "$system_type" = "Darwin" ]; then
# Open iTerm from VS Code terminal
# May refactor this to make the alias available in all non-iTerm terminals
[ ! -v "$IN_VS_CODE_TERMINAL" ] && alias iterm="open -a iTerm"
fi
if [ -e ./aliases.local ]; then
source ./aliases.local
fi

View File

View File

@ -0,0 +1,9 @@
# shellcheck disable=SC2148
# VPN aliases
CISCO_VPN_CLI="/opt/cisco/anyconnect/bin/vpn"
TGT_VPN="TGT_VPN_MAC"
[ -x $CISCO_VPN_CLI ] && alias vpn-connect="\$CISCO_VPN_CLI connect \$TGT_VPN"
[ -x $CISCO_VPN_CLI ] && alias vpn-disconnect="\$CISCO_VPN_CLI disconnect"
# Will delete this soon in favor of something better
[ -x "${HOME}/bin/auto-vpn.sh" ] && alias vpn="\${HOME}/bin/auto-vpn.sh"

View File

@ -0,0 +1,17 @@
brew-visit() {
# DESC: Open a Homebrew formula's web page
# ARGS: $1: Homebrew formula name
# REQS: MacOS
# USAGE: brew-visit [url]
INFO=$(brew info "${1}")
INFO_CODE=$?
[ $INFO_CODE -ne 0 ] && return 1
URL=$(echo $INFO | grep ^http | head -1)
if [ -z $URL ]; then
echo "There doesn't appear to be a URL in the info about ${1}."
return 1
fi
open "$URL"
}

5
.config/zsh/functions/f Normal file
View File

@ -0,0 +1,5 @@
f() { # DESC: Opens the Finder to specified directory. (Default is current oath) # ARGS: $1 (optional): Path to open in finder
# REQS: MacOS
# USAGE: f [path]
open -a "Finder" "${1:-.}"
}

7
.config/zsh/functions/ql Normal file
View File

@ -0,0 +1,7 @@
ql() {
# DESC: Opens files in MacOS Quicklook
# ARGS: $1 (optional): File to open in Quicklook
# REQS: MacOS
# USAGE: ql [file1] [file2]
qlmanage -p "${*}" &>/dev/null
}

View File

@ -0,0 +1,2 @@
# See https://github.com/dduan/tre/blob/main/README.md
tre() { command tre "$@" -e && source "/tmp/tre_aliases_$USER" 2>/dev/null; }

13
.fzf.bash Normal file
View File

@ -0,0 +1,13 @@
# Setup fzf
# ---------
if [[ ! "$PATH" == */opt/homebrew/opt/fzf/bin* ]]; then
PATH="${PATH:+${PATH}:}/opt/homebrew/opt/fzf/bin"
fi
# Auto-completion
# ---------------
[[ $- == *i* ]] && source "/opt/homebrew/opt/fzf/shell/completion.bash" 2> /dev/null
# Key bindings
# ------------
source "/opt/homebrew/opt/fzf/shell/key-bindings.bash"

16
.gitignore vendored
View File

@ -1,7 +1,11 @@
*.sock *.sock
*.swp *.swp
__pycache__/
.1password .1password
.anyconnect .anyconnect
.arduinoIDE/localization-cache
.arduinoIDE/recent-sketches.json
.arduinoIDE/recentworkspace.json
.awesomecache .awesomecache
.bash_history .bash_history
.cache .cache
@ -9,7 +13,10 @@
.cisco .cisco
.colima .colima
.config/gtk-2.0/ .config/gtk-2.0/
.config/nvim
.config/zed/**/*.mdb
.config/zsh/plugins .config/zsh/plugins
.cups
.docker/ .docker/
.DS_Store .DS_Store
.gitignore_global .gitignore_global
@ -17,11 +24,13 @@
.gnupg .gnupg
.gnupg_* .gnupg_*
.lesshst .lesshst
.local/bin/ .local/bin
.local/share .local/share
.local/state
.node_repl_history .node_repl_history
.npm .npm
.nvm .nvm
.openstack_history
.rest-client .rest-client
.sonarlint .sonarlint
.ssh .ssh
@ -29,6 +38,7 @@
.Trash .Trash
.vault-token .vault-token
.viminfo .viminfo
.vimrc_back
.vscode .vscode
.wget-hsts .wget-hsts
.yarn .yarn
@ -38,6 +48,7 @@
.zsh_history .zsh_history
.zsh_sessions .zsh_sessions
awesomecache awesomecache
Applications
Desktop Desktop
Development Development
Documents Documents
@ -53,3 +64,6 @@ Public
src src
tmp tmp
yarn.lock yarn.lock
# May add this back (much) later
.SpaceVim

1
.iterm2/AppSupport Symbolic link
View File

@ -0,0 +1 @@
/Users/joelillibridge/Library/Application Support/iTerm2

241
.iterm2/imgcat Executable file
View File

@ -0,0 +1,241 @@
#!/usr/bin/env bash
set -o pipefail
# tmux requires unrecognized OSC sequences to be wrapped with DCS tmux;
# <sequence> ST, and for all ESCs in <sequence> to be replaced with ESC ESC. It
# only accepts ESC backslash for ST. We use TERM instead of TMUX because TERM
# gets passed through ssh.
function print_osc() {
if [[ $TERM == screen* || $TERM == tmux* ]]; then
printf "\033Ptmux;\033\033]"
else
printf "\033]"
fi
}
# More of the tmux workaround described above.
function print_st() {
if [[ $TERM == screen* || $TERM == tmux* ]]; then
printf "\a\033\\"
else
printf "\a"
fi
}
function load_version() {
if [ -z ${IMGCAT_BASE64_VERSION+x} ]; then
IMGCAT_BASE64_VERSION=$(base64 --version 2>&1)
export IMGCAT_BASE64_VERSION
fi
}
function b64_encode() {
load_version
if [[ $IMGCAT_BASE64_VERSION =~ GNU ]]; then
# Disable line wrap
base64 -w0
else
base64
fi
}
function b64_decode() {
load_version
if [[ $IMGCAT_BASE64_VERSION =~ fourmilab ]]; then
BASE64ARG=-d
elif [[ $IMGCAT_BASE64_VERSION =~ GNU ]]; then
BASE64ARG=-di
else
BASE64ARG=-D
fi
base64 $BASE64ARG
}
# print_image filename inline base64contents print_filename width height preserve_aspect_ratio
# filename: Filename to convey to client
# inline: 0 or 1, if set to 1, the file will be displayed inline, otherwise, it will be downloaded
# base64contents: Base64-encoded contents
# print_filename: 0 or 1, if set to 1, print the filename after outputting the image
# width: set output width of the image in character cells, pixels or percent
# height: set output height of the image in character cells, pixels or percent
# preserve_aspect_ratio: 0 or 1, if set to 1, fill the specified width and height as much as possible without stretching the image
# file: Empty string or file type like "application/json" or ".js".
function print_image() {
print_osc
printf "1337;File=inline=%s" "$2"
printf ";size=%d" $(printf "%s" "$3" | b64_decode | wc -c)
[ -n "$1" ] && printf ";name=%s" "$(printf "%s" "$1" | b64_encode)"
[ -n "$5" ] && printf ";width=%s" "$5"
[ -n "$6" ] && printf ";height=%s" "$6"
[ -n "$7" ] && printf ";preserveAspectRatio=%s" "$7"
[ -n "$8" ] && printf ";type=%s" "$8"
printf ":%s" "$3"
print_st
printf '\n'
[ "$4" == "1" ] && echo "$1"
has_image_displayed=t
}
function error() {
errcho "ERROR: $*"
}
function errcho() {
echo "$@" >&2
}
function show_help() {
errcho
errcho "Usage: imgcat [-p] [-n] [-W width] [-H height] [-r] [-s] [-u] [-t file-type] [-f] filename ..."
errcho " cat filename | imgcat [-W width] [-H height] [-r] [-s]"
errcho
errcho "Display images inline in the iTerm2 using Inline Images Protocol"
errcho
errcho "Options:"
errcho
errcho " -h, --help Display help message"
errcho " -p, --print Enable printing of filename or URL after each image"
errcho " -n, --no-print Disable printing of filename or URL after each image"
errcho " -u, --url Interpret following filename arguments as remote URLs"
errcho " -f, --file Interpret following filename arguments as regular Files"
errcho " -t, --type file-type Provides a type hint"
errcho " -r, --preserve-aspect-ratio When scaling image preserve its original aspect ratio"
errcho " -s, --stretch Stretch image to specified width and height (this option is opposite to -r)"
errcho " -W, --width N Set image width to N character cells, pixels or percent (see below)"
errcho " -H, --height N Set image height to N character cells, pixels or percent (see below)"
errcho
errcho " If you don't specify width or height an appropriate value will be chosen automatically."
errcho " The width and height are given as word 'auto' or number N followed by a unit:"
errcho " N character cells"
errcho " Npx pixels"
errcho " N% percent of the session's width or height"
errcho " auto the image's inherent size will be used to determine an appropriate dimension"
errcho
errcho " If a type is provided, it is used as a hint to disambiguate."
errcho " The file type can be a mime type like text/markdown, a language name like Java, or a file extension like .c"
errcho " The file type can usually be inferred from the extension or its contents. -t is most useful when"
errcho " a filename is not available, such as whe input comes from a pipe."
errcho
errcho "Examples:"
errcho
errcho " $ imgcat -W 250px -H 250px -s avatar.png"
errcho " $ cat graph.png | imgcat -W 100%"
errcho " $ imgcat -p -W 500px -u http://host.tld/path/to/image.jpg -W 80 -f image.png"
errcho " $ cat url_list.txt | xargs imgcat -p -W 40 -u"
errcho " $ imgcat -t application/json config.json"
errcho
}
function check_dependency() {
if ! (builtin command -V "$1" >/dev/null 2>&1); then
error "missing dependency: can't find $1"
exit 1
fi
}
# verify that value is in the image sizing unit format: N / Npx / N% / auto
function validate_size_unit() {
if [[ ! "$1" =~ ^(:?[0-9]+(:?px|%)?|auto)$ ]]; then
error "Invalid image sizing unit - '$1'"
show_help
exit 1
fi
}
## Main
if [ -t 0 ]; then
has_stdin=f
else
has_stdin=t
fi
# Show help if no arguments and no stdin.
if [ $has_stdin = f ] && [ $# -eq 0 ]; then
show_help
exit
fi
check_dependency base64
check_dependency wc
file_type=""
# Look for command line flags.
while [ $# -gt 0 ]; do
case "$1" in
-h | --h | --help)
show_help
exit
;;
-p | --p | --print)
print_filename=1
;;
-n | --n | --no-print)
print_filename=0
;;
-W | --W | --width)
validate_size_unit "$2"
width="$2"
shift
;;
-H | --H | --height)
validate_size_unit "$2"
height="$2"
shift
;;
-r | --r | --preserve-aspect-ratio)
preserve_aspect_ratio=1
;;
-s | --s | --stretch)
preserve_aspect_ratio=0
;;
-f | --f | --file)
has_stdin=f
is_url=f
;;
-u | --u | --url)
check_dependency curl
has_stdin=f
is_url=t
;;
-t | --t | --type)
file_type="$2"
shift
;;
-*)
error "Unknown option flag: $1"
show_help
exit 1
;;
*)
if [ "$is_url" == "t" ]; then
encoded_image=$(curl -fs "$1" | b64_encode) || {
error "Could not retrieve image from URL $1, error_code: $?"
exit 2
}
elif [ -r "$1" ]; then
encoded_image=$(cat "$1" | b64_encode)
else
error "imgcat: $1: No such file or directory"
exit 2
fi
has_stdin=f
print_image "$1" 1 "$encoded_image" "$print_filename" "$width" "$height" "$preserve_aspect_ratio" "$file_type"
;;
esac
shift
done
# Read and print stdin
if [ $has_stdin = t ]; then
print_image "" 1 "$(cat | b64_encode)" 0 "$width" "$height" "$preserve_aspect_ratio" "$file_type"
fi
if [ "$has_image_displayed" != "t" ]; then
error "No image provided. Check command line options."
show_help
exit 1
fi
exit 0

624
.iterm2/imgls Executable file
View File

@ -0,0 +1,624 @@
#!/usr/bin/perl
# imgls: ls(1) listing supplemented with image thumbnails and dimensions
#
# Usage: imgls [--width #] [--height #] [--[no]preserve_ratio]
# [--[no]dimensions] [--[no]unknown] [ls options] [file ...]
#
# Writing an image to an iTerm window is simple. See the official documentation
# at https://iterm2.com/documentation-images.html and the write_image() function below.
#
# Many of ls' options are supported, but not all. The program does not support ls'
# default -C columnar output mode - output is always one entry per line. Writing
# images across the page in columns appears to be problematic.
#
# In addition, options are available to specify setting image properties (width, height,
# preserve aspect ratio), include inline image dimensions, and disable output of
# generic icons for unsupported image types. Finally, a table-based image dimensions
# lookup mechanism is employed to obtain image dimensions. It can call on Perl
# modules such as Image::Size, or call on external programs such as sips, mdls or php.
# It is easy to add additional entries to the table. You can use the --method option
# to select any of the currently supported methods ('sips', 'mdls', 'php', and
# 'image::size'). These are tried, in that order; the first that appears to work
# is used for all.
use v5.14;
use strict;
use utf8;
use warnings;
use File::stat;
use IO::Select;
use IPC::Open3;
use File::Spec;
use MIME::Base64;
use File::Basename;
use Symbol 'gensym';
use Encode qw(decode);
use List::Util qw(max);
use POSIX qw(strftime floor modf);
use Getopt::Long qw(:config no_permute pass_through require_order);
STDERR->autoflush(1);
STDOUT->autoflush(1);
binmode STDOUT, ':encoding(UTF-8)';
binmode STDERR, ':encoding(UTF-8)';
my $prog = basename $0;
sub usage {
my $leader = "usage: $prog";
say STDERR
"usage: $prog",
" [--width #] [--height #] [--[no]preserve_ratio] [--[no]dimensions]",
"\n",
' ' x length($leader),
" [--[no]unknown] [ls options] [file ...]";
exit shift;
}
# Some defaults
my $def_image_width = 3; # height (in character cells)
my $def_image_height = 1; # width (in character cells)
my $def_preserve_ratio = 'true'; # preserve aspect ratio
my %imgparams = ( # default image option parameters
inline => 1, # image appears inline with text
height => $def_image_height, # character cells tall
width => $def_image_width, # character cells wide
preserveAspectRatio => $def_preserve_ratio, # no stretchmarks please
);
my %failed_types; # cache of file extensions that have failed
my %stat_cache; # cache of file/directory lstat() calls
my $curtime = time();
my $sixmonths = (365 / 2) * 86400;
my %opts = (
height => \$imgparams{'height'},
width => \$imgparams{'width'},
);
get_options(\%opts);
# find a method to obtain image dimensions
my $dims_methods = init_dims_methods();
my $dims_method = find_dims_methods($dims_methods);
# single pixel image for non-renderable files
my ($one_pixel_black, $one_pixel_black_len) = get_black_pixel_image();
my $do_newline;
my $dot_filter = $opts{'A'} ? qr/^\.{1,2}$/ : qr/^\./;
$dot_filter = undef if $opts{'a'};
# special: empty @ARGV, or contains only '.'
my $do_header = @ARGV > 1 ? 1 : 0;
if (@ARGV <= 1) {
push @ARGV, '.' if @ARGV == 0;
}
my (@files, @dirs);
for (@ARGV) {
if (! -e _lstat($_)) {
say STDERR "$prog: $_: No such file or directory";
}
elsif (-f _lstat($_)) {
push @files, $_;
}
else {
push @dirs, $_;
}
}
@files = ls_sort(@files);
@dirs = ls_sort(@dirs);
if ($opts{'d'}) {
push @files, @dirs;
@dirs = ();
}
do_ls(undef, @files) if @files;
while (@dirs) {
my $path = shift @dirs;
if (! -e $path) {
say STDERR "$prog: $path: No such file or directory";
next;
}
my (@f, @d);
get_dir_content($path, $dot_filter, \@f, \@d) or
next;
do_ls($path, @f, @d);
if ($opts{'R'}) {
push @dirs, grep { ! /\.\.?$/ } @d;
}
$do_newline++;
}
# Encodes and outputs an image file to the window
# arg 1: path to an image file
# arg 2: size, in bytes, of the image
sub write_image {
my ($file, $size) = @_;
my $encoded;
$imgparams{'name'} = encode_base64($file, ''); # file name is base64 encoded
$imgparams{'size'} = $size; # file size in bytes
if (ref $file eq '') {
my $bytes = get_image_bytes($file);
$encoded = encode_base64($bytes) if defined $bytes;
}
if (! $encoded or ref $file eq 'SCALAR') {
$encoded = $one_pixel_black;
$imgparams{'name'} = encode_base64('one_pixel_black', '');
$imgparams{'size'} = $one_pixel_black_len;
}
printf "%s%s%s;File=%s:%s%s",
"\033", "]", "1337", # image leadin sequence (OSC + 1337)
join(';', map { $_ . '=' . $imgparams{$_} } keys %imgparams), # semicolon separated pairs of param=value pairs
$encoded, # base64 encoded image bytes
"\007"; # end-of-encoding char (BEL = ^G)
}
sub get_options {
local $SIG{__WARN__} = sub { say "$prog: ", $_[0]; usage(1) };
Getopt::Long::Configure(qw/no_ignore_case bundling no_passthrough/);
my $result = GetOptions(\%opts,
'dimensions!' => sub { $opts{'unknown'}++; $opts{$_[0]} = $_[1] },
'height=s',
'method=s', # use to force dimensions method
"preserve_ratio!" => sub { $imgparams{'preserveAspectRatio'} = $_[1] ? 'true' : 'false' },
'unknown!' => sub { $opts{'dimensions'}++; $opts{$_[0]} = $_[1] },
'width=s',
# supported ls options
'D=s',
't' => sub { delete $opts{'S'}; $opts{'t'}++ },
'S' => sub { delete $opts{'t'}; $opts{'S'}++ },
qw/ A F R T a d h i k l n o p r s u y /, 'c|U',
);
$opts{'d'} and delete $opts{'R'};
$opts{'D'} and delete $opts{'T'};
$opts{'n'} and $opts{'l'}++;
$opts{'o'} and $opts{'l'}++;
$opts{'s'} and $opts{'show_blocks'}++;
}
sub get_dir_content {
my ($path, $filter, $filesref, $dirsref) = @_;
my $dh;
unless (opendir($dh, $path)) {
say STDERR "Unable to open directory $path: $!";
return undef;
}
while (readdir($dh)) {
next if defined $filter and $_ =~ /$filter/;
my $p = "$path/$_";
if (-d _lstat($p)) {
push @$dirsref, $p;
}
else {
push @$filesref, $p;
}
}
closedir $dh;
return 1;
}
sub do_ls {
my $path = shift;
my $blocks_total = 0;
my (@hfiles, %widths, $st);
for my $file (ls_sort(@_)) {
#say "FILE: $file";
my %h;
$h{'file'} = $file;
$h{'filename'} = defined $path ? (split /\//, $file)[-1] : $file;
$h{'st'} = $st = _lstat($file);
$h{'ino'} = $st->ino if $opts{'i'};
$h{'bytes'} = $st->size;
$h{'bytesh'} = format_human($h{'bytes'}) if $opts{'h'};
$h{'dims'} = get_dimensions($file) if $opts{'dimensions'} and -f $st && -r $st && $h{'bytes'};
$h{'nlink'} = $st->nlink if $opts{'s'} or $opts{'l'};
if ($opts{'show_blocks'} or $opts{'l'}) {
$h{'blocks'} = $st->blocks;
if ( ! -d $st and ($opts{'a'} or $h{'filename'} !~ /^\.[^.]+/)) {
$blocks_total += $st->blocks;
}
}
if ($opts{'l'}) {
$h{'lsmodes'} = Stat::lsMode::format_mode($st->mode);
$h{'owner'} = ($opts{'n'} ? $st->uid : getpwuid $st->uid) // $st->uid;
$h{'group'} = ($opts{'n'} ? $st->gid : getgrgid $st->gid) // $st->gid if not $opts{'o'};
$h{'time'} = format_time($opts{'c'} ? $st->ctime : $st->mtime);
}
push @hfiles, \%h;
$widths{'dim_w'} = max(defined $h{'dims'} ? length($h{'dims'}{'width'}) : 0, $widths{'dim_w'} // 0);
$widths{'dim_h'} = max(defined $h{'dims'} ? length($h{'dims'}{'height'}) : 0, $widths{'dim_h'} // 0);
for my $key (qw/blocks ino bytes bytesh owner group nlink/) {
$widths{$key} = max(length($h{$key}), $widths{$key} // 0) if exists $h{$key};
}
}
# Header output when @ARGV was > 1, or after second dir
print "\n" if $path and $do_newline;
print "$path:\n" if $path and $do_header++;
# total blocks inline when -d, as header when -l or -s
say "total ", $blocks_total / ($opts{'k'} ? 2 : 1) if $path and ! $opts{'d'} and ($opts{'show_blocks'} or $opts{'l'});
for my $h (@hfiles) {
if (! -f $h->{'st'} or ! $h->{'bytes'} or ($opts{'dimensions'} and ! $h->{'dims'} and ! $opts{'unknown'})) {
# pass a ref to indicate the data is already base64 encoded
write_image \$one_pixel_black, $one_pixel_black_len;
}
else {
write_image $h->{'file'}, $h->{'bytes'};
}
if ($opts{'dimensions'}) {
if ($widths{'dim_w'} or $widths{'dim_h'}) {
my $min_w = $widths{'dim_w'} // 1;
my $min_h = $widths{'dim_h'} // 1;
if ($h->{'dims'}{'width'} or $h->{'dims'}{'height'}) {
printf " [%*d x %*d] ", $min_w, $h->{'dims'}{'width'} // 0, $min_h, $h->{'dims'}{'height'} // 0;
}
else {
printf " %*s %*s ", $min_w, ' ', $min_h, ' ';
}
}
}
printf " %*d", $widths{'ino'}, $h->{'ino'} if $opts{'i'};
printf " %*d", $widths{'blocks'}, $h->{'blocks'} if $opts{'s'};
printf " %s", $h->{'lsmodes'} if exists $h->{'lsmodes'};
printf " %*s", $widths{'nlink'}, $h->{'nlink'} if exists $h->{'nlink'};
printf " %*s", $widths{'owner'}, $h->{'owner'} if exists $h->{'owner'};
printf " %*s", $widths{'group'}, $h->{'group'} if exists $h->{'group'};
if ($opts{'l'}) {
printf " %*d", $widths{'bytes'}, $h->{'bytes'} if ! $opts{'h'};
printf " %4s", $h->{'bytesh'} if $opts{'h'};
}
printf " %s", $h->{'time'} if exists $h->{'time'};
print " ", Encode::decode('UTF-8', defined $path ? (split /\//, $h->{'file'})[-1] : $h->{'file'});
printf "%s", get_F_type($h->{'st'}) if $opts{'F'} or $opts{'p'};
print "\n";
}
}
# Get the image's dimensions to supplement the image and ls output.
sub get_dimensions {
my $file = shift;
my ($ret, $ext);
$file =~ /\.([^.]+)$/ and $ext = $1;
if ($dims_method and (!$ext or ($ext and ! exists $failed_types{$ext}))) {
if (ref $dims_method->{'prog'} eq 'CODE') {
$ret = $dims_method->{'format'}->($file);
}
else {
my ($stdout, $stderr, $exit) = runcmd($dims_method->{'prog'}, @{$dims_method->{'args'}}, $file);
if ($stdout) {
$ret = $dims_method->{'format'}->($stdout);
}
}
}
$failed_types{$ext}++ if ! $ret and $ext;
return $ret;
}
sub runcmd {
my $prog = shift;
my $pid = open3(my $in, my $out, my $err = gensym, $prog, @_);
my ($out_buf, $err_buf) = ('', '');
my $select = new IO::Select;
$select->add($out, $err);
while (my @ready = $select->can_read(5)) {
foreach my $fh (@ready) {
my $data;
my $bytes = sysread($fh, $data, 1024);
if (! defined( $bytes) && ! $!{ECONNRESET}) {
die "error running cmd: $prog: $!";
}
elsif (! defined $bytes or $bytes == 0) {
$select->remove($fh);
next;
}
else {
if ($fh == $out) { $out_buf .= $data; }
elsif ($fh == $err) { $err_buf .= $data; }
else {
die 'unexpected filehandle in runcmd';
}
}
}
}
waitpid($pid, 0);
return ($out_buf, $err_buf, $? >> 8);
}
# List of methods to obtain image dimensions, tried in prioritized order.
# Can be external programs or perl module. Expected to return undef when no
# dimensions can be found, or a hash ref with 'width' and 'height' elements.
sub init_dims_methods {
return [
{
prog => 'sips',
args => [ '-g', 'pixelWidth', '-g', 'pixelHeight' ],
format => sub {
my $out = shift;
return ($out =~ /pixelWidth: (\d+)\s+pixelHeight: (\d+)/s) ? { width => $1, height => $2 } : undef;
}
},
{
prog => 'mdls',
args => [ '-name', 'kMDItemPixelWidth', '-name', 'kMDItemPixelHeight' ],
format => sub {
my $out = shift;
my %dim;
for my $d (qw /Width Height/) {
$dim{$d} = $1 if $out =~ /kMDItemPixel$d\s*=\s*(\d+)$/m;
}
return ($dim{'Width'} and $dim{'Height'}) ? { width => $dim{'Width'}, height => $dim{'Height'} } : undef;
}
},
{
prog => 'php',
args => [ '-r', q/$a = getimagesize("$argv[1]"); if ($a==FALSE) exit(1); else { echo $a[0] . "x" .$a[1]; exit(0); }/ ],
format => sub {
my $out = shift;
return undef unless $out;
my @d = split /x/, $out;
return { width => $d[0], height => $d[1] };
}
},
{
prog => 'exiftool',
args => [ '-s', '-ImageSize' ],
format => sub {
my $out = shift;
return ($out =~ /ImageSize\s+:\s+(\d+)x(\d+)/) ? { width => $1, height => $2 } : undef;
}
},
# Use Image::Size last, due to limitations mentioned elsewhere
{
prog => \&have_Image_Size,
format => \&call_Image_Size,
name => 'Image::Size',
}
]
};
# Look for a dims_methods program to determine image dimensions
sub find_dims_methods {
my $methods = shift;
if ($opts{'method'}) {
@$methods = grep {
(exists $_->{'name'} and (lc($_->{'name'}) eq lc($opts{'method'}))) or
($_->{'prog'} eq $opts{'method'}) } @$methods;
}
for (@$methods) {
if (ref $_->{'prog'} eq 'CODE' and $_->{'prog'}->()) {
return $_;
}
elsif (my $choice = which($_->{'prog'})) {
$_->{'prog'} = $choice;
return $_;
}
}
say STDERR "$prog: no methods found to obtain image dimensions. Tried: ",
map { "\n " . (exists $_->{'name'} ? $_->{'name'} : $_->{'prog'}) } @$methods;
exit 1;
}
# Allow Image::Size to be used if available to calculate an image's size. It
# does not support dimensions of PDF files, so it will be tried last.
sub have_Image_Size {
eval "require Image::Size";
return Image::Size->can('imgsize');
}
sub call_Image_Size {
my $file = shift;
my ($w, $h, $type) = Image::Size::imgsize($file);
if (defined $w and defined $h) {
# Bug: Workaround negative BMP size values, discovered with export to BMP via
# SnagIt and Pixelmator (classic).
if ($type eq 'BMP') {
$w = (2**32) - $w if $w > 2**31;
$h = (2**32) - $h if $h > 2**31;
}
return { width => $w, height => $h };
}
return undef;
}
# grab the specified image file's contents
sub get_image_bytes {
my $file = shift;
$/ = undef;
open (my $fh, "<", $file)
or return undef;
my $filebytes = <$fh>;
chomp $filebytes;
close $fh;
return $filebytes;
}
sub ls_sort {
return if ! (@_ or scalar @_ > 1);
if ($opts{'t'}) {
# descending
@_ = ($opts{'y'} or $ENV{'LS_SAMESORT'}) ?
sort { _lstat($b)->mtime <=> _lstat($a)->mtime || $b cmp $a } @_ :
sort { _lstat($b)->mtime <=> _lstat($a)->mtime || $a cmp $b } @_;
}
# macOS seems to sort lexically with -c/-U, but shows ctime timestamps
elsif ($opts{'c'}) {
@_ = sort { $a cmp $b } @_;
}
elsif ($opts{'u'}) {
@_ = sort { _lstat($a)->atime <=> _lstat($b)->atime } @_;
}
elsif ($opts{'S'}) {
@_ = sort { _lstat($b)->size <=> _lstat($a)->size || $a cmp $b } @_;
}
else {
@_ = sort @_;
}
return $opts{'r'} ? reverse @_ : @_;
}
sub get_F_type {
my $st = shift;
return '/' if -d $st and ($opts{'p'} or $opts{'F'});
return '' unless $opts{'F'};
return '@' if -l $st;
return '|' if -p $st;
return '=' if -S $st;
return '*' if -x $st; # must come after other tests
return '';
}
sub format_time {
my $time = shift;
my $fmt;
if ($opts{'D'}) {
$fmt = $opts{'D'};
}
elsif ($opts{'T'}) {
# mmm dd hh:mm:ss yyyy
$fmt = '%b %e %T %Y';
}
else {
if ($time + $sixmonths > $curtime and $time < $curtime + $sixmonths) {
# mmm dd hh:mm
$fmt = '%b %e %R';
}
else {
# mmm dd yyyy
$fmt = '%b %e %Y';
}
}
return strftime $fmt, localtime($time);
}
sub format_human {
my $bytes = shift;
my @units = ('B', 'K', 'M', 'G', 'T', 'P');
my $scale = floor((length($bytes) - 1) / 3);
my $float = $bytes / (1024 ** $scale);
my ($frac, $int) = modf($float);
if (length($bytes) < 3 or length($int) >= 2) {
sprintf "%d%s", $frac <.5 ? $float : $float + 1, $units[$scale];
}
else {
sprintf "%.1f%s", $float, $units[$scale];
}
}
sub _lstat {
my $file = shift;
return $stat_cache{$file} if exists $stat_cache{$file};
if (my $s = lstat($file)) {
return $stat_cache{$file} = $s;
}
return $file;
}
sub which {
my ($exec) = @_;
$exec or
return undef;
if ($exec =~ m#/# && -f $exec && -x _) {
return $exec
}
foreach my $file ( map { File::Spec->catfile($_, $exec) } File::Spec->path) {
-d $file and
next;
-x _ and
return $file;
}
return undef;
}
# Generate 1 pixel black PNG as placeholding for non-image-able files.
sub get_black_pixel_image {
# base 64 encoded single black pixel png
my $one_pixel_black = 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVQIW2NgYGD4DwABBAEAwS2OUAAAAABJRU5ErkJggg==';
return ($one_pixel_black, length $one_pixel_black);
}
# Based on Stat::lsMode, Copyright 1998 M-J. Dominus, (mjd-perl-lsmode@plover.com)
# You may distribute this module under the same terms as Perl itself.
package Stat::lsMode;
sub format_mode {
my $mode = shift;
return undef unless defined $mode;
my @permchars = qw(--- --x -w- -wx r-- r-x rw- rwx);
my @ftypechars = qw(. p c ? d ? b ? - ? l ? s ? ? ?);
$ftypechars[0] = '';
my $setids = ($mode & 07000) >> 9;
my @permstrs = @permchars[($mode & 0700) >> 6, ($mode & 0070) >> 3, $mode & 0007];
my $ftype = $ftypechars[($mode & 0170000) >> 12];
if ($setids) {
if ($setids & 01) { # sticky
$permstrs[2] =~ s/([-x])$/$1 eq 'x' ? 't' : 'T'/e;
}
if ($setids & 04) { # setuid
$permstrs[0] =~ s/([-x])$/$1 eq 'x' ? 's' : 'S'/e;
}
if ($setids & 02) { # setgid
$permstrs[1] =~ s/([-x])$/$1 eq 'x' ? 's' : 'S'/e;
}
}
join '', $ftype, @permstrs;
}
# vim: expandtab

727
.iterm2/it2api Executable file
View File

@ -0,0 +1,727 @@
#!/usr/bin/env python3
import argparse
import asyncio
try:
import iterm2
except ModuleNotFoundError:
print("The current version of Python doesn't have the 'iterm2' module installed. Please run:")
print("\n $ python3 -m pip install iterm2\n")
exit()
import logging
import re
import sys
import traceback
async def list_sessions(connection, args):
a = await iterm2.async_get_app(connection)
for w in a.terminal_windows:
for t in w.tabs:
sessions = t.sessions
for s in sessions:
print(s.pretty_str(), end='')
print("")
print("Buried sessions:")
for s in a.buried_sessions:
print(s.pretty_str(), end='')
async def show_hierarchy(connection, args):
a = await iterm2.async_get_app(connection)
print(a.pretty_str())
async def send_text(connection, args):
a = await iterm2.async_get_app(connection)
s = a.get_session_by_id(args.session)
await s.async_send_text(args.text)
async def create_tab(connection, args):
a = await iterm2.async_get_app(connection)
if args.window is not None:
window_id = args.window
try:
window = next(window for window in a.terminal_windows if window.window_id == window_id)
tab = await window.async_create_tab(profile=args.profile, command=args.command, index=args.index)
except:
print("bad window id {}".format(window_id))
sys.exit(1)
else:
window = await iterm2.Window.async_create(connection, profile=args.profile, command=args.command)
if not window:
return
tab = window.tabs[0]
session = tab.sessions[0]
print(session.pretty_str())
async def split_pane(connection, args):
a = await iterm2.async_get_app(connection)
s = a.get_session_by_id(args.session)
session = await s.async_split_pane(vertical=args.vertical, before=args.before, profile=args.profile)
print(session.pretty_str())
async def get_buffer(connection, args):
a = await iterm2.async_get_app(connection)
s = a.get_session_by_id(args.session)
contents = await s.async_get_screen_contents()
for i in range(contents.number_of_lines):
line = contents.line(i)
print(line.string)
async def get_prompt(connection, args):
a = await iterm2.async_get_app(connection)
s = a.get_session_by_id(args.session)
result = await iterm2.async_get_last_prompt(connection, s.session_id)
print("working_directory: \"{}\"".format(result.working_directory))
print("command: \"{}\"".format(result.command))
def profile_property_type_map():
map = {
"allow_title_reporting": "bool",
"allow_title_setting": "bool",
"ambiguous_double_width": "bool",
"ansi_0_color": "color",
"ansi_10_color": "color",
"ansi_11_color": "color",
"ansi_12_color": "color",
"ansi_13_color": "color",
"ansi_14_color": "color",
"ansi_15_color": "color",
"ansi_1_color": "color",
"ansi_2_color": "color",
"ansi_3_color": "color",
"ansi_4_color": "color",
"ansi_5_color": "color",
"ansi_6_color": "color",
"ansi_7_color": "color",
"ansi_8_color": "color",
"ansi_9_color": "color",
"answerback_string": "str",
"application_keypad_allowed": "bool",
"ascii_anti_aliased": "bool",
"ascii_ligatures": "bool",
"background_color": "color",
"background_image_is_tiled": "bool",
"badge_color": "color",
"badge_text": "str",
"blend": "float",
"blink_allowed": "bool",
"blinking_cursor": "bool",
"blur": "float",
"blur_radius": "float",
"bm_growl": "bool",
"bold_color": "color",
"character_encoding": "int",
"close_sessions_on_end": "bool",
"cursor_boost": "float",
"cursor_color": "color",
"cursor_guide_color": "color",
"cursor_text_color": "color",
"cursor_type": "int",
"disable_printing": "bool",
"disable_smcup_rmcup": "bool",
"disable_window_resizing": "bool",
"flashing_bell": "bool",
"foreground_color": "color",
"horizontal_spacing": "float",
"idle_code": "int",
"idle_period": "float",
"link_color": "color",
"minimum_contrast": "float",
"mouse_reporting": "bool",
"mouse_reporting_allow_mouse_wheel": "bool",
"name": "str",
"non_ascii_anti_aliased": "bool",
"non_ascii_ligatures": "bool",
"only_the_default_bg_color_uses_transparency": "bool",
"left_option_key_sends": "int",
"place_prompt_at_first_column": "bool",
"prompt_before_closing": "bool",
"reduce_flicker": "bool",
"right_option_key_sends": "int",
"scrollback_in_alternate_screen": "bool",
"scrollback_lines": "int",
"scrollback_with_status_bar": "bool",
"selected_text_color": "color",
"selection_color": "color",
"send_bell_alert": "bool",
"send_code_when_idle": "bool",
"send_idle_alert": "bool",
"send_new_output_alert": "bool",
"send_session_ended_alert": "bool",
"send_terminal_generated_alerts": "bool",
"session_close_undo_timeout": "float",
"show_mark_indicators": "bool",
"silence_bell": "bool",
"smart_cursor_color": "color",
"smart_cursor_color": "color",
"sync_title": "str",
"tab_color": "color",
"thin_strokes": "int",
"transparency": "float",
"underline_color": "color",
"unicode_normalization": "int",
"unicode_version": "int",
"unlimited_scrollback": "bool",
"use_bold_font": "bool",
"use_bright_bold": "bool",
"use_cursor_guide": "bool",
"use_italic_font": "bool",
"use_non_ascii_font": "bool",
"use_tab_color": "bool",
"use_underline_color": "bool",
"vertical_spacing": "float",
"visual_bell": "bool",
"triggers": "dict",
"smart_selection_rules": "list",
"semantic_history": "dict",
"automatic_profile_switching_rules": "list",
"advanced_working_directory_window_setting": "string",
"advanced_working_directory_window_directory": "string",
"advanced_working_directory_tab_setting": "string",
"advanced_working_directory_tab_directory": "string",
"advanced_working_directory_pane_setting": "string",
"advanced_working_directory_pane_directory": "string",
"normal_font": "string",
"non_ascii_font": "string",
"background_image_location": "string",
"key_mappings": "dict",
"touchbar_mappings": "dict" }
return map
def profile_properties():
return list(profile_property_type_map().keys())
def profile_property_type(key):
return profile_property_type_map()[key]
async def get_profile_property(connection, args):
a = await iterm2.async_get_app(connection)
s = a.get_session_by_id(args.session)
profile = await s.async_get_profile()
if args.keys is not None:
keys = args.keys.split(",")
else:
keys = profile_properties()
for prop in keys:
fname = prop
value = getattr(profile, fname)
print("{}: {}".format(prop, value))
def encode_property_value(key, value):
type = profile_property_type(key)
if type == "bool":
assert value == "true" or value == "false"
return value == "true"
elif type == "str":
return value
elif type == "float":
return float(value)
elif type == "int":
return int(value)
elif type == "dict" or type == "list":
class TypeNotSupportedException(Exception): Pass
raise TypeNotSupportedException("this property's type is not supported")
elif type == "color":
# Accepted values look like: "(0,0,0,255 sRGB)"
regex = r"\(([0-9]+), *([0-9]+), *([0-9]+), *([0-9]+) *([A-Za-z]+)\)"
match = re.search(regex, value)
assert match is not None
return iterm2.Color(
float(match.group(1)),
float(match.group(2)),
float(match.group(3)),
float(match.group(4)),
iterm2.ColorSpace(match.group(5)))
async def set_profile_property(connection, args):
a = await iterm2.async_get_app(connection)
s = a.get_session_by_id(args.session)
encoded_value = encode_property_value(args.key, args.value)
profile = await s.async_get_profile()
fname = "async_set_" + args.key
f = getattr(profile, fname)
await f(encoded_value)
async def read(connection, args):
a = await iterm2.async_get_app(connection)
s = a.get_session_by_id(args.session)
if args.mode == "char":
async with iterm2.KeystrokeMonitor(connection) as mon:
keystroke = await mon.async_get()
print(keystroke)
elif args.mode == "line":
async with s.get_keystroke_reader() as reader:
eol = False
line = ""
while not eol:
k = await reader.get()
for e in k:
c = e.characters
if c == "\r" or c == "\n":
eol = True
break
line += c
print(line)
async def get_window_property(connection, args):
a = await iterm2.async_get_app(connection)
w = a.get_window_by_id(args.id)
if w is None:
print("bad window ID")
else:
if args.name == "frame":
frame = await w.async_get_frame()
print("{},{},{},{}".format(frame.origin.x,frame.origin.y,frame.size.width,frame.size.height))
elif args.name == "fullscreen":
print(await w.async_get_fullscreen(connection))
async def set_window_property(connection, args):
a = await iterm2.async_get_app(connection)
w = a.get_window_by_id(args.id)
if w is None:
print("bad window ID")
else:
if args.name == "frame":
parts = args.value.split(",")
frame = iterm2.Frame(iterm2.Point(int(parts[0]), int(parts[1])), iterm2.Size(int(parts[2]), int(parts[3])))
await w.async_set_frame(frame)
elif args.name == "fullscreen":
await w.async_set_fullscreen(args.value == "true")
async def inject(connection, args):
a = await iterm2.async_get_app(connection)
s = a.get_session_by_id(args.session)
if s is None:
print("bad session ID")
else:
await s.async_inject(args.data.encode())
async def activate(connection, args):
a = await iterm2.async_get_app(connection)
if args.mode == "session":
s = a.get_session_by_id(args.id)
if s is None:
print("bad session ID")
else:
await s.async_activate()
elif args.mode == "tab":
t = a.get_tab_by_id(args.id)
if t is None:
print("bad tab ID")
else:
await t.async_select()
elif args.mode == "window":
w = a.get_window_by_id(args.id)
if w is None:
print("bad window ID")
else:
await w.async_activate()
async def activate_app(connection, args):
a = await iterm2.async_get_app(connection)
await a.async_activate(raise_all_windows=args.raise_all_windows, ignoring_other_apps=args.ignoring_other_apps)
async def set_variable(connection, args):
a = await iterm2.async_get_app(connection)
if args.session:
s = a.get_session_by_id(args.session)
if s is None:
print("bad session ID")
return
await s.async_set_variable(args.name, args.value)
elif args.tab:
t = a.get_tab_by_id(args.tab)
if t is None:
print("bad tab ID")
return
await t.async_set_variable(args.name, args.value)
else:
await a.async_set_variable(args.name, args.value)
async def get_variable(connection, args):
a = await iterm2.async_get_app(connection)
if args.session:
s = a.get_session_by_id(args.session)
if s is None:
print("bad session ID")
return
value = await s.async_get_variable(args.name)
print(value)
elif args.tab:
t = a.get_tab_by_id(args.tab)
if t is None:
print("bad tab ID")
return
value = await t.async_get_variable(args.name)
print(value)
else:
value = await a.async_get_variable(args.name)
print(value)
async def list_variables(connection, args):
a = await iterm2.async_get_app(connection)
if args.session:
s = a.get_session_by_id(args.session)
if s is None:
print("bad session ID")
return
value = await s.async_get_variable("*")
for name in value:
print(name)
elif args.tab:
t = a.get_tab_by_id(args.tab)
if t is None:
print("bad tab ID")
return
value = await t.async_get_variable("*")
for name in value:
print(name)
else:
value = await a.async_get_variable("*")
for name in value:
print(name)
async def saved_arrangement(connection, args):
if args.window is not None:
a = await iterm2.async_get_app(connection)
w = a.get_window_by_id(args.window)
if w is None:
print("bad window ID")
return
if args.action == "save":
await w.async_save_window_as_arrangement(args.name)
elif args.action == "restore":
await w.async_restore_window_arrangement(args.name)
else:
if args.action == "save":
await iterm2.Arrangement.async_save(connection, args.name)
elif args.action == "restore":
await iterm2.Arrangement.async_restore(connection, args.name)
async def show_focus(connection, args):
a = await iterm2.async_get_app(connection)
if a.app_active:
print("App is active")
w = a.current_terminal_window
print("Key window: {}".format(w.window_id))
print("")
for w in a.terminal_windows:
t = a.get_tab_by_id(w.selected_tab_id)
print("Selected tab in {}: {}".format(w.window_id, t.tab_id))
s = a.get_session_by_id(t.active_session_id)
print(" Active session is: {}".format(s.pretty_str()))
async def list_profiles(connection, args):
guids = args.guids.split(",") if args.guids is not None else None
properties = args.properties.split(",") if args.properties is not None else None
profiles = await iterm2.PartialProfile.async_query(connection, guids=guids, properties=properties)
for profile in profiles:
keys = list(profile.all_properties.keys())
keys.sort()
for k in keys:
v = profile.all_properties[k]
print("{}: {}".format(k, v))
print("")
async def set_grid_size(connection, args):
a = await iterm2.async_get_app(connection)
s = a.get_session_by_id(args.session)
await s.async_set_grid_size(iterm2.Size(args.width, args.height))
async def list_tmux_connections(connection, args):
connections = await iterm2.async_get_tmux_connections(connection)
for connection in connections:
print("Connection ID: {}\nOwning session: {}".format(connection.connection_id, connection.owning_session))
async def send_tmux_command(connection, args):
connections = await iterm2.async_get_tmux_connections(connection)
ids = []
for connection in connections:
if connection.connection_id == args.connection_id:
print(await connection.async_send_command(args.command))
return;
ids.append(connection.connection_id)
print("No connection with id {} found. Have: {}".format(args.connection_id, ", ".join(ids)))
async def set_tmux_window_visible(connection, args):
connections = await iterm2.async_get_tmux_connections(connection)
ids = []
for connection in connections:
if connection.connection_id == args.connection_id:
await connection.async_set_tmux_window_visible(args.window_id, args.visible)
return;
ids.append(connection.connection_id)
print("No connection with id {} found. Have: {}".format(args.connection_id, ", ".join(ids)))
async def sort_tabs(connection, args):
app = await iterm2.async_get_app(connection)
for w in app.terminal_windows:
tabs = w.tabs
for t in tabs:
t.tab_name = await t.async_get_variable("currentSession.session.name")
def tab_name(t):
return t.tab_name
sorted_tabs = sorted(tabs, key=tab_name)
await w.async_set_tabs(sorted_tabs)
async def list_color_presets(connection, args):
presets = await iterm2.ColorPreset.async_get_list(connection)
for preset in presets:
print(preset)
async def set_color_preset(connection, args):
preset = await iterm2.ColorPreset.async_get(connection, args.preset)
profiles = await iterm2.PartialProfile.async_query(connection, properties=['Guid', 'Name'])
for partial in profiles:
if partial.name == args.profile:
profile = await partial.async_get_full_profile()
await profile.async_set_color_preset(preset)
async def monitor_variable(connection, args):
if args.session:
scope = iterm2.VariableScopes.SESSION
identifier = args.session
elif args.tab:
scope = iterm2.VariableScopes.TAB
identifier = args.tab
elif args.window:
scope = iterm2.VariableScopes.WINDOW
identifier = args.window
elif args.app:
scope = iterm2.VariableScopes.APP
identifier = ''
else:
assert False
async with iterm2.VariableMonitor(connection, scope, args.name, identifier) as monitor:
value = await monitor.async_get()
print(f"New value: {value}")
async def monitor_focus(connection, args):
async with iterm2.FocusMonitor(connection) as monitor:
update = await monitor.async_get_next_update()
print("Update: {}".format(update))
async def set_cursor_color(connection, args):
a = await iterm2.async_get_app(connection)
s = a.get_session_by_id(args.session)
partial = iterm2.LocalWriteOnlyProfile()
r, g, b = list(map(int, args.color.split(",")))
c = iterm2.Color(r, g, b)
partial.set_cursor_color(c)
await s.async_set_profile_properties(partial)
async def monitor_screen(connection, args):
a = await iterm2.async_get_app(connection)
s = a.get_session_by_id(args.session)
async with s.get_screen_streamer() as streamer:
done = False
while not done:
contents = await streamer.async_get()
for i in range(contents.number_of_lines):
line = contents.line(i)
if args.query in line.string:
return
async def show_selection(connection, args):
a = await iterm2.async_get_app(connection)
s = a.get_session_by_id(args.session)
selection = await s.async_get_selection()
for sub in selection.subSelections:
print("Sub selection: {}".format(await sub.async_get_string(connection, s.session_id)))
print("Text: {}".format(await selection.async_get_string(connection, s.session_id, s.grid_size.width)))
def make_parser():
parser = argparse.ArgumentParser(description='iTerm2 CLI')
subparsers = parser.add_subparsers(help='Commands')
list_sessions_parser = subparsers.add_parser("list-sessions", help="List sessions")
list_sessions_parser.set_defaults(func=list_sessions)
show_hierarchy_parser = subparsers.add_parser("show-hierarchy", help="Show all windows, tabs, and sessions")
show_hierarchy_parser.set_defaults(func=show_hierarchy)
send_text_parser = subparsers.add_parser("send-text", help="Send text as though the user had typed it")
send_text_parser.add_argument('session', type=str, help='Session ID')
send_text_parser.add_argument("text", type=str, help='Text to send')
send_text_parser.set_defaults(func=send_text)
create_tab_parser = subparsers.add_parser("create-tab", help="Create a new tab or window")
create_tab_parser.add_argument('--profile', type=str, nargs='?', help='Profile name')
create_tab_parser.add_argument('--window', type=str, nargs='?', help='Window ID')
create_tab_parser.add_argument('--index', type=int, nargs='?', help='Desired tab index')
create_tab_parser.add_argument('--command', type=str, nargs='?', help='Command')
create_tab_parser.set_defaults(func=create_tab)
split_pane_parser = subparsers.add_parser("split-pane", help="Split a pane into two")
split_pane_parser.add_argument('session', type=str, help='Session ID')
split_pane_parser.add_argument('--vertical', action='store_true', help='Split vertically?', default=False)
split_pane_parser.add_argument('--before', action='store_true', help='Spilt left or above target', default=False)
split_pane_parser.add_argument('--profile', type=str, nargs='?', help='Profile name')
split_pane_parser.set_defaults(func=split_pane)
get_buffer_parser = subparsers.add_parser("get-buffer", help="Get screen contents")
get_buffer_parser.add_argument("session", type=str, help="Session ID")
get_buffer_parser.set_defaults(func=get_buffer)
get_prompt_parser = subparsers.add_parser("get-prompt", help="Get info about prompt, if available. Gives either the current prompt or the last prompt if a command is being run. Requires shell integration for prompt detection.")
get_prompt_parser.add_argument("session", type=str, help="Session ID")
get_prompt_parser.set_defaults(func=get_prompt)
get_profile_property_parser = subparsers.add_parser("get-profile-property", help="Get a session's profile settings")
get_profile_property_parser.add_argument("session", type=str, help="Session ID")
get_profile_property_parser.add_argument("keys", type=str, nargs='?', help="Comma separated keys. Omit to get all. Valid keys are: " + ", ".join(profile_properties()))
get_profile_property_parser.set_defaults(func=get_profile_property)
set_profile_parser = subparsers.add_parser("set-profile-property", help="Set a session's profile setting")
set_profile_parser.add_argument("session", type=str, help="Session ID")
set_profile_parser.add_argument("key", type=str, help="Key to set. Valid keys are: " + ", ".join(profile_properties()))
set_profile_parser.add_argument("value", type=str, help="New value.")
set_profile_parser.set_defaults(func=set_profile_property)
read_parser = subparsers.add_parser("read", help="Wait for a input.")
read_parser.add_argument("session", type=str, help="Session ID")
read_parser.add_argument("mode", type=str, help="What to read", choices=[ "char", "line" ])
read_parser.set_defaults(func=read)
get_window_property_parser = subparsers.add_parser("get-window-property", help="Get a property of a window")
get_window_property_parser.add_argument("id", type=str, help="Window ID")
get_window_property_parser.add_argument("name", type=str, help="Property name", choices=["frame", "fullscreen"])
get_window_property_parser.set_defaults(func=get_window_property)
set_window_property_parser = subparsers.add_parser("set-window-property", help="Set a property of a window")
set_window_property_parser.add_argument("id", type=str, help="Window ID")
set_window_property_parser.add_argument("name", type=str, help="Property name", choices=["frame", "fullscreen"])
set_window_property_parser.add_argument("value", type=str, help="New value. For frame: x,y,width,height; for fullscreen: true or false")
set_window_property_parser.set_defaults(func=set_window_property)
inject_parser = subparsers.add_parser("inject", help="Inject a string as though it were program output")
inject_parser.add_argument("session", type=str, help="Session ID")
inject_parser.add_argument("data", type=str, help="Data to inject")
inject_parser.set_defaults(func=inject)
activate_parser = subparsers.add_parser("activate", help="Activate a session, tab, or window.")
activate_parser.add_argument("mode", type=str, help="What kind of object to activate", choices=["session", "tab", "window"])
activate_parser.add_argument("id", type=str, help="ID of object to activate")
activate_parser.set_defaults(func=activate)
activate_app_parser = subparsers.add_parser("activate-app", help="Activate the app")
activate_app_parser.add_argument('--raise_all_windows', action='store_true', help='Raise all windows?', default=False)
activate_app_parser.add_argument('--ignoring_other_apps', action='store_true', help='Activate ignoring other apps (may steal focus)', default=False)
activate_app_parser.set_defaults(func=activate_app)
set_variable_parser = subparsers.add_parser("set-variable", help="Set a user-defined variable in a session. See Badges documentation for details.")
set_variable_parser.add_argument("--session", type=str, nargs='?', help="Session ID")
set_variable_parser.add_argument("--tab", type=str, nargs='?', help="Tab ID")
set_variable_parser.add_argument("name", type=str, help="Variable name. Starts with \"user.\"")
set_variable_parser.add_argument("value", type=str, help="New value")
set_variable_parser.set_defaults(func=set_variable)
get_variable_parser = subparsers.add_parser("get-variable", help="Get a variable in a session. See Badges documentation for details.")
get_variable_parser.add_argument("--session", type=str, nargs='?', help="Session ID")
get_variable_parser.add_argument("--tab", type=str, nargs='?', help="Tab ID")
get_variable_parser.add_argument("name", type=str, help="Variable name. Starts with \"user.\"")
get_variable_parser.set_defaults(func=get_variable)
list_variables_parser = subparsers.add_parser("list-variables", help="Lists variable names available in a session.")
list_variables_parser.add_argument("--session", type=str, nargs='?', help="Session ID")
list_variables_parser.add_argument("--tab", type=str, nargs='?', help="Tab ID")
list_variables_parser.set_defaults(func=list_variables)
saved_arrangement_parser = subparsers.add_parser("saved-arrangement", help="Saves and restores window arrangements")
saved_arrangement_parser.add_argument("action", type=str, help="Action to perform", choices=["save", "restore"])
saved_arrangement_parser.add_argument("name", type=str, help="Arrangement name")
saved_arrangement_parser.add_argument('--window', type=str, nargs='?', help='Window ID to save/restore to')
saved_arrangement_parser.set_defaults(func=saved_arrangement)
show_focus_parser = subparsers.add_parser("show-focus", help="Show active windows, tabs, and panes")
show_focus_parser.set_defaults(func=show_focus)
list_profiles_parser = subparsers.add_parser("list-profiles", help="List profiles")
list_profiles_parser.add_argument("--guids", type=str, nargs='?', help="Comma-delimited list of profiles to list. Omit to get all of them.")
list_profiles_parser.add_argument("--properties", type=str, nargs='?', help="Comma-delimited list of properties to request. Omit to get all of them.")
list_profiles_parser.set_defaults(func=list_profiles)
set_grid_size_parser = subparsers.add_parser("set-grid-size", help="Set size of session")
set_grid_size_parser.add_argument("session", type=str, help="Session ID")
set_grid_size_parser.add_argument("width", type=int, help="Width in columns")
set_grid_size_parser.add_argument("height", type=int, help="Height in rows")
set_grid_size_parser.set_defaults(func=set_grid_size)
list_tmux_connections_parser = subparsers.add_parser("list-tmux-connections", help="List tmux integration connections")
list_tmux_connections_parser.set_defaults(func=list_tmux_connections)
send_tmux_command_parser = subparsers.add_parser("send-tmux-command", help="Send a tmux command to a tmux integration connection")
send_tmux_command_parser.add_argument("connection_id", type=str, help="tmux connection ID")
send_tmux_command_parser.add_argument("command", type=str, help="Command to send")
send_tmux_command_parser.set_defaults(func=send_tmux_command)
set_tmux_window_visible_parser = subparsers.add_parser("set-tmux-window-visible", help="Show or hide a tmux integration window (represented as a tab in iTerm2)")
set_tmux_window_visible_parser.add_argument("connection_id", type=str, help="tmux connection ID")
set_tmux_window_visible_parser.add_argument("window_id", type=str, help="tmux window ID (number)")
set_tmux_window_visible_parser.add_argument('--visible', dest='visible', action='store_true')
set_tmux_window_visible_parser.add_argument('--no-visible', dest='visible', action='store_false')
set_tmux_window_visible_parser.set_defaults(visible=True)
set_tmux_window_visible_parser.set_defaults(func=set_tmux_window_visible)
sort_tabs_parser = subparsers.add_parser("sort-tabs", help="Sort tabs alphabetically by name")
sort_tabs_parser.set_defaults(func=sort_tabs)
list_color_presets_parser = subparsers.add_parser("list-color-presets", help="Lists names of color presets")
list_color_presets_parser.set_defaults(func=list_color_presets)
set_color_preset_parser = subparsers.add_parser("set-color-preset", help="Lists names of color presets")
set_color_preset_parser.add_argument("profile", type=str, help="Profile name")
set_color_preset_parser.add_argument("preset", type=str, help="Color preset name")
set_color_preset_parser.set_defaults(func=set_color_preset)
monitor_variable_parser = subparsers.add_parser("monitor-variable", help="Monitor changes to a variable")
monitor_variable_parser.add_argument("name", type=str, help="variable name")
monitor_variable_parser.add_argument('--session', type=str, nargs='?', help='Session ID for the variable scope')
monitor_variable_parser.add_argument('--tab', type=str, nargs='?', help='Tab ID for the variable scope')
monitor_variable_parser.add_argument('--window', type=str, nargs='?', help='Window ID for the variable scope')
monitor_variable_parser.add_argument('--app', action='store_true', help='App scope', default=False)
monitor_variable_parser.set_defaults(func=monitor_variable)
monitor_focus_parser = subparsers.add_parser("monitor-focus", help="Monitor changes to focus")
monitor_focus_parser.set_defaults(func=monitor_focus)
set_cursor_color_parser = subparsers.add_parser("set-cursor-color", help="Set cursor color")
set_cursor_color_parser.add_argument("session", type=str, help="Session ID")
set_cursor_color_parser.add_argument("color", type=str, help="Color as red,green,blue where each value is in 0-255")
set_cursor_color_parser.set_defaults(func=set_cursor_color)
monitor_screen_parser = subparsers.add_parser("monitor-screen", help="Monitor screen contents")
monitor_screen_parser.add_argument("session", type=str, help="Session ID")
monitor_screen_parser.add_argument("query", type=str, help="Stop when this text is seen")
monitor_screen_parser.set_defaults(func=monitor_screen)
show_selection_parser = subparsers.add_parser("show-selection", help="Shows the selected text in a session")
show_selection_parser.add_argument("session", type=str, help="Session ID")
show_selection_parser.set_defaults(func=show_selection)
return parser
def main(argv):
logging.basicConfig()
parser = make_parser()
args = parser.parse_args(argv[1:])
if "func" not in args:
print(parser.format_help())
raise argparse.ArgumentTypeError('Missing command')
async def wrapper(connection):
try:
await args.func(connection, args)
except Exception as e:
print(traceback.format_exc())
iterm2.run_until_complete(wrapper)
if __name__ == "__main__":
try:
main(sys.argv)
except Exception as e:
print(traceback.format_exc())
sys.exit(1)

82
.iterm2/it2attention Executable file
View File

@ -0,0 +1,82 @@
#!/usr/bin/env bash
# tmux requires unrecognized OSC sequences to be wrapped with DCS tmux;
# <sequence> ST, and for all ESCs in <sequence> to be replaced with ESC ESC. It
# only accepts ESC backslash for ST.
function print_osc() {
if [[ $TERM == screen* || $TERM == tmux* ]] ; then
printf "\033Ptmux;\033\033]"
else
printf "\033]"
fi
}
# More of the tmux workaround described above.
function print_st() {
if [[ $TERM == screen* || $TERM == tmux* ]] ; then
printf "\a\033\\"
else
printf "\a"
fi
}
function show_help() {
echo "Usage:" 1>& 2
echo " $(basename $0) start" 1>& 2
echo " Begin bouncing the dock icon if another app is active" 1>& 2
echo " $(basename $0) stop" 1>& 2
echo " Stop bouncing the dock icon if another app is active" 1>& 2
echo " $(basename $0) once" 1>& 2
echo " Bounce the dock icon once if another app is active" 1>& 2
echo " $(basename $0) fireworks" 1>& 2
echo " Show an explosion animation at the cursor" 1>& 2
}
function start_bounce() {
print_osc
printf "1337;RequestAttention=1"
print_st
}
function stop_bounce() {
print_osc
printf "1337;RequestAttention=0"
print_st
}
function bounce_once() {
print_osc
printf "1337;RequestAttention=once"
print_st
}
function fireworks() {
print_osc
printf "1337;RequestAttention=fireworks"
print_st
}
## Main
if [[ $# == 0 ]]
then
show_help
exit 1
fi
if [[ $1 == start ]]
then
start_bounce
elif [[ $1 == stop ]]
then
stop_bounce
elif [[ $1 == once ]]
then
bounce_once
elif [[ $1 == fireworks ]]
then
fireworks
else
show_help
exit 1
fi

195
.iterm2/it2cat Executable file
View File

@ -0,0 +1,195 @@
#!/usr/bin/env bash
set -o pipefail
# tmux requires unrecognized OSC sequences to be wrapped with DCS tmux;
# <sequence> ST, and for all ESCs in <sequence> to be replaced with ESC ESC. It
# only accepts ESC backslash for ST. We use TERM instead of TMUX because TERM
# gets passed through ssh.
function print_osc() {
if [[ $TERM == screen* || $TERM == tmux* ]]; then
printf "\033Ptmux;\033\033]"
else
printf "\033]"
fi
}
# More of the tmux workaround described above.
function print_st() {
if [[ $TERM == screen* || $TERM == tmux* ]]; then
printf "\a\033\\"
else
printf "\a"
fi
}
function load_version() {
if [ -z ${IT2CAT_BASE64_VERSION+x} ]; then
IT2CAT_BASE64_VERSION=$(base64 --version 2>&1)
export IT2CAT_BASE64_VERSION
fi
}
function b64_encode() {
load_version
if [[ $IT2CAT_BASE64_VERSION =~ GNU ]]; then
# Disable line wrap
base64 -w0
else
base64
fi
}
function b64_decode() {
load_version
if [[ $IT2CAT_BASE64_VERSION =~ fourmilab ]]; then
BASE64ARG=-d
elif [[ $IT2CAT_BASE64_VERSION =~ GNU ]]; then
BASE64ARG=-di
else
BASE64ARG=-D
fi
base64 $BASE64ARG
}
# print_file filename base64contents type mode
# filename: Filename to convey to client
# base64contents: Base64-encoded contents
# type: type hint
# mode: wide or regular
function print_file() {
print_osc
printf "1337;File=inline=1"
printf ";size=%d" $(printf "%s" "$2" | b64_decode | wc -c)
[ -n "$1" ] && printf ";name=%s" "$(printf "%s" "$1" | b64_encode)"
[ -n "$3" ] && printf ";type=%s" "$3"
[ -n "$4" ] && printf ";mode=%s" "$4"
printf ":%s" "$2"
print_st
printf '\n'
did_print=t
}
function error() {
errcho "ERROR: $*"
}
function errcho() {
echo "$@" >&2
}
function show_help() {
errcho
errcho "Usage: it2cat [-w] [-t file-type] [-u] [-f] filename ..."
errcho " cat filename | it2cat [-w] [-t file-type]"
errcho
errcho "Display a text file with native rendering."
errcho
errcho "Options:"
errcho
errcho " -h, --help Display help message"
errcho " -u, --url Interpret following filename arguments as remote URLs"
errcho " -f, --file Interpret following filename arguments as regular Files"
errcho " -t, --type file-type Provides a type hint"
errcho " -w, --wide Render in wide mode with a horizontal scrollbar"
errcho
errcho " If a type is provided, it is used as a hint to disambiguate."
errcho " The file type can be a mime type like text/markdown, a language name like Java, or a file extension like .c"
errcho " The file type can usually be inferred from the extension or its contents. -t is most useful when"
errcho " a filename is not available, such as whe input comes from a pipe."
errcho
errcho "Examples:"
errcho
errcho " $ it2cat file.txt"
errcho " $ cat graph.png | it2cat"
errcho " $ it2cat -u http://example.com/path/to/file.txt -f otherfile.txt"
errcho " $ cat url_list.txt | xargs it2cat -u"
errcho " $ it2cat -w -t application/json config.json"
errcho
}
function check_dependency() {
if ! (builtin command -V "$1" >/dev/null 2>&1); then
error "missing dependency: can't find $1"
exit 1
fi
}
## Main
if [ -t 0 ]; then
has_stdin=f
else
has_stdin=t
fi
# Show help if no arguments and no stdin.
if [ $has_stdin = f ] && [ $# -eq 0 ]; then
show_help
exit
fi
check_dependency base64
check_dependency wc
file_type=""
mode=regular
# Look for command line flags.
while [ $# -gt 0 ]; do
case "$1" in
-h | --h | --help)
show_help
exit
;;
-w | --w | --wide)
mode=wide
;;
-f | --f | --file)
has_stdin=f
is_url=f
;;
-u | --u | --url)
check_dependency curl
has_stdin=f
is_url=t
;;
-t | --t | --type)
file_type="$2"
shift
;;
-*)
error "Unknown option flag: $1"
show_help
exit 1
;;
*)
if [ "$is_url" == "t" ]; then
encoded_file=$(curl -fs "$1" | b64_encode) || {
error "Could not retrieve file from URL $1, error_code: $?"
exit 2
}
elif [ -r "$1" ]; then
encoded_file=$(cat "$1" | b64_encode)
else
error "it2cat: $1: No such file or directory"
exit 2
fi
has_stdin=f
print_file "$1" "$encoded_file" "$file_type" "$mode"
;;
esac
shift
done
# Read and print stdin
if [ $has_stdin = t ]; then
print_file "" "$(cat | b64_encode)" "$file_type" "$mode"
fi
if [ "$did_print" != "t" ]; then
error "No file provided. Check command line options."
show_help
exit 1
fi
exit 0

90
.iterm2/it2check Executable file
View File

@ -0,0 +1,90 @@
#!/usr/bin/env bash
# Make sure stdin and stdout are a tty.
if [ ! -t 0 ] ; then
exit 1
fi
if [ ! -t 1 ] ; then
exit 1
fi
# Read some bytes from stdin. Pass the number of bytes to read as the first argument.
function read_bytes()
{
numbytes=$1
dd bs=1 count=$numbytes 2>/dev/null
}
function read_dsr() {
# Reading response to DSR.
dsr=""
spam=$(read_bytes 2)
byte=$(read_bytes 1)
while [ "${byte}" != "n" ]; do
dsr=${dsr}${byte}
byte=$(read_bytes 1)
done
echo ${dsr}
}
# Extract the terminal name from DSR 1337
function terminal {
echo -n "$1" | sed -e 's/ .*//'
}
# Extract the version number from DSR 1337
function version {
echo -n "$1" | sed -e 's/.* //'
}
trap clean_up EXIT
_STTY=$(stty -g) ## Save current terminal setup
function clean_up() {
stty "$_STTY" ## Restore terminal settings
}
# Prepare to silently read any (>=0) characters with no timeout.
stty -echo -icanon raw min 0 time 0
# Consume all pending input.
while read none; do :; done
# Reset the TTY, so it behaves as expected for the rest of the it2check script.
clean_up
# Enter raw mode and turn off echo so the terminal and I can chat quietly.
stty -echo -icanon raw
# Support for the extension first appears in this version of iTerm2:
MIN_VERSION=2.9.20160304
if [ $# -eq 1 ]; then
MIN_VERSION=$1
fi
# Send iTerm2-proprietary code. Other terminals ought to ignore it (but are
# free to use it respectfully). The response won't start with a 0 so we can
# distinguish it from the response to DSR 5. It should contain the terminal's
# name followed by a space followed by its version number and be terminated
# with an n.
echo -n ''
# Report device status. Responds with esc [ 0 n. All terminals support this. We
# do this because if the terminal will not respond to iTerm2's custom escape
# sequence, we can still read from stdin without blocking indefinitely.
echo -n ''
version_string=$(read_dsr)
if [ -n "${version_string}" -a "${version_string}" != "0" -a "${version_string}" != "3" ]; then
# Already read DSR 1337. Read DSR 5 and throw it away.
dsr=$(read_dsr)
else
# Terminal didn't respond to the DSR 1337. The response we read is from DSR 5.
version_string=""
fi
# Extract the terminal name and version number from the response.
version=$(version "${version_string}")
term=$(terminal "${version_string}")
# Check if they match what we're looking for. This becomes the return code of the script.
test "$term" = ITERM2 -a \( "$version" \> "$MIN_VERSION" -o "$version" = "$MIN_VERSION" \)

106
.iterm2/it2copy Executable file
View File

@ -0,0 +1,106 @@
#!/usr/bin/env bash
trap clean_up EXIT
trap clean_up INT
inosc=0
function clean_up() {
if [[ $inosc == 1 ]]
then
print_st
fi
}
function show_help() {
echo "Usage: $(basename $0)" 1>& 2
echo " Copies to clipboard from standard input" 1>& 2
echo " $(basename $0) filename" 1>& 2
echo " Copies to clipboard from file" 1>& 2
}
# tmux requires unrecognized OSC sequences to be wrapped with DCS tmux;
# <sequence> ST, and for all ESCs in <sequence> to be replaced with ESC ESC. It
# only accepts ESC backslash for ST.
function print_osc() {
if [[ $TERM == screen* || $TERM == tmux* ]] ; then
printf "\033Ptmux;\033\033]"
else
printf "\033]"
fi
}
# More of the tmux workaround described above.
function print_st() {
if [[ $TERM == screen* || $TERM == tmux* ]] ; then
printf "\a\033\\"
else
printf "\a"
fi
}
send_tmux() {
uid=$RANDOM$RANDOM
print_osc
inosc=1
printf '1337;Copy=2;%s' "$uid"
print_st
inosc=0
fold | while read line
do
print_osc
inosc=1
printf '1337;Copy=3;%s:%s' "$uid" "$line"
print_st
inosc=0
done
print_osc
inosc=1
printf '1337;Copy=4;%s' "$uid"
print_st
inosc=0
}
send_regular() {
print_osc
inosc=1
printf '1337;Copy=:%s' "$data"
print_st
inosc=0
}
send() {
if [[ $TERM == tmux* ]]; then
send_tmux
else
send_regular
fi
}
# Look for command line flags.
while [ $# -gt 0 ]; do
case "$1" in
-h|--h|--help)
show_help
exit
;;
-*)
error "Unknown option flag: $1"
show_help
exit 1
;;
*)
if [ -r "$1" ] ; then
base64 < $1 | send
exit 0
else
error "it2copy: $1: No such file or directory"
exit 2
fi
;;
esac
shift
done
base64 | send

74
.iterm2/it2dl Executable file
View File

@ -0,0 +1,74 @@
#!/usr/bin/env bash
if [ $# -lt 1 ]; then
echo "Usage: $(basename $0) file ..."
exit 1
fi
# tmux requires unrecognized OSC sequences to be wrapped with DCS tmux;
# <sequence> ST, and for all ESCs in <sequence> to be replaced with ESC ESC. It
# only accepts ESC backslash for ST. We use TERM instead of TMUX because TERM
# gets passed through ssh.
function print_osc() {
if [[ $TERM == screen* || $TERM == tmux* ]]; then
printf "\033Ptmux;\033\033]"
else
printf "\033]"
fi
}
# More of the tmux workaround described above.
function print_st() {
if [[ $TERM == screen* || $TERM == tmux* ]]; then
printf "\a\033\\"
else
printf "\a"
fi
}
function load_version() {
if [ -z ${IT2DL_BASE64_VERSION+x} ]; then
export IT2DL_BASE64_VERSION=$(base64 --version 2>&1)
fi
}
function b64_encode() {
load_version
if [[ "$IT2DL_BASE64_VERSION" =~ GNU ]]; then
# Disable line wrap
base64 -w0
else
base64
fi
}
for fn in "$@"
do
if [ -r "$fn" ] ; then
[ -d "$fn" ] && { echo "$fn is a directory"; continue; }
if [[ $TERM == screen* || $TERM == tmux* ]]; then
print_osc
printf '1337;MultipartFile=name=%s;' $(echo -n "$fn" | b64_encode)
wc -c "$fn" | awk '{printf "size=%d",$1}'
print_st
parts=$(b64_encode < "$fn" | fold -w 256)
for part in $parts; do
print_osc
printf '1337;FilePart=%s' "$part"
print_st
done
print_osc
printf '1337;FileEnd'
print_st
else
printf '\033]1337;File=name=%s;' $(echo -n "$fn" | b64_encode)
wc -c "$fn" | awk '{printf "size=%d",$1}'
printf ":"
base64 < "$fn"
printf '\a'
fi
else
echo File $fn does not exist or is not readable.
fi
done

133
.iterm2/it2getvar Executable file
View File

@ -0,0 +1,133 @@
#!/usr/bin/env bash
set -o pipefail
# tmux requires unrecognized OSC sequences to be wrapped with DCS tmux;
# <sequence> ST, and for all ESCs in <sequence> to be replaced with ESC ESC. It
# only accepts ESC backslash for ST.
function print_osc() {
if [[ $TERM == screen* || $TERM == tmux* ]] ; then
printf "\033Ptmux;\033\033]"
else
printf "\033]"
fi
}
# More of the tmux workaround described above.
function print_st() {
if [[ $TERM == screen* || $TERM == tmux* ]] ; then
printf "\a\033\\"
else
printf "\a"
fi
}
function get_b64_version() {
if [[ -z "${BASE64_VERSION+x}" ]]; then
BASE64_VERSION=$(base64 --version 2>&1)
export BASE64_VERSION
fi
}
function b64_encode() {
get_b64_version
if [[ $BASE64_VERSION =~ GNU ]]; then
# Disable line wrap
base64 -w0
else
base64
fi
}
function b64_decode() {
get_b64_version
if [[ $BASE64_VERSION =~ fourmilab ]]; then
BASE64_ARG=-d
elif [[ $BASE64_VERSION =~ GNU ]]; then
BASE64_ARG=-di
else
BASE64_ARG=-D
fi
base64 $BASE64_ARG
}
function error() {
errcho "ERROR: $*"
}
function errcho() {
echo "$@" >&2
}
function show_help() {
errcho
errcho "Usage: it2getvar variable_name"
errcho
errcho "Output value of the iTerm2 variable"
errcho
errcho "See the Variables Reference for information about built-in iTerm2 variables:"
errcho " -> https://iterm2.com/documentation-variables.html"
errcho
}
function check_dependency() {
if ! (builtin command -V "$1" >/dev/null 2>&1); then
error "missing dependency: can't find $1"
exit 1
fi
}
# get_variable variable_name
#
# This function uses POSIX standard synonym for the controlling terminal
# associated with the current process group - /dev/tty. It is useful for programs
# that wish to be sure of writing or reading data from the terminal
# no matter how STDIN/STDOUT/STDERR has been redirected.
function get_variable() {
trap 'cleanup' EXIT
stty -echo < /dev/tty
exec 9<> /dev/tty
print_osc >&9
printf "1337;ReportVariable=%s" "$(echo -n "$1" | b64_encode)" >&9
print_st >&9
read -r -t 5 -d $'\a' iterm_response <&9
exec 9>&-
stty echo < /dev/tty
[[ "$iterm_response" =~ ReportVariable= ]] || {
error "Failed to read response from iTerm2"
exit 2
}
echo "$(b64_decode <<< ${iterm_response#*=})"
}
function cleanup() {
stty echo < /dev/tty
}
# Show help if no arguments
if [ $# -eq 0 ]; then
show_help
exit
fi
check_dependency stty
check_dependency base64
# Process command line arguments
case "$1" in
-h|--h|--help)
show_help
exit
;;
-*)
error "Unknown option: $1"
show_help
exit 1
;;
*)
[[ -z "$1" ]] && error "Variable name can't be empty" && exit 1
get_variable "$1"
;;
esac
exit 0

117
.iterm2/it2git Executable file
View File

@ -0,0 +1,117 @@
#!/usr/bin/env bash
# This script sets iTerm2 user-defined variables describing the state of the git
# repo in the current directory.
#
# For more information on the status bar, see:
# https://www.iterm2.com/3.3/documentation-status-bar.html
#
# Installation instructions for this script:
#
# bash: Place this in .bashrc.
# --------------------------------------------------------------------------------------
# function iterm2_print_user_vars() {
# it2git
# }
# fish: Place this in ~/.config/fish/config.fish after the line
# "source ~/.iterm2_shell_integration.fish".
# --------------------------------------------------------------------------------------
# function iterm2_print_user_vars
# it2git
# end
# tcsh: Place this in .tcshrc
# --------------------------------------------------------------------------------------
# alias get_current_branch "bash -c '((git branch 2> /dev/null) | grep \* | cut -c3-)'"
# alias _iterm2_user_defined_vars 'it2git'
# zsh:Place this in .zshrc after "source /Users/georgen/.iterm2_shell_integration.zsh".
# --------------------------------------------------------------------------------------
# iterm2_print_user_vars() {
# it2git
# }
GIT_BINARY=/usr/bin/git
dirty() {
# Outputs "dirty" or "clean"
OUTPUT=$("$GIT_BINARY" status --porcelain --ignore-submodules -unormal 2>/dev/null)
if (($?)); then
echo "clean"
return
fi
if [ -z "$OUTPUT" ]; then
echo "clean"
else
echo "dirty"
fi
}
counts() {
OUTPUT=$("$GIT_BINARY" rev-list --left-right --count HEAD...@'{u}' 2>/dev/null)
if (($?)); then
echo "error"
return
fi
echo "$OUTPUT"
}
branch() {
OUTPUT=$("$GIT_BINARY" symbolic-ref -q --short HEAD 2>/dev/null || git rev-parse --short HEAD 2>/dev/null)
if (($?)); then
return
fi
echo "$OUTPUT"
}
adds() {
"${GIT_BINARY}" ls-files --others --exclude-standard | wc -l
}
deletes() {
"${GIT_BINARY}" ls-files --deleted --exclude-standard | wc -l
}
function iterm2_begin_osc {
printf "\033]"
}
function iterm2_end_osc {
printf "\007"
}
function iterm2_set_user_var() {
iterm2_begin_osc
printf "1337;SetUserVar=%s=%s" "$1" $(printf "%s" "$2" | base64 | tr -d '\n')
iterm2_end_osc
}
git_poll () {
DIRECTORY="$1"
cd "$DIRECTORY"
DIRTY=$(dirty)
COUNTS=$(counts)
PUSH_COUNT=$(cut -f1 <<< "$COUNTS")
PULL_COUNT=$(cut -f2 <<< "$COUNTS")
BRANCH=$(branch)
iterm2_set_user_var gitBranch "$BRANCH"
iterm2_set_user_var gitDirty "$DIRTY"
iterm2_set_user_var gitPushCount "$PUSH_COUNT"
iterm2_set_user_var gitPullCount "$PULL_COUNT"
iterm2_set_user_var gitAdds "$ADDS"
iterm2_set_user_var gitDeletes "$DELETES"
}
"$GIT_BINARY" rev-parse --git-dir 2>/dev/null >/dev/null
if (($?)); then
iterm2_set_user_var gitBranch ""
iterm2_set_user_var gitDirty ""
iterm2_set_user_var gitPushCount ""
iterm2_set_user_var gitPullCount ""
iterm2_set_user_var gitAdds ""
iterm2_set_user_var gitDeletes ""
else
git_poll "$PWD"
fi

170
.iterm2/it2profile Executable file
View File

@ -0,0 +1,170 @@
#!/usr/bin/env bash
set -o pipefail
# tmux requires unrecognized OSC sequences to be wrapped with DCS tmux;
# <sequence> ST, and for all ESCs in <sequence> to be replaced with ESC ESC. It
# only accepts ESC backslash for ST.
function print_osc() {
if [[ $TERM == screen* || $TERM == tmux* ]] ; then
printf "\033Ptmux;\033\033]"
else
printf "\033]"
fi
}
# More of the tmux workaround described above.
function print_st() {
if [[ $TERM == screen* || $TERM == tmux* ]] ; then
printf "\a\033\\"
else
printf "\a"
fi
}
function get_b64_version() {
if [[ -z "${BASE64_VERSION+x}" ]]; then
BASE64_VERSION=$(base64 --version 2>&1)
export BASE64_VERSION
fi
}
function b64_encode() {
get_b64_version
if [[ $BASE64_VERSION =~ GNU ]]; then
# Disable line wrap
base64 -w0
else
base64
fi
}
function b64_decode() {
get_b64_version
if [[ $BASE64_VERSION =~ fourmilab ]]; then
BASE64_ARG=-d
elif [[ $BASE64_VERSION =~ GNU ]]; then
BASE64_ARG=-di
else
BASE64_ARG=-D
fi
base64 $BASE64_ARG
}
function error() {
errcho "ERROR: $*"
}
function errcho() {
echo "$@" >&2
}
function show_help() {
errcho
errcho "Usage: it2profile -s profile_name"
errcho " it2profile -g"
errcho
errcho "Change iTerm2 session profile on the fly"
errcho
errcho "Options:"
errcho
errcho " -s Set current iTerm2 session profile to specified profile name"
errcho " empty string refers to profile marked as Default"
errcho " -g Get current iTerm2 session profile name"
errcho " -r Reset to the session initial profile"
errcho
}
function check_dependency() {
if ! (builtin command -V "$1" >/dev/null 2>&1); then
error "missing dependency: can't find $1"
exit 1
fi
}
# get_profile / set_profile
#
# These functions uses POSIX standard synonym for the controlling terminal
# associated with the current process group - /dev/tty. It is useful for programs
# that wish to be sure of writing or reading data from the terminal
# no matter how STDIN/STDOUT/STDERR has been redirected.
#
# get_profile uses iTerm2 Session Context variable "profileName" to
# get currently active profile name.
#
function get_profile() {
trap 'cleanup' EXIT
stty -echo < /dev/tty
exec 9<> /dev/tty
print_osc >&9
printf "1337;ReportVariable=cHJvZmlsZU5hbWU=" >&9
print_st >&9
read -r -t 5 -d $'\a' iterm_response <&9
exec 9>&-
stty echo < /dev/tty
[[ "$iterm_response" =~ ReportVariable= ]] || {
error "Failed to read response from iTerm2"
exit 2
}
echo "$(b64_decode <<< ${iterm_response#*=})"
}
function cleanup() {
stty echo < /dev/tty
}
function set_profile() {
exec 9> /dev/tty
print_osc >&9
printf '1337;SetProfile=%s' "$1" >&9
print_st >&9
exec 9>&-
}
# Show help if no arguments
if [ $# -eq 0 ]; then
show_help
exit
fi
check_dependency stty
check_dependency base64
# Process command line arguments
case "$1" in
-h|--h|--help)
show_help
exit
;;
-s|--s|--set)
[[ $# -eq 2 ]] || {
error "-s option requires exactly 1 argument - profile name"
show_help
exit 1
}
set_profile "$2"
;;
-g|--g|--get)
[[ $# -eq 1 ]] || {
error "-g option does not accept any argument"
show_help
exit 1
}
get_profile
;;
-r|--r|--reset)
[[ $# -eq 1 ]] || {
error "-r option does not accept any argument"
show_help
exit 1
}
set_profile "${ITERM_PROFILE:-}"
;;
*)
error "Unknown option: $1"
show_help
exit 1
;;
esac
exit 0

116
.iterm2/it2setcolor Executable file
View File

@ -0,0 +1,116 @@
#!/usr/bin/env bash
open=0
# tmux requires unrecognized OSC sequences to be wrapped with DCS tmux;
# <sequence> ST, and for all ESCs in <sequence> to be replaced with ESC ESC. It
# only accepts ESC backslash for ST.
function print_osc() {
if [[ $TERM == screen* || $TERM == tmux* ]] ; then
printf "\033Ptmux;\033\033]"
else
printf "\033]"
fi
}
# More of the tmux workaround described above.
function print_st() {
if [[ $TERM == screen* || $TERM == tmux* ]] ; then
printf "\a\033\\"
else
printf "\a"
fi
}
# set_color key rgb
function set_color() {
print_osc
printf '1337;SetColors=%s=%s' "$1" "$2"
print_st
}
function error() {
echo "ERROR: $*" 1>&2
}
function show_help() {
if [ $open = 1 ]; then
print_st
fi
echo "Usage"
echo ""
echo "1) To set a specific color to an RGB value:"
echo " it2setcolor name color [name color...]" 1>& 2
echo "For example:"
echo " it2setcolor fg fff"
echo ""
echo "name is one of:"
echo " fg bg bold link selbg selfg curbg curfg underline tab"
echo " black red green yellow blue magenta cyan white"
echo " br_black br_red br_green br_yellow br_blue br_magenta br_cyan br_white"
echo ""
echo "color is of the format:"
echo " RGB (three hex digits, like fff)"
echo " RRGGBB (six hex digits, like f0f0f0)"
echo " cs:RGB (cs is a color space name)"
echo " cs:RRGGBB (cs is a color space name)"
echo ""
echo " The color space names accepted in the color are:"
echo " srgb (sRGB, the default if none is specified)"
echo " rgb (Apple's old device-independent colorspace)"
echo " p3 (Apple's fancy large-gamut colorspace)"
echo ""
echo "2) To switch to a named color preset:"
echo " it2setcolor preset name"
echo "For example:"
echo " it2setcolor preset 'Light Background'"
echo ""
echo "3) To reset the current tab's color to the system default:"
echo " it2setcolor tab default"
}
# Show help if no arguments and no stdin.
if [ $# -eq 0 ]; then
show_help
exit
fi
# Look for command line flags.
while [ $# -gt 0 ]; do
case "$1" in
-h|--h|--help)
show_help
exit
;;
-*)
error "Unknown option flag: $1"
show_help
exit 1
;;
*)
if [ $# -lt 2 ]; then
show_help
exit
fi
if [ $open = 0 ]; then
open=1
print_osc
printf '1337;SetColors='
else
printf ","
fi
# name is not checked for validity because we'd like this to work with future colors, too.
printf "%s=%s" "$1" "$2"
shift
;;
esac
shift
done
if [ $open = 1 ]; then
print_st
else
show_help
fi
exit 0

123
.iterm2/it2setkeylabel Executable file
View File

@ -0,0 +1,123 @@
#!/usr/bin/env bash
# tmux requires unrecognized OSC sequences to be wrapped with DCS tmux;
# <sequence> ST, and for all ESCs in <sequence> to be replaced with ESC ESC. It
# only accepts ESC backslash for ST.
function print_osc() {
if [[ $TERM == screen* || $TERM == tmux* ]] ; then
printf "\033Ptmux;\033\033]"
else
printf "\033]"
fi
}
# More of the tmux workaround described above.
function print_st() {
if [[ $TERM == screen* || $TERM == tmux* ]] ; then
printf "\a\033\\"
else
printf "\a"
fi
}
function show_help() {
echo "Usage:" 1>& 2
echo " $(basename $0) set Fn Label" 1>& 2
echo " Where n is a value from 1 to 20" 1>& 2
echo " $(basename $0) set status Label" 1>& 2
echo " Sets the touch bar status button's label" 1>& 2
echo " $(basename $0) push [name]" 1>& 2
echo " Saves the current labels with an optional name. Resets labels to their default value, unless name begins with a "." character." 1>& 2
echo " $(basename $0) pop [name]" 1>& 2
echo " If name is given, all key labels up to and including the one with the matching name are popped." 1>& 2
echo "" 1>& 2
echo "Example:" 1>& 2
echo "#!/usr/bin/env bash" 1>& 2
echo "# Wrapper script for mc that sets function key labels" 1>& 2
echo "NAME=mc_\$RANDOM" 1>& 2
echo "# Save existing labels" 1>& 2
echo "$(basename $0) push \$NAME" 1>& 2
echo "$(basename $0) set F1 Help" 1>& 2
echo "$(basename $0) set F2 Menu" 1>& 2
echo "$(basename $0) set F3 View" 1>& 2
echo "$(basename $0) set F4 Edit" 1>& 2
echo "$(basename $0) set F5 Copy" 1>& 2
echo "$(basename $0) set F6 Move" 1>& 2
echo "$(basename $0) set F7 Mkdir" 1>& 2
echo "$(basename $0) set F8 Del" 1>& 2
echo "$(basename $0) set F9 Menu" 1>& 2
echo "$(basename $0) set F10 Quit" 1>& 2
echo "$(basename $0) set F11 Menu" 1>& 2
echo "$(basename $0) set F13 View" 1>& 2
echo "$(basename $0) set F14 Edit" 1>& 2
echo "$(basename $0) set F15 Copy" 1>& 2
echo "$(basename $0) set F16 Move" 1>& 2
echo "$(basename $0) set F17 Find" 1>& 2
echo "mc" 1>& 2
echo "# Restore labels to their previous state" 1>& 2
echo "$(basename $0) pop \$NAME" 1>& 2
}
## Main
if [[ $# == 0 ]]
then
show_help
exit 1
fi
if [[ $1 == set ]]
then
if [[ $# != 3 ]]
then
show_help
exit 1
fi
print_osc
printf "1337;SetKeyLabel=%s=%s" "$2" "$3"
print_st
elif [[ $1 == push ]]
then
if [[ $# == 1 ]]
then
print_osc
printf "1337;PushKeyLabels"
print_st
elif [[ $# == 2 ]]
then
if [[ $2 == "" ]]
then
echo "Name must not be empty" 1>& 2
exit 1
fi
print_osc
printf "1337;PushKeyLabels=%s" "$2"
print_st
else
show_help
exit 1
fi
elif [[ $1 == pop ]]
then
if [[ $# == 1 ]]
then
print_osc
printf "1337;PopKeyLabels"
print_st
elif [[ $# == 2 ]]
then
if [[ $2 == "" ]]
then
echo "Name must not be empty" 1>& 2
exit 1
fi
print_osc
printf "1337;PopKeyLabels=%s" "$2"
print_st
else
show_help
exit 1
fi
else
show_help
exit 1
fi

546
.iterm2/it2tip Executable file
View File

@ -0,0 +1,546 @@
#!/usr/bin/env python3
import os
import sys
tips = [
{
"title": "Shell Integration",
"body": "The big new feature of iTerm2 version 3 is Shell Integration. Click “Learn More” for all the details.",
"url": "https://iterm2.com/shell_integration.html"
},
{
"title": "Timestamps",
"body": "“View > Show Timestamps” shows the time (and date, if appropriate) when each line was last modified."
},
{
"title": "Password Manager",
"body": "Did you know iTerm2 has a password manager? Open it with “Window > Password Manager.” You can define a Trigger to open it for you at a password prompt in “Prefs > Profiles > Advanced > Triggers.”"
},
{
"title": "Open Quickly",
"body": "You can quickly search through your sessions with “View > Open Quickly” (⇧⌘O). You can type a query and sessions whose name, badge, current hostname, current user name, recent commands, and recent working directories match will be surfaced. It works best with Shell Integration so the user name, hostname, command, and directories can be known even while sshed.",
"url": "https://iterm2.com/shell_integration.html"
},
{
"title": "Undo Close",
"body": "If you close a session, tab, or window by accident you can undo it with “Edit > Undo” (⌘Z). By default you have five seconds to undo, but you can adjust that timeout in “Prefs > Profiles > Session.”"
},
{
"title": "Annotations",
"body": "Want to mark up your scrollback history? Right click on a selection and choose “Annotate Selection” to add a personal note to it. Use “View > Show Annotations” to show or hide them, and look in “Edit > Marks and Annotations” for more things you can do."
},
{
"title": "Copy with Styles",
"body": "Copy a selection with ⌥⌘C to include styles such as colors and fonts. You can make this the default action for Copy in “Prefs > Advanced.”"
},
{
"title": "Inline Images",
"body": "iTerm2 can display images (even animated GIFs) inline.",
"url": "https://iterm2.com/images.html"
},
{
"title": "Automatic Profile Switching",
"body": "Automatic Profile Switching changes the current profile when the username, hostname, or directory changes. Set it up in “Prefs > Profiles > Advanced.” It requires Shell Integration to be installed.",
"url": "https://iterm2.com/shell_integration.html"
},
{
"title": "Captured Output",
"body": "iTerm2 can act like an IDE using the Captured Output feature. When it sees text matching a regular expression you define, like compiler errors, it shows the matching lines in the Toolbelt. You can click to jump to the line in your terminal and double-click to perform an action like opening an editor to the line with the error.",
"url": "https://iterm2.com/captured_output.html"
},
{
"title": "Badges",
"body": "You can display a status message in the top right of your session in the background. Its called a “Badge.” If you install Shell Integration you can include info like user name, hostname, current directory, and more.",
"url": "https://iterm2.com/badges.html"
},
{
"title": "Dynamic Profiles",
"body": "Dynamic Profiles let you store your profiles as one or more JSON files. Its great for batch creating and editing profiles.",
"url": "https://iterm2.com/dynamic-profiles.html"
},
{
"title": "Advanced Paste",
"body": "“Edit > Paste Special > Advanced Paste” lets you preview and edit text before you paste. You get to tweak options, like how to handle control codes, or even to base-64 encode before pasting."
},
{
"title": "Zoom",
"body": "Ever wanted to focus on a block of lines without distraction, or limit Find to a single commands output? Select the lines and choose “View > Zoom In on Selection.” The sessions contents will be temporarily replaced with the selection. Press “esc” to unzoom."
},
{
"title": "Semantic History",
"body": "The “Semantic History” feature allows you to ⌘-click on a file or URL to open it."
},
{
"title": "Tmux Integration",
"body": "If you use tmux, try running “tmux -CC” to get iTerm2s tmux integration mode. The tmux windows show up as native iTerm2 windows, and you can use iTerm2s keyboard shortcuts. It even works over ssh!",
"url": "https://gitlab.com/gnachman/iterm2/wikis/TmuxIntegration"
},
{
"title": "Triggers",
"body": "iTerm2 can automatically perform actions you define when text matching a regular expression is received. For example, you can highlight text or show an alert box. Set it up in “Prefs > Profiles > Advanced > Triggers.”",
"url": "https://www.iterm2.com/documentation-triggers.html"
},
{
"title": "Smart Selection",
"body": "Quadruple click to perform Smart Selection. It figures out if youre selecting a URL, filename, email address, etc. based on prioritized regular expressions.",
"url": "https://www.iterm2.com/smartselection.html"
},
{
"title": "Instant Replay",
"body": "Press ⌥⌘B to step back in time in a terminal window. Use arrow keys to go frame by frame. Hold ⇧ and press arrow keys to go faster."
},
{
"title": "Hotkey Window",
"body": "You can have a terminal window open with a keystroke, even while in other apps. Click “Create a Dedicated Hotkey Window” in “Prefs > Keys.”"
},
{
"title": "Hotkey Window",
"body": "Hotkey windows can stay open after losing focus. Turn it on in “Window > Pin Hotkey Window.”"
},
{
"title": "Cursor Guide",
"body": "The cursor guide is a horizontal line that follows your cursor. You can turn it on in “Prefs > Profiles > Colors” or toggle it with the ⌥⌘; shortcut."
},
{
"title": "Shell Integration: Alerts",
"body": "The Shell Integration feature lets you ask to be alerted (⌥⌘A) when a long-running command completes.",
"url": "https://iterm2.com/shell_integration.html"
},
{
"title": "Cursor Blink Rate",
"body": "You can configure how quickly the cursor blinks in “Prefs > Advanced.”"
},
{
"title": "Shell Integration: Navigation",
"body": "The Shell Integration feature lets you navigate among shell prompts with ⇧⌘↑ and ⇧⌘↓.",
"url": "https://iterm2.com/shell_integration.html"
},
{
"title": "Shell Integration: Status",
"body": "The Shell Integration feature puts a blue arrow next to your shell prompt. If you run a command that fails, it turns red. Right click on it to get the running time and status.",
"url": "https://iterm2.com/shell_integration.html"
},
{
"title": "Shell Integration: Selection",
"body": "With Shell Integration installed, you can select the output of the last command with ⇧⌘A.",
"url": "https://iterm2.com/shell_integration.html"
},
{
"title": "Bells",
"body": "The dock icon shows a count of the number of bells rung and notifications posted since the app was last active."
},
{
"title": "Shell Integration: Downloads",
"body": "If you install Shell Integration on a machine you ssh to, you can right click on a filename (for example, in the output of “ls”) and choose “Download with scp” to download the file.",
"url": "https://iterm2.com/shell_integration.html"
},
{
"title": "Find Your Cursor",
"body": "Press ⌘/ to locate your cursor. Its fun!"
},
{
"title": "Customize Smart Selection",
"body": "You can edit Smart Selection regular expressions in “Prefs > Profiles > Advanced > Smart Selection.”",
"url": "https://www.iterm2.com/smartselection.html"
},
{
"title": "Smart Selection Actions",
"body": "Assign an action to a Smart Selection rule in “Prefs > Profiles > Advanced > Smart Selection > Edit Actions.” They go in the context menu and override semantic history on ⌘-click.",
"url": "https://www.iterm2.com/smartselection.html"
},
{
"title": "Visual Bell",
"body": "If you want the visual bell to flash the whole screen instead of show a bell icon, you can turn that on in “Prefs > Advanced.”"
},
{
"title": "Tab Menu",
"body": "Right click on a tab to change its color, close tabs after it, or to close all other tabs."
},
{
"title": "Tags",
"body": "You can assign tags to your profiles, and by clicking “Tags>” anywhere you see a list of profiles you can browse those tags."
},
{
"title": "Tag Hierarchy",
"body": "If you put a slash in a profiles tag, that implicitly defines a hierarchy. You can see it in the Profiles menu as nested submenus."
},
{
"title": "Downloads",
"body": "iTerm2 can download files by base-64 encoding them. Click “Learn More” to download a shell script that makes it easy.",
"url": "https://iterm2.com/download.sh"
},
{
"title": "Command Completion",
"body": "If you install Shell Integration, ⇧⌘; helps you complete commands. It remembers the commands youve run on each host that has Shell Integration installed. It knows how often that command was run and how recently to help make the best suggestions.",
"url": "https://iterm2.com/shell_integration.html"
},
{
"title": "Recent Directories",
"body": "iTerm2 remembers which directories you use the most on each host that has Shell Integration installed. Theres a Toolbelt tool to browse them, and ⌥⌘/ gives you a popup sorted by frequency and recency of use.",
"url": "https://iterm2.com/shell_integration.html"
},
{
"title": "Favorite Directories",
"body": "If you have Shell Integration installed, you can “star” a directory to keep it always at the bottom of the Recent Directories tool in the Toolbelt. Right click and choose “Toggle Star.”",
"url": "https://iterm2.com/shell_integration.html"
},
{
"title": "Shell Integration History",
"body": "Install Shell Integration and turn on “Prefs > General > Save copy/paste and command history to disk” to remember command history per host across restarts of iTerm2.",
"url": "https://iterm2.com/shell_integration.html"
},
{
"title": "Paste File as Base64",
"body": "Copy a file to the pasteboard in Finder and then use “Edit > Paste Special > Paste File Base64-Encoded” for easy uploads of binary files. Use ”base64 -D” (or -d on Linux) on the remote host to decode it."
},
{
"title": "Split Panes",
"body": "You can split a tab into multiple panes with ⌘D and ⇧⌘D."
},
{
"title": "Adjust Split Panes",
"body": "Resize split panes with the keyboard using ^⌘-Arrow Key."
},
{
"title": "Move Cursor",
"body": "Hold ⌥ and click to move your cursor. It works best with Shell Integration installed (to avoid sending up/down arrow keys to your shell).",
"url": "https://iterm2.com/shell_integration.html"
},
{
"title": "Edge Windows",
"body": "You can tell your profile to create windows that are attached to one edge of the screen in “Prefs > Profiles > Window.” You can resize them by dragging the edges."
},
{
"title": "Tab Color",
"body": "You can assign colors to tabs in “Prefs > Profiles > Colors,” or in the View menu."
},
{
"title": "Rectangular Selection",
"body": "Hold ⌥⌘ while dragging to make a rectangular selection."
},
{
"title": "Multiple Selection",
"body": "Hold ⌘ while dragging to make multiple discontinuous selections."
},
{
"title": "Dragging Panes",
"body": "Hold ⇧⌥⌘ and drag a session into another session to create or change split panes."
},
{
"title": "Cursor Boost",
"body": "Adjust Cursor Boost in “Prefs > Profiles > Colors” to make all colors more muted, except the cursor. Use a bright white cursor and it pops!"
},
{
"title": "Minimum Contrast",
"body": "Adjust “Minimum Contrast” in “Prefs > Profiles > Colors” to ensure text is always legible regardless of text/background color combination."
},
{
"title": "Tabs",
"body": "Normally, new tabs appear at the end of the tab bar. Theres a setting in “Prefs > Advanced” to place them next to your current tab."
},
{
"title": "Base Conversion",
"body": "Right-click on a number and the context menu shows it converted to hex or decimal as appropriate."
},
{
"title": "Saved Searches",
"body": "In “Prefs > Keys” you can assign a keystroke to a search for a regular expression with the “Find Regular Expression…” action."
},
{
"title": "Find URLs",
"body": "Search for URLs using “Edit > Find > Find URLs.” Navigate search results with ⌘G and ⇧⌘G. Open the current selection with ⌥⌘O."
},
{
"title": "Triggers",
"body": "The “instant” checkbox in a Trigger allows it to fire while the cursor is on the same line as the text that matches your regular expression."
},
{
"title": "Soft Boundaries",
"body": "Turn on “Edit > Selection Respects Soft Boundaries” to recognize split pane dividers in programs like vi, emacs, and tmux so you can select multiple lines of text."
},
{
"title": "Select Without Dragging",
"body": "Single click where you want to start a selection and ⇧-click where you want it to end to select text without dragging."
},
{
"title": "Smooth Window Resizing",
"body": "Hold ^ while resizing a window and it wont snap to the character grid: you can make it any size you want."
},
{
"title": "Pasting Tabs",
"body": "If you paste text containing tabs, youll be asked if you want to convert them to spaces. Its handy at the shell prompt to avoid triggering filename completion."
},
{
"title": "Bell Silencing",
"body": "Did you know? If the bell rings too often, youll be asked if youd like to silence it temporarily. iTerm2 cares about your comfort."
},
{
"title": "Profile Search",
"body": "Every list of profiles has a search field (e.g., in ”Prefs > Profiles.”) You can use various operators to restrict your search query. Click “Learn More” for all the details.",
"url": "https://iterm2.com/search_syntax.html"
},
{
"title": "Color Schemes",
"body": "The online color gallery features over one hundred beautiful color schemes you can download.",
"url": "https://www.iterm2.com/colorgallery"
},
{
"title": "ASCII/Non-Ascii Fonts",
"body": "You can have a separate font for ASCII versus non-ASCII text. Enable it in “Prefs > Profiles > Text.”"
},
{
"title": "Coprocesses",
"body": "A coprocess is a job, such as a shell script, that has a special relationship with a particular iTerm2 session. All output in a terminal window (that is, what you see on the screen) is also input to the coprocess. All output from the coprocess acts like text that the user is typing at the keyboard.",
"url": "https://iterm2.com/coprocesses.html"
},
{
"title": "Touch Bar Customization",
"body": "You can customize the touch bar by selecting “View > Customize Touch Bar.” You can add a tab bar for full-screen mode, a user-customizable status button, and you can even define your own touch bar buttons in Prefs > Keys. Theres also a new shell integration tool to customize touch bar function key labels."
},
{
"title": "Ligatures",
"body": "If you use a font that supports ligatures, you can enable ligature support in Prefs > Profiles > Text."
},
{
"title": "Floating Hotkey Window",
"body": "New in 3.1: You can configure your hotkey window to appear over other apps full screen windows. Turn on “Floating Window” in “Prefs > Profiles > Keys > Customize Hotkey Window.”"
},
{
"title": "Multiple Hotkey Windows",
"body": "New in 3.1: You can have multiple hotkey windows. Each profile can have one or more hotkeys."
},
{
"title": "Double-Tap Hotkey",
"body": "New in 3.1: You can configure a hotkey window to open on double-tap of a modifier in “Prefs > Profiles > Keys > Customize Hotkey Window.”"
},
{
"title": "Buried Sessions",
"body": "You can “bury” a session with “Session > Bury Session.” It remains hidden until you restore it by selecting it from “Session > Buried Sessions > Your session.”"
},
{
"title": "Python API",
"body": "You can add custom behavior to iTerm2 using the Python API.",
"url": "https://iterm2.com/python-api"
},
{
"title": "Status Bar",
"body": "You can add a configurable status bar to your terminal windows.",
"url": "https://iterm2.com/3.3/documentation-status-bar.html"
},
{
"title": "Minimal Theme",
"body": "Try the “Minimal” and “Compact” themes to reduce visual clutter. You can set it in “Prefs > Appearance > General.”"
},
{
"title": "Session Titles",
"body": "You can configure which elements are present in session titles in “Prefs > Profiles > General > Title.”"
},
{
"title": "Tab Icons",
"body": "Tabs can show an icon indicating the current application. Configure it in “Prefs > Profiles > General > Icon.”"
},
{
"title": "Drag Window by Tab",
"body": "Hold ⌥ while dragging a tab to move the window. This is useful in the Compact and Minimal themes, which have a very small area for dragging the window."
},
{
"title": "Composer",
"body": "Press ⇧⌘. to open the Composer. It gives you a scratchpad to edit a command before sending it to the shell."
},
{
"title": "Shell Integration: Uploads",
"body": "If you install Shell Integration on a machine you ssh to, you can drag-drop from Finder into the remote host by holding ⌥ while dragging. The destination directory is determined by where you drop the file in the terminal window: run cd foo, then drop the file below the cd command, and the file will go into the foo directory.",
"url": "https://iterm2.com/shell_integration.html"
},
{
"title": "Composer Power Features",
"body": "The composer supports multiple cursors. It also has the ability to send just one command out of a list, making it easy to walk through a list of commands one-by-one. Click the help button in the composer for details."
},
{ "title": "Render Selection",
"body": "Transform selected text into a prettified, syntax-highlighted view with the “Render Selection” command, ideal for JSON, Markdown, or source code. This feature includes horizontal scrolling for easy log navigation."
},
{ "title": "SSH Integration",
"body": "Export environment variables and copy files to remote hosts seamlessly with SSH integration. Either configure a profile to use ssh or use it2ssh in place of ssh."
},
{ "title": "Auto Composer",
"body": "Improve your command line with the “auto composer”, which replaces the command line with a native control for ease of use. Requires shell integration."
},
{ "title": "AI Command Writing",
"body": "Generate commands using AI by entering a prompt in the composer and selecting “Edit > Engage Artificial Intelligence”. An OpenAI API key is required for this functionality."
},
{ "title": "Codecierge Tool",
"body": "Set and achieve terminal goals with “Codecierge”, a Toolbelt feature that guides you step-by-step based on your terminal activity. An OpenAI API key is necessary for this feature."
},
{ "title": "Named Marks",
"body": "Navigate your command history effortlessly with “named marks” by assigning names to lines in the terminal."
},
{ "title": "Font Assignments",
"body": "You can assign specific fonts to Unicode ranges. Use 'Settings > Profiles > Text > Manage Special Exceptions' to manage it and to install a huge set of Powerline symbols."
},
{ "title": "Disable Transparency",
"body": "Maintain clarity in your active window while enjoying transparency in background windows by using 'View > Disable transparency in key window'."
},
{ "title": "Leader Shortcut",
"body": "Create two-keystroke shortcuts with a “leader”: a special keystroke that precedes a custom key binding."
},
{ "title": "Sequence Binding",
"body": "Execute a series of actions in order with a single shortcut using “sequence” key bindings."
},
{ "title": "Export/Import Settings",
"body": "Easily backup or transfer your iTerm2 settings using the Export/Import feature in “Settings > General > Preferences”."
},
{ "title": "Multi-Session Bindings",
"body": "Apply key bindings uniformly across multiple sessions for consistent control in different tabs or windows."
},
{ "title": "Inject Trigger",
"body": "Simulate terminal input as if it were output from a running app with the “Inject” trigger."
},
{ "title": "Trigger Status Bar",
"body": "Easily manage your triggers using the new Triggers status bar component."
},
{ "title": "Session Size in Tab",
"body": "Display session size directly in tab titles for convenient at-a-glance information."
},
{ "title": "Advanced Snippet Editing",
"body": "Edit snippets in Advanced Paste by holding the ⌥ key, or open them in the composer with ⇧."
},
{ "title": "HTML Logs",
"body": "Save your terminal logs in HTML format for enhanced readability and sharing capabilities."
},
{ "title": "ASCIICast Logs",
"body": "Create and play back terminal recordings with ASCIICast logs, compatible with asciinema."
},
{ "title": "Timestamped Logs",
"body": "Include timestamps in your logs for better tracking and event correlation."
},
{ "title": "LastPass & 1Password",
"body": "Utilize LastPass or 1Password with the password manager by configuring it in the menu next to the search field."
},
{ "title": "Password Manager Access",
"body": "Access your password manager without authentication by adjusting the settings via the menu next to its search field."
},
{ "title": "Password Generation",
"body": "Generate strong, secure passwords using the password managers new password generation feature."
},
{ "title": "it2tip Utility",
"body": "Access tips of the day with the it2tip utility, a command line app. Enable it by installing shell integration and utilities."
},
{ "title": "Auto Shell Integration",
"body": "Experience automatic shell integration when creating a login shell, removing the need for explicit setup on your Mac."
},
{ "title": "Command Prompt Info",
"body": "Get detailed information about commands by ⌘-clicking on the command prompt."
},
{ "title": "tmux Integration",
"body": "Use tmux integration for automatic key bindings that emulate tmuxs shortcuts, configurable via the Leader settings."
},
{ "title": "tmux Clipboard Mirroring",
"body": "Sync your tmux paste buffer with the local clipboard for seamless integration (requires tmux 3.4)."
},
{ "title": "Multi-Cursor in Composer",
"body": "Enhance your editing in the Composer with multiple cursors, created using ^⇧-up/down or ⌥-drag."
},
{ "title": "Advanced Paste from Composer",
"body": "Move content from the Composer to the Advanced Paste window with ⌥⌘V for additional editing options."
},
{ "title": "Composer Search",
"body": "Search within the Composer using ⌘F to quickly find specific text."
},
{ "title": "Resize Composer",
"body": "Adjust the Composers height to suit your needs by dragging its bottom edge."
},
{ "title": "Explain Command",
"body": "Learn more about your commands by ⌘-clicking in the Composer to open them in explainshell.com."
},
{ "title": "Quick Command Send",
"body": "Quickly send and remove commands in the Composer using ⌥⇧-enter."
},
{ "title": "Queue Commands",
"body": "Queue up a command in the Composer to be sent after the current command finishes with ⌥-Enter."
},
{ "title": "Draggable Tip Window",
"body": "Reposition the Tip of the Day window conveniently on your screen, as it is now draggable."
},
]
home = os.getenv("XDG_DATA_HOME")
if not home:
home = "~"
RCFILE = os.path.expanduser(os.path.join(home, '.it2totd'))
def last_index():
try:
with open(RCFILE) as f:
lines = f.readlines()
return int(lines[0].rstrip())
except:
return -1
def print_tip(i):
def dcs(args):
return "\x1bP" + ";".join(args)
def osc(args):
term = os.getenv("TERM")
if term.startswith("screen"):
return dcs(["tmux", "\x1b\x1b]"]) + ";".join(args) + "\a\x1b\\"
else:
return "\x1b]" + ";".join(args) + "\x1b\\"
tip = tips[i]
print(f'iTerm2 tip - {tip["title"]}:')
print(tip["body"])
if "url" in tip:
print("Learn more: " + osc(["8", "", tip["url"]]) + tip["url"] + osc(["8", "", ""]))
def save_index(i):
with open(RCFILE, "w") as f:
f.write(str(i))
i = last_index() + 1
if i >= len(tips) and len(sys.argv) > 1 and sys.argv[1] == "-w":
i = 0
if i < len(tips):
print_tip(i)
save_index(i)

107
.iterm2/it2ul Executable file
View File

@ -0,0 +1,107 @@
#!/usr/bin/env bash
trap clean_up EXIT
_STTY=$(stty -g) ## Save current terminal setup
stty -echo ## Turn off echo
function clean_up() {
stty "$_STTY" ## Restore terminal settings
}
function show_help() {
echo "Usage: $(basename $0) [destination [tar flags]]" 1>& 2
echo " If given, the destination specifies the directory to place downloaded files."
echo " Further options are passed through to tar. See your system's manpage for tar for details."
}
function bad_input() {
echo "Bad input: %1" 1>& 2
exit 1
}
function die() {
echo "Fatal error: $1" 1>& 2
exit 1
}
function read_base64_stanza() {
value=""
while read line;
do
if [ "$line" == "" ]; then
break
fi
printf "%s" "$line"
done
}
function decode() {
VERSION=$(base64 --version 2>&1)
if [[ "$VERSION" =~ fourmilab ]]; then
BASE64ARG=-d
elif [[ "$VERSION" =~ GNU ]]; then
BASE64ARG=-di
else
BASE64ARG=-D
fi
base64 "$BASE64ARG" <<< "$1"
}
# tmux requires unrecognized OSC sequences to be wrapped with DCS tmux;
# <sequence> ST, and for all ESCs in <sequence> to be replaced with ESC ESC. It
# only accepts ESC backslash for ST.
function print_osc() {
if [[ $TERM == screen* || $TERM == tmux* ]] ; then
printf "\033Ptmux;\033\033]"
else
printf "\033]"
fi
}
# More of the tmux workaround described above.
function print_st() {
if [[ $TERM == screen* || $TERM == tmux* ]] ; then
printf "\a\033\\"
else
printf "\a"
fi
}
function b64_encode() {
if [[ "$IT2DL_BASE64_VERSION" =~ GNU ]]; then
# Disable line wrap
base64 -w0
else
base64
fi
}
function send_request_for_upload() {
print_osc
printf '1337;RequestUpload=format=tgz;version=%s' "$(tar --version | head -1 | b64_encode)"
print_st
}
location="$PWD"
if [[ $# > 0 ]]
then
location="$1"
shift
fi
send_request_for_upload
read status
if [[ $status == ok ]]
then
data=$(read_base64_stanza)
clean_up
decode "$data" | tar -x -z -C "$location" -f - $* 1>& 2
elif [[ $status == abort ]]
then
echo "Upload aborted" 1>& 2
else
die "Unknown status: $status" 1>& 2
fi

104
.iterm2/it2universion Executable file
View File

@ -0,0 +1,104 @@
#!/usr/bin/env bash
# tmux requires unrecognized OSC sequences to be wrapped with DCS tmux;
# <sequence> ST, and for all ESCs in <sequence> to be replaced with ESC ESC. It
# only accepts ESC backslash for ST.
function print_osc() {
if [[ $TERM == screen* || $TERM == tmux* ]] ; then
printf "\033Ptmux;\033\033]"
else
printf "\033]"
fi
}
# More of the tmux workaround described above.
function print_st() {
if [[ $TERM == screen* || $TERM == tmux* ]] ; then
printf "\a\033\\"
else
printf "\a"
fi
}
function show_help() {
echo "Usage:" 1>& 2
echo " $(basename $0) set 8" 1>& 2
echo " $(basename $0) set 9" 1>& 2
echo " $(basename $0) push [name]" 1>& 2
echo " Saves the current version with an optional name." 1>& 2
echo " $(basename $0) pop [name]" 1>& 2
echo " If name is given, all versions up to and including the one with the matching name are popped." 1>& 2
}
function set_version() {
print_osc
printf "1337;UnicodeVersion=$1"
print_st
}
function push_version() {
print_osc
printf "1337;UnicodeVersion=push $1"
print_st
}
function pop_version() {
print_osc
printf "1337;UnicodeVersion=pop $1"
print_st
}
## Main
if [[ $# == 0 ]]
then
show_help
exit 1
fi
if [[ $1 == set ]]
then
if [[ $# != 2 ]]
then
show_help
exit 1
fi
set_version $2
elif [[ $1 == push ]]
then
if [[ $# == 1 ]]
then
push_version ""
elif [[ $# == 2 ]]
then
if [[ $2 == "" ]]
then
echo "Name must not be empty" 1>& 2
exit 1
fi
push_version "$2"
else
show_help
exit 1
fi
elif [[ $1 == pop ]]
then
if [[ $# == 1 ]]
then
pop_version ""
elif [[ $# == 2 ]]
then
if [[ $2 == "" ]]
then
echo "Name must not be empty" 1>& 2
exit 1
fi
pop_version "$2"
else
show_help
exit 1
fi
else
show_help
exit 1
fi

179
.iterm2_shell_integration.zsh Executable file
View File

@ -0,0 +1,179 @@
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
if [[ -o interactive ]]; then
if [ "${ITERM_ENABLE_SHELL_INTEGRATION_WITH_TMUX-}""$TERM" != "tmux-256color" -a "${ITERM_ENABLE_SHELL_INTEGRATION_WITH_TMUX-}""$TERM" != "screen" -a "${ITERM_SHELL_INTEGRATION_INSTALLED-}" = "" -a "$TERM" != linux -a "$TERM" != dumb ]; then
ITERM_SHELL_INTEGRATION_INSTALLED=Yes
ITERM2_SHOULD_DECORATE_PROMPT="1"
# Indicates start of command output. Runs just before command executes.
iterm2_before_cmd_executes() {
if [ "$TERM_PROGRAM" = "iTerm.app" ]; then
printf "\033]133;C;\r\007"
else
printf "\033]133;C;\007"
fi
}
iterm2_set_user_var() {
printf "\033]1337;SetUserVar=%s=%s\007" "$1" $(printf "%s" "$2" | base64 | tr -d '\n')
}
# Users can write their own version of this method. It should call
# iterm2_set_user_var but not produce any other output.
# e.g., iterm2_set_user_var currentDirectory $PWD
# Accessible in iTerm2 (in a badge now, elsewhere in the future) as
# \(user.currentDirectory).
whence -v iterm2_print_user_vars > /dev/null 2>&1
if [ $? -ne 0 ]; then
iterm2_print_user_vars() {
true
}
fi
iterm2_print_state_data() {
local _iterm2_hostname="${iterm2_hostname-}"
if [ -z "${iterm2_hostname:-}" ]; then
_iterm2_hostname=$(hostname -f 2>/dev/null)
fi
printf "\033]1337;RemoteHost=%s@%s\007" "$USER" "${_iterm2_hostname-}"
printf "\033]1337;CurrentDir=%s\007" "$PWD"
iterm2_print_user_vars
}
# Report return code of command; runs after command finishes but before prompt
iterm2_after_cmd_executes() {
printf "\033]133;D;%s\007" "$STATUS"
iterm2_print_state_data
}
# Mark start of prompt
iterm2_prompt_mark() {
printf "\033]133;A\007"
}
# Mark end of prompt
iterm2_prompt_end() {
printf "\033]133;B\007"
}
# There are three possible paths in life.
#
# 1) A command is entered at the prompt and you press return.
# The following steps happen:
# * iterm2_preexec is invoked
# * PS1 is set to ITERM2_PRECMD_PS1
# * ITERM2_SHOULD_DECORATE_PROMPT is set to 1
# * The command executes (possibly reading or modifying PS1)
# * iterm2_precmd is invoked
# * ITERM2_PRECMD_PS1 is set to PS1 (as modified by command execution)
# * PS1 gets our escape sequences added to it
# * zsh displays your prompt
# * You start entering a command
#
# 2) You press ^C while entering a command at the prompt.
# The following steps happen:
# * (iterm2_preexec is NOT invoked)
# * iterm2_precmd is invoked
# * iterm2_before_cmd_executes is called since we detected that iterm2_preexec was not run
# * (ITERM2_PRECMD_PS1 and PS1 are not messed with, since PS1 already has our escape
# sequences and ITERM2_PRECMD_PS1 already has PS1's original value)
# * zsh displays your prompt
# * You start entering a command
#
# 3) A new shell is born.
# * PS1 has some initial value, either zsh's default or a value set before this script is sourced.
# * iterm2_precmd is invoked
# * ITERM2_SHOULD_DECORATE_PROMPT is initialized to 1
# * ITERM2_PRECMD_PS1 is set to the initial value of PS1
# * PS1 gets our escape sequences added to it
# * Your prompt is shown and you may begin entering a command.
#
# Invariants:
# * ITERM2_SHOULD_DECORATE_PROMPT is 1 during and just after command execution, and "" while the prompt is
# shown and until you enter a command and press return.
# * PS1 does not have our escape sequences during command execution
# * After the command executes but before a new one begins, PS1 has escape sequences and
# ITERM2_PRECMD_PS1 has PS1's original value.
iterm2_decorate_prompt() {
# This should be a raw PS1 without iTerm2's stuff. It could be changed during command
# execution.
ITERM2_PRECMD_PS1="$PS1"
ITERM2_SHOULD_DECORATE_PROMPT=""
# Add our escape sequences just before the prompt is shown.
# Use ITERM2_SQUELCH_MARK for people who can't mdoify PS1 directly, like powerlevel9k users.
# This is gross but I had a heck of a time writing a correct if statetment for zsh 5.0.2.
local PREFIX=""
if [[ $PS1 == *"$(iterm2_prompt_mark)"* ]]; then
PREFIX=""
elif [[ "${ITERM2_SQUELCH_MARK-}" != "" ]]; then
PREFIX=""
else
PREFIX="%{$(iterm2_prompt_mark)%}"
fi
PS1="$PREFIX$PS1%{$(iterm2_prompt_end)%}"
ITERM2_DECORATED_PS1="$PS1"
}
iterm2_precmd() {
local STATUS="$?"
if [ -z "${ITERM2_SHOULD_DECORATE_PROMPT-}" ]; then
# You pressed ^C while entering a command (iterm2_preexec did not run)
iterm2_before_cmd_executes
if [ "$PS1" != "${ITERM2_DECORATED_PS1-}" ]; then
# PS1 changed, perhaps in another precmd. See issue 9938.
ITERM2_SHOULD_DECORATE_PROMPT="1"
fi
fi
iterm2_after_cmd_executes "$STATUS"
if [ -n "$ITERM2_SHOULD_DECORATE_PROMPT" ]; then
iterm2_decorate_prompt
fi
}
# This is not run if you press ^C while entering a command.
iterm2_preexec() {
# Set PS1 back to its raw value prior to executing the command.
PS1="$ITERM2_PRECMD_PS1"
ITERM2_SHOULD_DECORATE_PROMPT="1"
iterm2_before_cmd_executes
}
# If hostname -f is slow on your system set iterm2_hostname prior to
# sourcing this script. We know it is fast on macOS so we don't cache
# it. That lets us handle the hostname changing like when you attach
# to a VPN.
if [ -z "${iterm2_hostname-}" ]; then
if [ "$(uname)" != "Darwin" ]; then
iterm2_hostname=`hostname -f 2>/dev/null`
# Some flavors of BSD (i.e. NetBSD and OpenBSD) don't have the -f option.
if [ $? -ne 0 ]; then
iterm2_hostname=`hostname`
fi
fi
fi
[[ -z ${precmd_functions-} ]] && precmd_functions=()
precmd_functions=($precmd_functions iterm2_precmd)
[[ -z ${preexec_functions-} ]] && preexec_functions=()
preexec_functions=($preexec_functions iterm2_preexec)
iterm2_print_state_data
printf "\033]1337;ShellIntegrationVersion=14;shell=zsh\007"
fi
fi
alias imgcat=${HOME}/.iterm2/imgcat;alias imgls=${HOME}/.iterm2/imgls;alias it2api=${HOME}/.iterm2/it2api;alias it2attention=${HOME}/.iterm2/it2attention;alias it2check=${HOME}/.iterm2/it2check;alias it2copy=${HOME}/.iterm2/it2copy;alias it2dl=${HOME}/.iterm2/it2dl;alias it2getvar=${HOME}/.iterm2/it2getvar;alias it2git=${HOME}/.iterm2/it2git;alias it2setcolor=${HOME}/.iterm2/it2setcolor;alias it2setkeylabel=${HOME}/.iterm2/it2setkeylabel;alias it2tip=${HOME}/.iterm2/it2tip;alias it2ul=${HOME}/.iterm2/it2ul;alias it2universion=${HOME}/.iterm2/it2universion;alias it2profile=${HOME}/.iterm2/it2profile;alias it2cat=${HOME}/.iterm2/it2cat

1
.vim Symbolic link
View File

@ -0,0 +1 @@
/Users/joelillibridge/.SpaceVim

5
.zshrc
View File

@ -26,7 +26,8 @@ alias bs="brew search"
# YADM aliases # YADM aliases
alias y="yadm" alias y="yadm"
alias ys="yadm status" alias ys="y status"
alias ysu="ys -u"
# These depend on some installed packages, so just to be safe # These depend on some installed packages, so just to be safe
[[ "$(command -v bat)" ]] && alias cat="bat" [[ "$(command -v bat)" ]] && alias cat="bat"
@ -38,7 +39,7 @@ export CLICOLOR=1
# export ZSH_HIGHLIGHT_HIGHLIGHTERS_DIR=/opt/homebrew/share/zsh-syntax-highlighting/highlighters # export ZSH_HIGHLIGHT_HIGHLIGHTERS_DIR=/opt/homebrew/share/zsh-syntax-highlighting/highlighters
# Load functions # Load functions
fpath=("$HOME/.functions" "${fpath[@]}") fpath+=( "$HOME/.config/zsh/functions" )
autoload -Uz ql f brew-visit tre compinit && compinit autoload -Uz ql f brew-visit tre compinit && compinit
[ -f ~/.fzf.zsh ] && source ~/.fzf.zsh && source <(fzf --zsh) [ -f ~/.fzf.zsh ] && source ~/.fzf.zsh && source <(fzf --zsh)