#compdef xpanes tmux-xpanes

_xpanes () {
  # matches multiple hosts.
  if [[ "${words[*]}" =~ "--ssh( [^-][^ ]*)*$" ]] ; then
    __xpanes-ssh_hosts
  else
    local opts_omit="-h --help -V --version"
    # (<options which should not exist together>)-option[description]:name:(element1 element2 ...)
    _arguments "(: -)"{-h,--help}"[Display this help and exit.]" \
           "(: -)"{-V,--version}"[Output version information and exit.]" \
      "($opts_omit -c --ssh -e)-c[Set <command> to be executed in each pane. Default is \`echo {}\`.]:arg:" \
      "($opts_omit -d)"{-d,--desync}"[Make synchronize-panes option off on new window.]" \
      "($opts_omit -e -c -I --ssh)-e[Execute given arguments as is. Same as \`-c '{}'\`]" \
      "($opts_omit -I --ssh -e)-I[Replacing one or more occurrences of <repstr> in command provided by -c or -B. Default is \`{}\`.]:repstr:(@ % _REPLACE_ @@@)" \
      "($opts_omit -B)-B[Run <begin-command> before processing <command> in each pane. Multiple options are allowed.]:arg:" \
      "($opts_omit -C --cols -R --rows --bulk-cols -l -x)"{-C,--cols=}"[Number of columns of window layout.]:num:" \
      "($opts_omit -R --rows -C --cols --bulk-cols -l -x)"{-R,--rows=}"[Number of rows of window layout.]:num:" \
      "($opts_omit --bulk-cols -C --cols -R --rows -l -x)--bulk-cols=[Number of columns on multiple rows (i.e, \"2,2,2\" represents 2 cols x 3 rows).]:comma_num:" \
      "($opts_omit -l -C --cols -R --rows --bulk-cols)-l[Set the preset of window layout.]:layout:__xpanes-layout" \
      "($opts_omit -s -ss --ssh)-s[Speedy mode: Run command without opening an interactive shell.]" \
      "($opts_omit -ss -s)-ss[Speedy mode AND close a pane automatically at the same time as process exiting.]" \
      "($opts_omit -n)-n[Set the maximum number of <argument> taken for each pane.]:num:" \
      "($opts_omit -r)-r[Reuse the existing panes, or create then in the current active window.]" \
      "($opts_omit -S)-S[Specify a full alternative path to the server socket.]:filename:_files" \
      "($opts_omit -t)-t[Display each argument on the each pane's border as their title.]" \
      "($opts_omit -x --stay)-x[Create extra panes in the current active window.]" \
      "($opts_omit --log)--log=[Enable logging and store log files to <directory>.]:dirs:_dir_list" \
      "($opts_omit --log-format)--log-format=[Make name of log files follow <FORMAT>.]:_log_format:" \
      "($opts_omit --ssh -I -c -e -t -s)--ssh[Same as \`-t -s -c 'ssh -o StrictHostKeyChecking=no {}'\`.]:hosts:__xpanes-ssh_hosts" \
      "($opts_omit --stay)--stay[Do not switch to new window.]" \
      "($opts_omit --interval)--interval[Set interval between each pane creation and each command execution.]:num:" \
      "($opts_omit --debug)--debug[Print debug message.]"
  fi
}

_tmux-xpanes() {
  _xpanes "$@"
}

__xpanes-layout() {
  local -a args
  args=($args 'eh:even-horizontal')
  args=($args 'ev:even-vertical')
  args=($args 'mh:main-horizontal')
  args=($args 'mv:main-vertical')
  args=($args 't:tiled')
  _describe -t args 'args' args
}

# __xpanes-ssh_hosts function
# ==============================================================
# This function is modified version of _ssh_hosts function which is distributed with MIT-like license.
# (from: https://github.com/zsh-users/zsh/blob/aa8157b463c18489b378da322f46574bd9ab8dbb/Completion/Unix/Command/_ssh#L665)
# Here is the original copyright.
# ---
# The Z Shell is copyright (c) 1992-2017 Paul Falstad, Richard Coleman,
# Zoltán Hidvégi, Andrew Main, Peter Stephenson, Sven Wischnowsky, and
# others.  All rights reserved.  Individual authors, whether or not
# specifically named, retain copyright in all changes; in what follows, they
# are referred to as `the Zsh Development Group'.  This is for convenience
# only and this body has no legal status.  The Z shell is distributed under
# the following licence; any provisions made in individual files take
# precedence.
#
# Permission is hereby granted, without written agreement and without
# licence or royalty fees, to use, copy, modify, and distribute this
# software and to distribute modified versions of this software for any
# purpose, provided that the above copyright notice and the following
# two paragraphs appear in all copies of this software.
#
# In no event shall the Zsh Development Group be liable to any party for
# direct, indirect, special, incidental, or consequential damages arising out
# of the use of this software and its documentation, even if the Zsh
# Development Group have been advised of the possibility of such damage.
#
# The Zsh Development Group specifically disclaim any warranties, including,
# but not limited to, the implied warranties of merchantability and fitness
# for a particular purpose.  The software provided hereunder is on an "as is"
# basis, and the Zsh Development Group have no obligation to provide
# maintenance, support, updates, enhancements, or modifications.
# ---
__xpanes-ssh_hosts () {
  local -a config_hosts
  local config
  integer ind

  # If users-hosts matches, we shouldn't complete anything else.
  if [[ "$IPREFIX" == *@ ]]; then
    _combination -s '[:@]' my-accounts users-hosts "users=${IPREFIX/@}" hosts "$@" && return
  else
    _combination -s '[:@]' my-accounts users-hosts \
      ${opt_args[-l]:+"users=${opt_args[-l]:q}"} hosts "$@" && return
  fi
  if (( ind = ${words[(I)-F]} )); then
    config=${~words[ind+1]}
  else
    config="$HOME/.ssh/config"
  fi
  if [[ -r $config ]]; then
    local key hosts host
    while IFS=$'=\t ' read -r key hosts; do
      if [[ "$key" == (#i)host ]]; then
         for host in ${(z)hosts}; do
            case $host in
            (*[*?]*) ;;
            (*) config_hosts+=("$host") ;;
            esac
         done
      fi
    done < "$config"
    if (( ${#config_hosts} )); then
      _wanted hosts expl 'remote host name' \
        compadd -M 'm:{a-zA-Z}={A-Za-z} r:|.=* r:|=*' "$@" $config_hosts
    fi
  fi
}
# ==============================================================

# Local Variables:
# mode: Shell-Script
# sh-indentation: 2
# indent-tabs-mode: nil
# sh-basic-offset: 2
# End:
# vim: ft=zsh sw=2 ts=2 et
