# vim: ft=tmux

set -g default-terminal "$TERM"
# Enable undercurl and color.
set -ga terminal-features ",*:usstyle"
# Support RGB color with SGR escape sequences.
set -gs terminal-overrides ",*:RGB"

unbind C-b
set -g prefix2 C-a
bind C-a send-prefix

# reload ~/.tmux.conf using PREFIX r
bind-key r source-file ~/.config/tmux/tmux.conf \; display "Reloaded!"

set -g history-limit 1000000

# Neovim https://github.com/neovim/neovim/wiki/FAQ#esc-in-tmux-or-gnu-screen-is-delayed
set -sg escape-time 0
set -g focus-events on

# set window and pane index to 1 (0 by default)
set -g base-index 1
set -g pane-base-index 1
set -g automatic-rename on
set -g renumber-windows on # re-number windows when one is closed
set -g set-titles on                        # set terminal title
set -g set-titles-string '#h ❐ #S ● #I #W'
set -g display-time 1500 # tmux messages are displayed for 1.5 seconds
set -g display-panes-time 800 # slightly longer pane indicators display time

# Rather than constraining window size to the maximum size of any client
# connected to the *session*, constrain window size to the maximum size of any
# client connected to *that window*. Much more reasonable.
setw -g aggressive-resize on

# loud or quiet?
set -g monitor-activity on
set -g visual-activity off

# use vim keybindings in copy mode
set -g mode-keys vi
set -g other-pane-height 25
set -g other-pane-width 80

# Make base16-shell work by turning passthrough of escape sequences.
# (Needed on tmux 3.3 and later).
# Also, `yazi`: https://yazi-rs.github.io/docs/image-preview/
set -gq allow-passthrough on

# =======================================================================
# = Key Bindings
# =======================================================================

# Smart pane switching with awareness of Vim splits.
# See: https://github.com/christoomey/vim-tmux-navigator
%hidden VIM_PATTERN='(\\S+\\/)?g?\.?(view|l?n?vim?x?|fzf)(diff)?(-wrapped)?$'
%hidden IS_VIM="ps -o state= -o comm= -t '#{pane_tty}' \
    | grep -iqE '^[^TXZ ]+ +${VIM_PATTERN}'"
%hidden TMUX_VERSION='$(tmux -V | sed -En "s/^tmux ([0-9]+(.[0-9]+)?).*/\1/p")'

if-shell -b '[ "$(echo "$TMUX_VERSION < 3.0" | bc)" = 1 ]' \
    "bind-key -n 'C-\\' if-shell \"$IS_VIM\" 'send-keys C-\\'  'select-pane -l'"
if-shell -b '[ "$(echo "$TMUX_VERSION >= 3.0" | bc)" = 1 ]' \
    "bind-key -n 'C-\\' if-shell \"$IS_VIM\" 'send-keys C-\\\\'  'select-pane -l'"

bind-key -n 'C-h' if-shell "$IS_VIM" 'send-keys C-h'  'select-pane -L'
bind-key -n 'C-j' if-shell "$IS_VIM" 'send-keys C-j'  'select-pane -D'
bind-key -n 'C-k' if-shell "$IS_VIM" 'send-keys C-k'  'select-pane -U'
bind-key -n 'C-l' if-shell "$IS_VIM" 'send-keys C-l'  'select-pane -R'
bind-key -T copy-mode-vi 'C-h' select-pane -L
bind-key -T copy-mode-vi 'C-j' select-pane -D
bind-key -T copy-mode-vi 'C-k' select-pane -U
bind-key -T copy-mode-vi 'C-l' select-pane -R
bind -r C-h run "tmux select-pane -L"
bind -r C-j run "tmux select-pane -D"
bind -r C-k run "tmux select-pane -U"
bind -r C-l run "tmux select-pane -R"

# mouse behavior
set -g mouse on
bind-key -n WheelUpPane if-shell -F -t = "#{mouse_any_flag}" "send-keys -M" "if -Ft= '#{pane_in_mode}' 'send-keys -M' 'select-pane -t=; copy-mode -e; send-keys -M'"
bind-key -n WheelDownPane select-pane -t= \; send-keys -M

# Quick kill-session
bind-key C-q confirm-before 'kill-session'
# Disable confirm before killing
bind-key x kill-pane
bind-key -n C-p choose-tree -Z

# Pressing Ctrl+Shift+Left (will move the current window to the left. Similarly
# right. No need to use the modifier (C-b).
bind-key -n C-S-Left swap-window -t -1
bind-key -n C-S-Right swap-window -t +1

bind-key -n S-Right next-window
bind-key -n S-Left previous-window

unbind-key c
bind-key c new-window -ac '#{pane_current_path}'
# use vim-like keys for splits and windows
bind-key v split-window -h -c "#{pane_current_path}"
bind-key s split-window -v -c "#{pane_current_path}"

bind-key C-o rotate-window

bind-key + select-layout main-horizontal
bind-key = select-layout main-vertical

# bind-key a last-pane
bind-key q display-panes

# Resizing (mouse also works).
unbind-key Left
unbind-key Right
unbind-key Down
unbind-key Up
bind-key -r Left resize-pane -L 10
bind-key -r Right resize-pane -R 10
bind-key -r Down resize-pane -D 10
bind-key -r Up resize-pane -U 10

# https://github.com/zanshin/dotfiles/blob/master/tmux/tmux.conf
# ---------------------
# Copy & Paste
# ---------------------
bind-key -T copy-mode-vi v send-keys -X begin-selection
bind-key -T copy-mode-vi V send-keys -X select-line
bind-key -T copy-mode-vi r send-keys -X rectangle-toggle
bind-key -T copy-mode-vi Escape send-keys -X cancel
bind-key -T copy-mode-vi y if-shell "test ! -z $KITTY_WINDOW_ID" "send-keys -X copy-pipe-and-cancel 'kitty +kitten clipboard'" "send-keys -X copy-pipe-and-cancel  'pbcopy'"
bind-key -T copy-mode-vi MouseDragEnd1Pane if-shell "test ! -z $KITTY_WINDOW_ID" "send-keys -X copy-pipe-and-cancel 'kitty +kitten clipboard'" "send-keys -X copy-pipe-and-cancel  'pbcopy'"

# Save entire tmux history to a file - file will be on machine where tmux is
# running
bind-key * command-prompt -p 'save history to filename:' -I '~/tmux.history' 'capture-pane -S -32768 ; save-buffer %1 ; delete-buffer'

# ----------------------
# Popups
# ----------------------

# This will override time command
# quickly show a popup with a terminal on top of everything
bind t display-popup -d "#{pane_current_path}" -w "75%" -h "75%"


# ----------------------
# set some pretty colors
# ----------------------
# colorize messages in the command line
set -g message-style bg=terminal,fg=brightred #base02
set -g message-command-style bg=black,fg=blue

# ----------------------
# Panes
# -----------------------

set -g pane-border-style bg=terminal,fg=colour235
set -g pane-active-border-style bg=terminal,fg=colour235
set -g pane-border-status top

# Copied from https://github.com/wincent/wincent/blob/c02f91d6821f687305fe4f03911d62c8fa36eeb6/aspects/dotfiles/files/.config/tmux/tmux.conf
# Show copy mode info in pane border. We suppress it (elsewhere) by setting our
# bindings to use the `-H` switch to the `copy-mode` command.
#
# Note that we show position as offset from top of history to make it less
# confusing (tmux usually shows offset from bottom).
#
# - #{?condition,consequent,else} is ternary syntax.
# - #{==:#{pane_mode},copy-mode} is our first condition (equals 1 when
#   `pane_mode` is "copy-mode").
# - #{e|-|:x,y} does our arithmetic, `history_size` - `scroll_position`.
# - #, is used to escape one of the commas inside the "consequent" format of
#   the ternary syntax (without this, the format breaks); funnily enough,
#   escaping is _not_ needing in the "else" format (and including it breaks the
#   format).
# - On next-3.5 and above, we can show `#{search_count}` and
#   `#{search_count_partial}`; this latter is used to show "+" after the count
#   in the event that the search times out without completing (I've never seen
#   this in practice).
# - #{e|>|:x,y} is used to check if `#{search_count}` is greater than zero.
#   and to check if #{search_count_partial}` is non-zero (in practice, it should
#   only ever be 0 or 1).
# - #{==:x,y} is used to check if `#{search_count}` is 1; this is used to decide
#   whether to render "1 result" (singular) or "N results" (plural).
# - #{&&:a,b} is used along with ternary syntax to indicate when our
#   `search_count` is greater than zero and `#{search_present}` is also true
#   (otherwise we'd show the count of the last successful match instead of the
#   current match).
#
# If we get a format that would allow us to know when a search is active, we
# could show a Neovim-style indicator in the middle:
#
#   #[fg=red,align=centre]"Pattern not found: #{pane_search_string}#[default]"
#
# We can't do that right now because `pane_search_string` is set even in the
# absence of a search, `search_match` is true only if the cursor is on a match,
# and although `search_present` will tell us if there is a match anywhere,
# that's not useful if we don't know that a search is active.
#
%hidden IS_COPY_MODE="#{==:#{pane_mode},copy-mode}"
%hidden COPY_MODE_MARKER="#[align=left#,fg=black#,bg=yellow]  -- COPY --  #[default]"
%hidden COPY_MODE_LEFT="$COPY_MODE_MARKER"
%hidden HAS_SEARCH_RESULT="#{&&:#{e|>|:#{search_count},0},#{search_present}}"
%hidden RESULT_OR_RESULTS="result#{?#{==:#{search_count},1},,s}"
%hidden RESULT_COUNT_IS_PARTIAL="#{e|>|:#{search_count_partial},0}"
%hidden SEARCH_RESULT_COUNT="(#{search_count}#{?$RESULT_COUNT_IS_PARTIAL,+,} $RESULT_OR_RESULTS)"
%hidden OFFSET_FROM_TOP="#{e|-|:#{history_size},#{scroll_position}}"
%hidden COPY_MODE_LOCATION="[$OFFSET_FROM_TOP/#{history_size}]"
%hidden COPY_MODE_CENTER="#[align=centre#,bg=black]#[default]"

%hidden COPY_MODE_RIGHT="#[align=right#,bg=yellow#,fg=black]  #{?$HAS_SEARCH_RESULT,$SEARCH_RESULT_COUNT  ,}$COPY_MODE_LOCATION  #[default]"

set-option -g pane-border-format "#{?$IS_COPY_MODE,$COPY_MODE_LEFT$COPY_MODE_CENTER$COPY_MODE_RIGHT,}"

# For other ways of getting into copy-mode, we _could_ redefine the bindings
# (passing in `-H` to suppress the top-right indicator), but instead we can use
# a hook to toggle it off every time we enter the mode; see:
#
# - https://github.com/wincent/wincent/issues/155
#

set-hook -g pane-mode-changed {
  if-shell -F '$IS_COPY_MODE' {
    send-keys -X toggle-position
  }
}

bind-key -T root MouseDrag1Pane if-shell -F "#{||:#{pane_in_mode},#{mouse_any_flag}}" {
  send-keys -M
} {
  copy-mode -M
}

bind-key -T root WheelUpPane if-shell -F "#{||:#{pane_in_mode},#{mouse_any_flag}}" {
  send-keys -M
} {
  copy-mode -e
}

# ----------------------
# Status Bar
# -----------------------
set -g status on

set -g status-interval 5
set -g status-justify left
set -g status-position top

# set color for status bar
set -g status-style bg=terminal,fg=terminal

setw -g window-status-format "#[bg=terminal]#{?window_activity_flag,#{?window_bell_flag,#[fg=brightred]▲,#[fg=colour243]⦁},#[fg=colour235]⦁}#[bg=terminal]"
setw -g window-status-current-format "#{?window_zoomed_flag,#[fg=yellow]  #W,#W}#[bg=terminal]"
setw -g window-status-activity-style bg=terminal,fg=colour243
setw -g window-status-bell-style bg=terminal,fg=brightred
setw -g window-status-current-style bg=terminal,fg=colour004

# show session name, window & pane number, date and time on left side of
# status bar
set -g status-left-length 70
set -g status-left "#[fg=colour237]#{?client_prefix,#[fg=colour012],#[fg=colour237]}#S #[fg=colour237] "

%hidden STATUS_PREFIX="#{?client_prefix,#[fg=colour012]#(echo $(tmux show-option -gqv prefix | tr \"[:lower:]\" \"[:upper:]\" | sed 's/C-/\^/')) #[fg=colour237]⦁ ,}"
%hidden STATUS_BATTERY="#(battery -tpGi -c ' ')#[fg=colour237] ⦁ "
%hidden STATUS_WIFI="#[fg=colour237]#(wifi)#[fg=colour237] ⦁ "
%hidden STATUS_WEATHER="#[fg=colour243]#(~/.config/tmux/scripts/tmux-weather)#[fg=colour237] ⦁ "
# for some reason that extra space at the end prevents the date from overlapping & makes it play nice with Nerd Fonts
%hidden STATUS_DATE_TIME="#[fg=colour237]CAI: #(TZ=':/usr/share/zoneinfo/Africa/Cairo' date +%%H:%%M) ⦁ #[fg=colour243]%A, %d %b %Y %H:%M#[fg=colour237] "
%hidden STATUS_GITHUB="#(~/.config/tmux/scripts/tmux-github-status)"
%hidden STATUS_NPM="#(~/.config/tmux/scripts/tmux-npm-status)"
%hidden STATUS_PRAYER_TIMES="#[fg=colour243]#(~/.config/tmux/scripts/get-prayer) #[fg=colour237]⦁ "

set -g status-right-length 300
set -g status-right "${STATUS_PREFIX}${STATUS_NPM}${STATUS_GITHUB}${STATUS_WEATHER}${STATUS_BATTERY}${STATUS_WIFI}${STATUS_PRAYER_TIMES}${STATUS_DATE_TIME}"

if-shell 'test "$(uname)" = "Darwin"' 'source -q ~/.tmux-macos.conf' 'source -q ~/.tmux-linux.conf'
if-shell 'test -f "$HOST_CONFIGS/tmux.conf"' 'source -q "$HOST_CONFIGS/tmux.conf"'
