#!/usr/bin/env sh
#                           │
#       ╭╮                  │
#       ││                  │
#    ╭──┤│╭┬──┬──┬──┬──╮    │
#    │╭╮││├┤╭╮│ ─┤│─┤ ─┤    │
#    │╭╮│╰┤│╭╮├─ ││─┼─ │    │
#    ╰╯╰┴─┴┴╯╰┴──┴──┴──╯    │
#          and functions    │
#                           │
#  curator: Lucas Larson    │
#                           │
# ──────────────────────────╯
#
# https://github.com/mathiasbynens/dotfiles/commit/cb8843b
alias ,='exec -l -- "${SHELL:-sh}"'       # unnecessary pre-reset run-command reload
alias ,='exec -- - "${SHELL:-sh}"'        # Zsh-only           (but this generates `zsh` instead of `-zsh`)
alias ,='exec "${SHELL:-sh}" -l'          # any POSIX shell
alias ,='exec -l -- "${SHELL:-sh}"'       # Zsh or Bash (but in Zsh this generates `zsh` instead of `-zsh`)
alias ,='exec -l - "${${SHELL##*/}:-sh}"' # Zsh-only using `-` precommand modifier to generate `-zsh` instead of `zsh` and the `-l` is not required
alias ,='exec - "${${SHELL##*/}:-sh}"'    # Zsh-only using `-` precommand modifier to generate `-zsh` instead of `zsh`
alias ,='exec "${SHELL:-sh}"'             # portable
alias ,='exec - "${SHELL##*/}"'           # Zsh-only using `-` precommand modifier to generate `-zsh` instead of `zsh`, but POSIX parameter expansion
aliases() {
  set -- "${DOTFILES-}"'/custom/aliases.sh'
  "${EDITOR:-vi}" -- "${1-}" &&
    command -v -- shfmt >/dev/null 2>&1 &&
    shfmt --indent 2 --language-dialect bash --simplify --write -- "${1-}"
  # shellcheck disable=SC1090
  . "${1-}"
  command -v -- sc >/dev/null 2>&1 &&
    sc -- "${1-}"
}

# ## Adobe Acrobat
# acrobat() {
#   test "${#}" -gt 0 ||
#     # EX_USAGE
#     return 64
#   for file in "${@}"; do
#     test -s "${file-}" &&
#       test ! -L "${file-}" &&
#       open -a "$(
#         (
#           # /Applications/*/*/* instead of
#           # /Applications/*/* because it’s possibly inside /Applications/Adobe Acrobat DC
#           find -- /Applications \
#             -path '/Applications/*/*/*' -prune -o \
#             -name 'Adobe Acrobat.app' \
#             -type d \
#             -exec ls -d -1 -t -- {} + 2>/dev/null \
#             &
#         ) |
#           sed \
#             -n \
#             -e '/1/ {' \
#             -e '  s/^\/Applications\///' \
#             -e '  s/\.app$//' \
#             -e '}' \
#             -e 'p'
#       )" -- "${file-}"
#   done
# }

awk_pretty() {
  command -v -- gawk >/dev/null 2>&1 ||
    # EX_UNAVAILABLE
    return 69
  test "${#}" -ne 0 ||
    # EX_USAGE
    return 64
  gawk \
    --no-optimize \
    --posix \
    --pretty-print=- \
    --use-lc-numeric \
    "${@}" |
    sed \
      -e ':a' \
      -e 'N' \
      -e '$! b a' \
      -e 's/\n{\n/ {\n/g' \
      -e 's/\t/  /g' \
      -e '/^$/ d' | {
    bat \
      --language=awk \
      --paging=never \
      --style=plain \
      --wrap=never \
      -- \
      - 2>/dev/null ||
      cat \
        -- \
        -
  }
}

base_to_base() {
  command -v -- bc >/dev/null 2>&1 ||
    # EX_UNAVAILABLE
    return 69
  test "${#}" -gt 0 &&
    test "${#}" -lt 4 ||
    # EX_USAGE
    return 64
  # https://stackoverflow.com/a/13280173
  printf -- 'ibase=%s; obase=%s; %s\n' "${2:-10}" "${3:-10}" "$(
    printf -- '%s\n' "${1-}" |
      LANG='C' LC_ALL='C' tr -- '[:lower:]' '[:upper:]' |
      sed -e 's/^0[BODX]//'
  )" |
    bc
}
hexadecimal_to_decimal() {
  base_to_base "${1-}" 16 A
}
alias \
  hex2dec='hexadecimal_to_decimal' \
  hex_to_decimal='hexadecimal_to_decimal'
decimal_to_hexadecimal() {
  base_to_base "${1-}" A 16
}
alias dec2hex='decimal_to_hexadecimal'
octal_to_decimal() {
  base_to_base "${1-}" 8 A
}
alias oct2dec='octal_to_decimal'
octal_to_hexadecimal() {
  base_to_base "${1-}" 8 16
}
decimal_to_octal() {
  base_to_base "${1-}" A 8
}
alias dec2oct='decimal_to_octal'
binary_to_decimal() {
  base_to_base "${1-}" 2 A
}
alias bin2dec='binary_to_decimal'
decimal_to_binary() {
  base_to_base "${1-}" A 2
}
alias dec2bin='decimal_to_binary'

basename_r() {
  test "${#}" -gt 0 ||
    # EX_USAGE
    return 64
  for file in "${@}"; do
    printf -- '%s\n' "${file##*/}"
  done
}

bash_pretty() {
  command -v -- bash >/dev/null 2>&1 ||
    # EX_UNAVAILABLE
    return 69
  test "${#}" -gt 0 ||
    # EX_USAGE
    return 64
  set \
    -o noclobber \
    -o noglob \
    -o nounset \
    -o verbose \
    -o xtrace

  # use this script to remove comments from shell scripts
  # and potentially find duplicate content

  for file in "${@}"; do

    # ensure it is a non-zero-length file
    test -s "${file-}" &&

      # ensure it is not a symlink
      test ! -L "${file-}" &&

      # if it does not already have the obvious yet unlikely `.bash` filename extension
      # test 'file-without-bash-extension' = 'file-without-bash-extension' &&
      test "${file-}" = "${file%.bash}" &&

      # if `bash --pretty-print` fails on the file, skip it
      # noting that `bash --pretty-print` prints to `stdout`
      # but since this part is a test, send both `stdout` and `stderr` to `/dev/null`
      bash --pretty-print -- "${file-}" >/dev/null 2>&1 &&
      {
        # add the shell directive then the `bash --pretty-print` content
        printf -- '#!/usr/bin/env sh\n\n' &&
          # add the shell directive then the `bash --pretty-print` content
          bash --pretty-print -- "${file-}"

        # save `$file`'s interpolated content into a file called `$file.bash`
      } >"${file-}"'.bash' &&
      # match the input file’s permissions without `test -x` or `command -v`
      find -- "${file-}" -perm -700 -exec chmod -- 755 "${file-}"'.bash' ';'
  done
  {
    set \
      +o noclobber \
      +o noglob \
      +o nounset \
      +o verbose \
      +o xtrace
  } 2>/dev/null
}
bash_pretty_overwrite() {
  LC_ALL='C' \
    find -- . \
    -path '*/.git' -prune -o \
    -path '*/node_modules' -prune -o \
    -name '*.bash' \
    -type f \
    -exec sh -C -e -f -u -x -c -- 'git ls-files --error-unmatch -- "${1-}" >/dev/null 2>&1 ||
  ! git rev-parse --is-inside-work-tree >/dev/null 2>&1 &&
  git mv --force --verbose -- "${1-}" "${1%.bash}"
' _ {} ';'
}

bitly() {
  test "${BITLY_TOKEN-}" != '' ||
    # EX_CONFIG
    return 78
  test "${#}" -gt 0 ||
    # EX_USAGE
    return 64
  for link in "${@}"; do
    curl \
      --data '{"bitlink_id":"bit.ly/'"${link-}"'"}' \
      --header 'Authorization: Bearer '"${BITLY_TOKEN-}" \
      --header 'Content-Type: application/json' \
      --show-error \
      --silent \
      --url 'https://api-ssl.bitly.com/v4/expand' |
      sed \
        -e '# remove everything but the last doublequoted string or long_url value' \
        -e '# and add a newline' \
        -e 's/.*"\(.*\)".*/\1\n/g'
  done
}

black_r() {
  command -v -- black >/dev/null 2>&1 ||
    # EX_UNAVAILABLE
    return 69
  # https://github.com/psf/black/blob/b1d0601016/src/black/const.py
  find -- . \
    '(' \
    -name '*.py' -o \
    -name '*.py3' -o \
    -name '*.pyi' -o \
    -name '*.ipynb' \
    ')' \
    -type f \
    -exec sh -c -- 'for file in "${@}"; do
  git ls-files --error-unmatch -- "${file-}" >/dev/null 2>&1 ||
    ! git rev-parse --is-inside-work-tree >/dev/null 2>&1 &&
    black --preview --verbose -- "${file-}"
done' _ {} +
}

## braces
braces() {
  test "${#}" -gt 0 ||
    # EX_USAGE
    return 64
  set \
    -o noglob \
    -o xtrace
  while test "${#}" -gt 0; do
    test -f "${1-}" &&
      rm -f -- "${TMPDIR:-${TEMP:-${TMP:-/tmp}}}"'/'"${1##*/}" &&
      cp -f -p -- "${1-}" "${TMPDIR:-${TEMP:-${TMP:-/tmp}}}"'/'"${1##*/}" &&
      # add braces to shell variables but do not even try with `awk` commands
      sed \
        -e '# do not apply to awk content' \
        -e '/awk /! {' \
        -e '# replace uncommented ＄var/＄var[@] with "＄{var-}"/"＄{var[@]-}"' \
        -e 's/^\([^#]*\)\$\([a-zA-Z0-9_][a-zA-Z0-9_]*\(\[[^]]\{1,\}\]\)\{0,1\}\)/\1\${\2-}/g' \
        -e '# replace dollar-# with "dollar-{#}"' \
        -e '# TO DELETE superseded by next line s/[[:space:]][[:space:]]*"\{0,1\}\(\$\)\#-*"\{0,1\}[[:space:]][[:space:]]*/ "\1{#}" /g' \
        -e 's/[[:space:]][[:space:]]*"\{0,1\}\(\$\)\#-*"\{0,1\}/ "\1{#}"/g' \
        -e '}' \
        "${TMPDIR:-${TEMP:-${TMP:-/tmp}}}"'/'"${1##*/}" \
        >"${1-}" &&
      rm -f -- "${TMPDIR:-${TEMP:-${TMP:-/tmp}}}"'/'"${1##*/}"
    shift 1
  done
  {
    set \
      +o noglob \
      +o xtrace
  } 2>/dev/null
}

# cargo
cargo_install() {
  # https://forge.rust-lang.org/infra/other-installation-methods.html#rustup
  set -- 'https://sh.rustup.rs' && {
    curl \
      --fail \
      --show-error \
      --silent \
      --url "${1-}" ||
      wget \
        --content-on-error \
        --hsts-file=/dev/null \
        --output-document=- \
        --quiet \
        -- \
        "${1-}"
  } |
    sh -s -- --no-modify-path
}
alias install_cargo='cargo_install'
cargo_list() {
  cargo install --list 2>/dev/null |
    sed \
      -e 's/[[:space:]].*//' \
      -e '/^$/ d'
}

# prefer `bat` without line numbers for easier copying
# this includes `command` otherwise
# `bat` appears unprepared to accept filenames as arguments
alias bat >/dev/null 2>&1 &&
  unalias -- bat
command -v -- bat >/dev/null 2>&1 &&
  alias \
    bat='bat --decorations=never --paging=never' \
    batsh='bat --language=sh' &&
  command -v -- _bat >/dev/null 2>&1 &&
  compdef -- batsh='bat' >/dev/null 2>&1

## cd
# this construction:
# - skips printing the new directory
# - coerces Zsh into creating an alias named `-` without
#   tripping up BusyBox `alias`, which does not support `-`
alias 1='CDPATH='\''.'\'' cd "${OLDPWD:--}" >/dev/null 2>&1' -='CDPATH='\''.'\'' cd "${OLDPWD:--}" >/dev/null 2>&1'
alias \
  2='CDPATH='\''.'\'' cd -2 >/dev/null 2>&1' \
  3='CDPATH='\''.'\'' cd -3 >/dev/null 2>&1' \
  4='CDPATH='\''.'\'' cd -4 >/dev/null 2>&1' \
  5='CDPATH='\''.'\'' cd -5 >/dev/null 2>&1' \
  6='CDPATH='\''.'\'' cd -6 >/dev/null 2>&1' \
  7='CDPATH='\''.'\'' cd -7 >/dev/null 2>&1' \
  8='CDPATH='\''.'\'' cd -8 >/dev/null 2>&1' \
  9='CDPATH='\''.'\'' cd -9 >/dev/null 2>&1' \
  ...='CDPATH='\''.'\'' cd ./../.. >/dev/null 2>&1' \
  ....='CDPATH='\''.'\'' cd ./../../.. >/dev/null 2>&1' \
  .....='CDPATH='\''.'\'' cd ./../../../.. >/dev/null 2>&1' \
  ......='CDPATH='\''.'\'' cd ./../../../../.. >/dev/null 2>&1' \
  .......='CDPATH='\''.'\'' cd ./../../../../../.. >/dev/null 2>&1' \
  ........='CDPATH='\''.'\'' cd ./../../../../../../.. >/dev/null 2>&1' \
  .........='CDPATH='\''.'\'' cd ./../../../../../../../.. >/dev/null 2>&1'

cdp() {
  set -- "$(pwd -P)" &&
    if test "${PWD%/}" != "${1-}"; then
      printf -- 'moving from \342\200\230' >&2 &&
        printf -- '%s' "${PWD%/}" &&
        printf -- '\342\200\231' >&2 &&
        printf -- '\n' &&
        CDPATH='.' cd "${1-}" >/dev/null 2>&1 || {
        printf -- 'unable to perform this operation\n' >&2
        return 1
      } &&
        printf -- '       into \342\200\230' >&2 &&
        printf -- '%s' "${1-}" &&
        printf -- '\342\200\231' >&2 &&
        printf -- '\n'
    else
      printf -- 'already in unaliased directory ' >&2 &&
        printf -- '\342\200\230' >&2 &&
        printf -- '%s' "${PWD%/}" &&
        printf -- '\342\200\231' >&2 &&
        printf -- '\n'
      return 1
    fi
}

cdx_to_csv() {
  # https://web.archive.org/cdx/search/cdx?url=popkorn.it/*&output=json
  # https://claude.ai/chat/13791398-d210-48ba-904d-c529be5272c0
  command -v -- jq >/dev/null 2>&1 ||
    # EX_UNAVAILABLE
    return 69
  test "${#}" -gt 0 ||
    # EX_USAGE
    return 64
  set \
    -o noclobber \
    -o verbose \
    -o xtrace
  for file in "${@}"; do
    test -s "${file-}" &&
      test ! -L "${file-}" &&
      case "${file-}" in
      *.[Jj][Ss][Oo][Nn])
        jq --raw-output '(.[0] | @csv), (.[1:] [] | @csv)' "${file-}" >"${file%.json}"'.csv'
        ;;
      *) ;;
      esac
  done
  {
    set \
      +o noclobber \
      +o verbose \
      +o xtrace
  } 2>/dev/null
}

changelog_find_newest() {
  pwd="$(
    git rev-parse --path-format=relative --show-toplevel | sed -e '1 q' ||
      git rev-parse --show-toplevel ||
      find -- . -name '.git' -type d -exec dirname -- {} ';'
  )" 2>/dev/null ||
    return "${?:-1}"
  LC_ALL='C' find -- "${pwd%/}" \
    -path "${pwd%/}"'/[Cc][Hh][Aa][Nn][Gg][Ee]*[Ll][Oo][Gg]*.[Mm]*[Dd]*' \
    -type f \
    -exec sh -c -- 'git --no-pager log --max-count=1 --format='\''%at '\''"${1-}"' _ {} ';' |
    LANG='C' LC_ALL='C' sort -n -r |
    sed \
      -e 's/.*\///g' \
      -e 'q'
  unset pwd >/dev/null 2>&1 || pwd=''
}

checkbashisms_r() {
  find_shell_scripts | while IFS='' read -r -- file; do
    checkbashisms --extra --force --lint --newline --posix "${file-}" 2>&1 |
      sed \
        -e '# skip warnings about commands prepended by "command", which POSIX does allow' \
        -e '# https://pubs.opengroup.org/onlinepubs/9699919799/utilities/command.html#tag_20_22_03' \
        -e '/warning.*command.*with option other than -p, -v or -V/ d'
  done
}

clang_r() {
  command -v -- "${CC:-c99}" >/dev/null 2>&1 ||
    # EX_UNAVAILABLE
    return 69
  test "${#}" -gt 0 ||
    # EX_USAGE
    return 64
  # https://news.ycombinator.com/item?id=35758898
  "${CC:-c99}" \
    -g3 \
    -Wall \
    -Wextra \
    -Wconversion \
    -Wdouble-promotion \
    -Wno-unused-parameter \
    -Wno-unused-function \
    -Wno-sign-conversion \
    -fsanitize=undefined \
    -fsanitize-trap \
    -fsanitize=integer \
    "${@}"
}

clang_format() {

  clang-format --version >/dev/null 2>&1 ||
    # EX_UNAVAILABLE
    return 69

  # permit arguments in any order
  # https://salsa.debian.org/debian/debianutils/blob/c2a1c435ef/savelog
  while getopts -- 'i:s:w:' opt; do
    case "${opt-}" in
    i)
      export IndentWidth="${OPTARG-}"
      ;;
    s)
      export SpacesBeforeTrailingComments="${OPTARG-}"
      ;;
    w)
      export ColumnLimit="${OPTARG-}"
      ;;
    *)
      printf -- 'only \140-i <indent width>\140, \140-s <spaces before trailing comments>\140, and \140-w <number of columns>\140 are supported\n' >&2
      return 1
      ;;
    esac
  done

  # permit `find` to have a narrower scope by parsing the rest of the arguments
  shift "$((OPTIND - 1))"

  # eligible filename extensions:
  # https://github.com/llvm/llvm-project/blob/17c6c8da56/clang/lib/Driver/Types.cpp#L311-L377
  # https://github.com/llvm/llvm-project/blob/17c6c8da56/clang/lib/Frontend/FrontendOptions.cpp#L17-L38
  # https://github.com/llvm/llvm-project/blob/f22a8d1822/clang/tools/clang-format-vs/ClangFormat/ClangFormatPackage.cs#L41-L42
  # https://github.com/llvm/llvm-project/blob/db6ba82acc/clang/tools/clang-format/git-clang-format#L88-L128
  # https://github.com/llvm/llvm-project/blob/b17f1fd676/clang/tools/clang-format/clang-format-diff.py#L65-L66

  find -- . \
    -path '*/.git' -prune -o \
    -path '*/.rbenv' -prune -o \
    -path '*/.venv' -prune -o \
    -path '*/.well-known' -prune -o \
    -path '*/__pycache__' -prune -o \
    -path '*/Library' -prune -o \
    -path '*/node_modules' -prune -o \
    -path '*/t' -prune -o \
    -path '*/Test*' -prune -o \
    -path '*/test*' -prune -o \
    -path '*/tst*' -prune -o \
    -path '*copilot*' -prune -o \
    -path '*dummy*' -prune -o \
    -path '*vscode*' -prune -o \
    '(' \
    -name '*.[Aa][Dd][Aa]' -o \
    -name '*.[Aa][Dd][Bb]' -o \
    -name '*.[Aa][Dd][Ss]' -o \
    -name '*.[Aa][Ss][Cc][Ii][Ii][Pp][Bb]' -o \
    -name '*.[Aa][Ss][Mm]' -o \
    -name '*.[Aa][Ss][Tt]' -o \
    -name '*.[Bb][Cc]' -o \
    -name '*.[Cc]' -o \
    -name '*.[Cc]++' -o \
    -name '*.[Cc]++[Mm]' -o \
    -name '*.[Cc].[Ii][Nn]' -o \
    -name '*.[Cc][Aa][Kk][Ee]' -o \
    -name '*.[Cc][Aa][Tt][Ss]' -o \
    -name '*.[Cc][Cc]' -o \
    -name '*.[Cc][Cc].[Ii][Nn]' -o \
    -name '*.[Cc][Cc][Mm]' -o \
    -name '*.[Cc][Ii][Rr]' -o \
    -name '*.[Cc][Jj][Ss]' -o \
    -name '*.[Cc][Ll]' -o \
    -name '*.[Cc][Ll][Cc][Pp][Pp]' -o \
    -name '*.[Cc][Ll][Ii]' -o \
    -name '*.[Cc][Ll][Ii][Ii]' -o \
    -name '*.[Cc][Pp]' -o \
    -name '*.[Cc][Pp][Pp]' -o \
    -name '*.[Cc][Pp][Pp].[Ii][Nn]' -o \
    -name '*.[Cc][Pp][Pp][Mm]' -o \
    -name '*.[Cc][Ss]' -o \
    -name '*.[Cc][Ss][Xx]' -o \
    -name '*.[Cc][Tt][Ss]' -o \
    -name '*.[Cc][Uu]' -o \
    -name '*.[Cc][Uu][Hh]' -o \
    -name '*.[Cc][Uu][Ii]' -o \
    -name '*.[Cc][Xx][Xx]' -o \
    -name '*.[Cc][Xx][Xx].[Ii][Nn]' -o \
    -name '*.[Cc][Xx][Xx][Mm]' -o \
    -name '*.[Ee][Cc]' -o \
    -name '*.[Ee][Cc][Pp]' -o \
    -name '*.[Ee][Dd][Cc]' -o \
    -name '*.[Ff]' -o \
    -name '*.[Ff]03' -o \
    -name '*.[Ff]08' -o \
    -name '*.[Ff]77' -o \
    -name '*.[Ff]90' -o \
    -name '*.[Ff]95' -o \
    -name '*.[Ff][Oo][Rr]' -o \
    -name '*.[Ff][Pp][Pp]' -o \
    -name '*.[Gg][Cc][Hh]' -o \
    -name '*.[Gg][Mm][Ll]' -o \
    -name '*.[Hh]' -o \
    -name '*.[Hh]++' -o \
    -name '*.[Hh].[Ii][Nn]' -o \
    -name '*.[Hh][Hh]' -o \
    -name '*.[Hh][Hh].[Ii][Nn]' -o \
    -name '*.[Hh][Ii][Pp]' -o \
    -name '*.[Hh][Ii][Pp][Ii]' -o \
    -name '*.[Hh][Ll][Ss][Ll]' -o \
    -name '*.[Hh][Pp]' -o \
    -name '*.[Hh][Pp][Pp]' -o \
    -name '*.[Hh][Pp][Pp].[Ii][Nn]' -o \
    -name '*.[Hh][Xx][Xx]' -o \
    -name '*.[Hh][Xx][Xx].[Ii][Nn]' -o \
    -name '*.[Ii]' -o \
    -name '*.[Ii][Dd][Cc]' -o \
    -name '*.[Ii][Ff][Ss]' -o \
    -name '*.[Ii][Ii]' -o \
    -name '*.[Ii][Ii][Hh]' -o \
    -name '*.[Ii][Ii][Mm]' -o \
    -name '*.[Ii][Nn][Cc]' -o \
    -name '*.[Ii][Nn][Ll]' -o \
    -name '*.[Ii][Nn][Oo]' -o \
    -name '*.[Ii][Pp][Pp]' -o \
    -name '*.[Ii][Pp][Yy][Nn][Bb]' -o \
    -name '*.[Ii][Xx][Xx]' -o \
    -name '*.[Jj][Aa][Vv]' -o \
    -name '*.[Jj][Aa][Vv][Aa]' -o \
    -name '*.[Jj][Ss][Hh]' -o \
    -name '*.[Ll][Ii][Bb]' -o \
    -name '*.[Ll][Ii][Nn][Qq]' -o \
    -name '*.[Ll][Ll]' -o \
    -name '*.[Mm]' -o \
    -name '*.[Mm][Ee][Tt][Aa][Ll]' -o \
    -name '*.[Mm][Ii]' -o \
    -name '*.[Mm][Ii][Ii]' -o \
    -name '*.[Mm][Jj][Ss]' -o \
    -name '*.[Mm][Mm]' -o \
    -name '*.[Mm][Tt][Ss]' -o \
    -name '*.[Nn][Uu][Tt]' -o \
    -name '*.[Oo]' -o \
    -name '*.[Oo][Bb][Jj]' -o \
    -name '*.[Pp][Bb].[Tt][Xx][Tt]' -o \
    -name '*.[Pp][Cc][Cc]' -o \
    -name '*.[Pp][Cc][Hh]' -o \
    -name '*.[Pp][Cc][Mm]' -o \
    -name '*.[Pp][Ff][Oo]' -o \
    -name '*.[Pp][Gg][Cc]' -o \
    -name '*.[Pp][Rr][Oo][Tt][Oo]' -o \
    -name '*.[Pp][Rr][Oo][Tt][Oo][Dd][Ee][Vv][Ee][Ll]' -o \
    -name '*.[Rr][Ee]' -o \
    -name '*.[Ss]' -o \
    -name '*.[Ss][Vv]' -o \
    -name '*.[Ss][Vv][Hh]' -o \
    -name '*.[Tt][Cc][Cc]' -o \
    -name '*.[Tt][Dd]' -o \
    -name '*.[Tt][Ee][Xx][Tt][Pp][Bb]' -o \
    -name '*.[Tt][Ee][Xx][Tt][Pp][Rr][Oo][Tt][Oo]' -o \
    -name '*.[Tt][Ll][Hh]' -o \
    -name '*.[Tt][Ll][Ii]' -o \
    -name '*.[Tt][Pp][Pp]' -o \
    -name '*.[Tt][Ss]' -o \
    -name '*.[Tt][Ss][Xx]' -o \
    -name '*.[Tt][Xx][Tt][Pp][Bb]' -o \
    -name '*.[Tt][Xx][Xx]' -o \
    -name '*.[Vv]' -o \
    -name '*.[Vv][Hh]' -o \
    -name '*.[Xx][Bb][Mm]' -o \
    -name '*.[Xx][Pp][Mm]' \
    ')' \
    -type f \
    -exec sh -c -- 'for file in "${@}"; do ! grep -e '\''^#!.*sh'\'' -e '\''moderni.*sh'\'' -- "${file-}" >/dev/null 2>&1 && git ls-files --error-unmatch -- "${file-}" >/dev/null 2>&1 || ! git rev-parse --is-inside-work-tree >/dev/null 2>&1 && clang-format -i --style "{ColumnLimit: ${ColumnLimit:-79}, IndentWidth: ${IndentWidth:-2}, SpacesBeforeTrailingComments: ${SpacesBeforeTrailingComments:-2}}" --verbose -- "${file-}"; done' _ {} + 2>&1 |
    sed \
      -e 's/ \[1\/1\]//' >&2
  unset ColumnLimit >/dev/null 2>&1 || ColumnLimit=''
  unset IndentWidth >/dev/null 2>&1 || IndentWidth=''
  unset SpacesBeforeTrailingComments >/dev/null 2>&1 || SpacesBeforeTrailingComments=''
}
alias clang_format_r='clang_format -i 2 -s 2 -w "$(getconf -- UINT_MAX)"'

cleanup() {
  # this function is POSIX in an obnoxiously pedantic way and must never be used
  set -o xtrace

  if test -d "${HOME%/}"'/.Trash'; then
    target="${HOME%/}"'/.Trash'
  elif mkdir -p -- "${XDG_DATA_HOME:-${HOME%/}/.local/share}"'/Trash' 2>/dev/null; then
    target="${XDG_DATA_HOME:-${HOME%/}/.local/share}"'/Trash'
  elif mkdir -p -- "${TMPDIR:-${TEMP:-${TMP:-/tmp}}}"'/.Trash' 2>/dev/null; then
    target="${TMPDIR:-${TEMP:-${TMP:-/tmp}}}"'/.Trash'
  else
    # EX_CANTCREAT
    return 73
  fi
  export target

  # refuse to run from `/`
  test "$(pwd -P)" = '/' ||
    # or from `$HOME`
    test "$(pwd -P)" = "${HOME%/}" ||
    # or from any titlecase-named directory just below `$HOME`
    # such the closed set of macOS standard directories:
    # `Applications`, `Desktop`, `Documents`, `Downloads`, `Library`, `Movies`, `Music`, `Pictures`, `Public`, and `Sites`
    # https://web.archive.org/web/0id_/developer.apple.com/library/mac/documentation/FileManagement/Conceptual/FileSystemProgrammingGUide/FileSystemOverview/FileSystemOverview.html#//apple_ref/doc/uid/TP40010672-CH2-SW9
    test "${PWD%/*}" = "${HOME%/}" &&
    case "$(
      pwd -P |
        sed -e 's/.*\/[[:space:]]*//'
    )" in
    [[:upper:]]*)
      printf -- '\n\n' >&2
      printf -- '\342\233\224\357\270\217 aborting: refusing to run from a macOS standard directory\n' >&2
      printf -- '\n\n' >&2
      set +o verbose
      # EX_NOPERM
      return 77
      ;;
    *)
      # permit running from non-titlecase-named directories in `$HOME`
      ;;
    esac

  set -o xtrace
  now="$(LANG='C' LC_ALL='C' date -- '+%Y%m%d%H%M%S')" &&
    export now

  # delete thumbnail cache files
  command -v -- dss >/dev/null 2>&1 &&
    dss

  # delete crufty Zsh files
  # if `$ZSH_COMPDUMP` always generates a crufty file then skip, but
  # if it’s not set then still perform the check
  # https://stackoverflow.com/a/8811800
  if test "${ZSH_COMPDUMP-}" = '' || {
    test ! "${ZSH_COMPDUMP-}" != "${ZSH_COMPDUMP#*'zcompdump-'}" &&
      test ! "${ZSH_COMPDUMP-}" != "${ZSH_COMPDUMP#*'zcompdump.'}"
  }; then
    # the first prune should mean that the Library line is unnecessary, but that is not the case ¯\_(ツ)_/¯
    # so it appears that all find commands should prune at least both `*/.git` and `*/Library`
    while test "$(
      find -- "${ZDOTDIR:-${HOME%/}}" \
        -path '*/.git' -prune -o \
        -path '*/Library' -prune -o \
        -path '*/node_modules' -prune -o \
        -path "${ZDOTDIR:-${HOME%/}}"'/*/*' -prune -o \
        -name '.zcompdump' -prune -o \
        -name '.zcompdump*' \
        -type f \
        -print
    )" != ''; do
      find -- "${ZDOTDIR:-${HOME%/}}" \
        -path '*/.git' -prune -o \
        -path '*/Library' -prune -o \
        -path '*/node_modules' -prune -o \
        -path "${ZDOTDIR:-${HOME%/}}"'/*/*' -prune -o \
        -name '.zcompdump' -prune -o \
        -name '.zcompdump*' \
        -type f \
        -exec sh -c -- 'rm -f -- "${1-}"' _ {} ';'
    done
  fi

  # delete empty files except
  # those with specific names
  find -- . \
    -path '*/.git' -prune -o \
    -path '*/.rbenv' -prune -o \
    -path '*/.venv' -prune -o \
    -path '*/.well-known' -prune -o \
    -path '*/__pycache__' -prune -o \
    -path '*/Library' -prune -o \
    -path '*/node_modules' -prune -o \
    -path '*/t' -prune -o \
    -path '*/Test*' -prune -o \
    -path '*/test*' -prune -o \
    -path '*/themes' -prune -o \
    -path '*/tst*' -prune -o \
    -path '*/venv' -prune -o \
    -path '*copilot*' -prune -o \
    -path '*dummy*' -prune -o \
    -path '*invalid*' -prune -o \
    -path '*vscode*' -prune -o \
    ! -name "$(printf -- 'Icon\015\012')" \
    ! -name '*.plugin.*sh' \
    ! -name '*Empty*' \
    ! -name '*empty*' \
    ! -name '*ignore' \
    ! -name '*journal' \
    ! -name '*lck' \
    ! -name '*LOCK' \
    ! -name '*lock' \
    ! -name '*lockfile' \
    ! -name '*rc' \
    ! -name '. ' \
    ! -name '.. ' \
    ! -name '.dirstamp' \
    ! -name '.do_not_remove' \
    ! -name '.gitkeep' \
    ! -name '.hushlogin' \
    ! -name '.keep' \
    ! -name '.keep_me' \
    ! -name '.keepme' \
    ! -name '.nojekyll' \
    ! -name '.sudo_as_admin_successful' \
    ! -name '.watchmanconfig' \
    ! -name '__init__.py' \
    ! -name 'favicon.*' \
    ! -name 'README*' \
    -size 0 \
    -type f \
    -exec sh -C -f -u -x -c -- 'test "$(git -C "${1%/*}" rev-parse --show-superproject-working-tree)" = '\'''\'' ||
  git ls-files --error-unmatch -- "${1-}" >/dev/null 2>&1 ||
  ! git rev-parse --is-inside-work-tree >/dev/null 2>&1 &&
  mkdir -p -- "${target%/}/${1%/*}_${now-}" &&
  mv -v -- "${1-}" "${target%/}/${1%/*}_${now-}/${1##*/}"
' _ {} ';'

  # delete empty directories
  # but skip certain directories
  while LC_ALL='C' test "$(
    LC_ALL='C' find -- . \
      -path '*/.git' -prune -o \
      -path '*/Library' -prune -o \
      -path '*/node_modules' -prune -o \
      -path './*' \
      -type d \
      -exec sh -c -- 'for directory in "${@}"; do test "$(find -- "${directory-}" -path "${directory-}"'\''/*'\'' -print)" = '\'''\'' && printf -- '\''%s\n'\'' "${directory-}"; done' _ {} +
  )" != ''; do
    LC_ALL='C' find -- . \
      -path '*/.git' -prune -o \
      -path '*/Library' -prune -o \
      -path '*/node_modules' -prune -o \
      -path './*' \
      -type d \
      -exec rmdir -p -- {} + >/dev/null 2>&1 ||
      true
  done

  # swap each tab for two spaces each in gitconfig files
  command -v -- ed >/dev/null 2>&1 &&
    (
      set -o noglob &&
        {
          find -- \
            "${XDG_CONFIG_HOME-}"'/git/config' \
            "${HOME%/}"'/.config/git/config' \
            "${DOTFILES-}"'/.config/git/config' \
            "${HOME%/}"'/.gitconfig' \
            "${DOTFILES-}"'/.gitconfig' \
            "${GIT_DIR:-./.git}"'/config' \
            "${GIT_DIR:-./.git}"'/config.worktree' \
            ! -size 0 \
            -type f \
            -print || true
        } 2>/dev/null | while IFS='' read -r -- file; do
          ed -s -- "${file-}" <<EOF
1,\$ s/	/  /g
w
q
EOF
        done |
        # suppress `ed` question mark-only lines
        sed -e '/^?$/ d'
    )

  # remove Git sample hooks and Dropbox pollution from `.git/` directories
  find -- . \
    -path '*/.git/*' \
    '(' \
    -name '._*' -o \
    -name '* conflicted copy *'because_you_probs_do_want_these_instead_of_Dropbox -o \
    -path '*/hooks/*.sample' \
    ')' \
    -type f \
    -print \
    -delete
  find -- . \
    -path '*/.git/*' \
    -name 'description' \
    -type f \
    '(' \
    -size '73c' -o \
    -size '88c' \
    ')' \
    -exec sh -x -c -- 'case "$(cksum -- "${1-}" | sed -e '\''s/ 73 .*//'\'' -e '\''s/ 88 .*//'\'' )" in 1558055404|76865375) printf -- '\''%s\n'\'' "${1-}" && rm -- "${1-}" ;; *) ;; esac' _ {} ';'
  find -- . \
    -path '*/.git/info/*' \
    -name 'exclude' \
    -type f \
    -size '240c' \
    -exec sh -x -c -- 'test "$(cksum -- "${1-}" | sed -e '\''s/ 240 .*//'\'')" -eq 684386549 && printf -- '\''%s\n'\'' "${1-}" && rm -- "${1-}"' _ {} ';'
  find -- . \
    -path '*/.git/*' \
    -path '*.gitstatus.*' \
    -type d \
    -exec rmdir -- {} + >/dev/null 2>&1 ||
    true

  {
    set +o xtrace
  } 2>/dev/null
  unset file >/dev/null 2>&1 || file=''
  unset now >/dev/null 2>&1 || now=''
  unset target >/dev/null 2>&1 || target=''
}

# codesign
codesign_r() {
  command -v -- xcrun >/dev/null 2>&1 ||
    # EX_UNAVAILABLE
    return 69
  test "${#}" -gt 0 ||
    # EX_USAGE
    return 64
  xcrun --run -- codesign \
    --deep \
    --force \
    --options runtime \
    --timestamp \
    --verbose \
    --sign "$(
      xcrun --run -- security \
        find-identity \
        -p codesigning \
        -v |
        sed \
          -e 's/.*\([[:xdigit:]]\{40\}\).*/\1/' \
          -e 'q'
    )" -- "${@}"
}

cpplint_filename_extensions() {
  # cpplint has had 12 valid filename extensions
  # since 2018-05-07 until at least 2026
  # https://github.com/cpplint/cpplint/commit/3d8f6f876d
  printf -- 'c c++ cc cpp cu cuh cxx h h++ hh hpp hxx\n'
}
cpplint_r() {
  PS4=' ' find -- . \
    -path '*/.git' -prune -o \
    -path '*/.rbenv' -prune -o \
    -path '*/.venv' -prune -o \
    -path '*/.well-known' -prune -o \
    -path '*/__pycache__' -prune -o \
    -path '*/Library' -prune -o \
    -path '*/node_modules' -prune -o \
    -path '*/t' -prune -o \
    -path '*/Test*' -prune -o \
    -path '*/test*' -prune -o \
    -path '*/tst*' -prune -o \
    -path '*copilot*' -prune -o \
    -path '*dummy*' -prune -o \
    -path '*vscode*' -prune -o \
    '(' \
    -name '*.cpp' -o \
    -name '*.[Aa][Dd][Aa]' -o \
    -name '*.[Aa][Dd][Bb]' -o \
    -name '*.[Aa][Dd][Ss]' -o \
    -name '*.[Aa][Ss][Mm]' -o \
    -name '*.[Aa][Ss][Tt]' -o \
    -name '*.[Bb][Cc]' -o \
    -name '*.[Cc]' -o \
    -name '*.[Cc].[Ii][Nn]' -o \
    -name '*.[Cc][Aa][Kk][Ee]' -o \
    -name '*.[Cc][Aa][Tt][Ss]' -o \
    -name '*.[Cc][Cc]' -o \
    -name '*.[Cc][Cc].[Ii][Nn]' -o \
    -name '*.[Cc][Cc][Mm]' -o \
    -name '*.[Cc][Ll]' -o \
    -name '*.[Cc][Ll][Cc][Pp][Pp]' -o \
    -name '*.[Cc][Pp]' -o \
    -name '*.[Cc][Pp][Pp]' -o \
    -name '*.[Cc][Pp][Pp].[Ii][Nn]' -o \
    -name '*.[Cc][Pp][Pp][Mm]' -o \
    -name '*.[Cc][Ss]' -o \
    -name '*.[Cc][Ss][Xx]' -o \
    -name '*.[Cc][Tt][Ss]' -o \
    -name '*.[Cc][Uu]' -o \
    -name '*.[Cc][Uu][Hh]' -o \
    -name '*.[Cc][Uu][Ii]' -o \
    -name '*.[Cc][Xx][Xx]' -o \
    -name '*.[Cc][Xx][Xx].[Ii][Nn]' -o \
    -name '*.[Cc][Xx][Xx][Mm]' -o \
    -name '*.[Cc]++' -o \
    -name '*.[Cc]++[Mm]' -o \
    -name '*.[Ee][Cc]' -o \
    -name '*.[Ee][Cc][Pp]' -o \
    -name '*.[Ee][Dd][Cc]' -o \
    -name '*.[Ff]' -o \
    -name '*.[Ff][Oo][Rr]' -o \
    -name '*.[Ff][Pp][Pp]' -o \
    -name '*.[Ff]03' -o \
    -name '*.[Ff]08' -o \
    -name '*.[Ff]77' -o \
    -name '*.[Ff]90' -o \
    -name '*.[Ff]95' -o \
    -name '*.[Gg][Cc][Hh]' -o \
    -name '*.[Gg][Mm][Ll]' -o \
    -name '*.[Hh]' -o \
    -name '*.[Hh].[Ii][Nn]' -o \
    -name '*.[Hh][Hh]' -o \
    -name '*.[Hh][Hh].[Ii][Nn]' -o \
    -name '*.[Hh][Ii][Pp]' -o \
    -name '*.[Hh][Ll][Ss][Ll]' -o \
    -name '*.[Hh][Pp]' -o \
    -name '*.[Hh][Pp][Pp]' -o \
    -name '*.[Hh][Pp][Pp].[Ii][Nn]' -o \
    -name '*.[Hh][Xx][Xx]' -o \
    -name '*.[Hh][Xx][Xx].[Ii][Nn]' -o \
    -name '*.[Hh]++' -o \
    -name '*.[Ii]' -o \
    -name '*.[Ii][Dd][Cc]' -o \
    -name '*.[Ii][Ff][Ss]' -o \
    -name '*.[Ii][Ii]' -o \
    -name '*.[Ii][Ii][Hh]' -o \
    -name '*.[Ii][Ii][Mm]' -o \
    -name '*.[Ii][Nn][Cc]' -o \
    -name '*.[Ii][Nn][Ll]' -o \
    -name '*.[Ii][Nn][Oo]' -o \
    -name '*.[Ii][Pp][Pp]' -o \
    -name '*.[Ii][Xx][Xx]' -o \
    -name '*.[Jj][Aa][Vv]' -o \
    -name '*.[Jj][Aa][Vv][Aa]' -o \
    -name '*.[Jj][Ss][Hh]' -o \
    -name '*.[Ll][Ii][Bb]' -o \
    -name '*.[Ll][Ii][Nn][Qq]' -o \
    -name '*.[Ll][Ll]' -o \
    -name '*.[Mm]' -o \
    -name '*.[Mm][Ee][Tt][Aa][Ll]' -o \
    -name '*.[Mm][Ii]' -o \
    -name '*.[Mm][Ii][Ii]' -o \
    -name '*.[Mm][Mm]' -o \
    -name '*.[Mm][Tt][Ss]' -o \
    -name '*.[Nn][Uu][Tt]' -o \
    -name '*.[Pp][Cc][Cc]' -o \
    -name '*.[Pp][Cc][Hh]' -o \
    -name '*.[Pp][Cc][Mm]' -o \
    -name '*.[Pp][Ff][Oo]' -o \
    -name '*.[Pp][Gg][Cc]' -o \
    -name '*.[Pp][Rr][Oo][Tt][Oo][Dd][Ee][Vv][Ee][Ll]' -o \
    -name '*.[Rr][Ee]' -o \
    -name '*.[Ss]' -o \
    -name '*.[Tt][Cc][Cc]' -o \
    -name '*.[Tt][Dd]' -o \
    -name '*.[Tt][Ll][Hh]' -o \
    -name '*.[Tt][Ll][Ii]' -o \
    -name '*.[Tt][Pp][Pp]' -o \
    -name '*.[Tt][Ss]' -o \
    -name '*.[Tt][Ss][Xx]' -o \
    -name '*.[Tt][Xx][Xx]' -o \
    -name '*.[Xx][Bb][Mm]' -o \
    -name '*.[Xx][Pp][Mm]' \
    ')' \
    -type f \
    -exec sh -x -c -- 'git ls-files --error-unmatch -- "${1-}" >/dev/null 2>&1 ||
  ! git rev-parse --is-inside-work-tree >/dev/null 2>&1 &&
  cpplint --counting=detailed --verbose=0 --filter=-legal/copyright -- "${1-}"
' _ {} ';' 2>&1
}

# copy repository boilerplate files
cy() {
  set \
    -o verbose \
    -o xtrace
  test -d "${DOTFILES-}" ||
    test -d "${TEMPLATE-}" ||
    test -d "${_GITHUB-}" ||
    # EX_CONFIG
    return 78

  target="$(
    git rev-parse --path-format=relative --show-toplevel 2>/dev/null | sed -e '1 q' ||
      git rev-parse --show-toplevel 2>/dev/null ||
      pwd -L
  )" ||
    return 1

  for file in \
    "${DOTFILES-}"'/.github' \
    "${TEMPLATE-}"'/.github' \
    "${_GITHUB-}"'/.github' \
    "${TEMPLATE-}"'/.gitlab-ci.yml' \
    "${TEMPLATE-}"'/.imgbotconfig' \
    "${TEMPLATE-}"'/.whitesource' \
    "${TEMPLATE-}"'/citation.cff' \
    "${TEMPLATE-}"'/renovate.json'; do
    case "${file-}" in
    */funding.yml | */code_of_conduct.md | */this_does_dot_work_because_we_are_requesting_a_directory_then_requesting_this_file)
      shift 1
      ;;
    *)
      test -r "${file-}" &&
        # -L to follow symbolic links
        # -R to copy recursively (not `-r`)
        cp -L -R -p -- "${file-}" "${target-}"
      ;;
    esac
  done
  {
    set \
      +o verbose \
      +o xtrace
  } 2>/dev/null
  unset target >/dev/null 2>&1 || target=''
}

# number of files
# this directory and below
count_files() {
  # https://unix.stackexchange.com/a/1126
  find -- .//. \
    -path '*/.git' -prune -o \
    -path '*/node_modules' -prune -o \
    ! -name '.DS_Store' \
    ! -type d \
    -print |
    grep \
      -c \
      -e '//'
}

count_files_and_directories() {
  # -path './/./*' is POSIX mindepth=1 when searching
  # nonstandard directory `.//.`
  find -- .//. \
    -path '*/.git' -prune -o \
    -path '*/node_modules' -prune -o \
    -path './/./*' \
    ! -name '.DS_Store' \
    -print |
    grep \
      -c \
      -e '//'
}

count_files_by_extension() {
  # files with extensions
  # skip files:
  #   with no extension
  #   with a trailing dot
  find -- . \
    -path '*/.git' -prune -o \
    -path '*/node_modules' -prune -o \
    -name '*.*' \
    ! -name '*.' \
    ! -name '.DS_Store' \
    ! -type d \
    -exec sh -c -- 'for file in "${@}"; do printf -- '\''%s\n'\'' "${file##*.}"; done' _ {} + |
    LANG='C' LC_ALL='C' sort |
    uniq -c |
    LANG='C' LC_ALL='C' sort -n

  # files with no extension
  # - https://github.com/super-linter/super-linter/commit/4faa6433ab
  # - https://github.com/super-linter/super-linter/pull/1640
  # - https://github.com/super-linter/super-linter/pull/1536
  find -- . \
    -path '*/.git' -prune -o \
    -path '*/node_modules' -prune -o \
    ! -name '*.*' \
    ! -type d \
    -exec sh -c -- 'for file in "${@}"; do printf -- '\''[no extension]\n'\''; done' _ {} + 2>/dev/null |
    uniq -c
}
alias cfx='count_files_by_extension'

# number of files
# in current directory
count_files_in_this_directory() {
  case "${1-}" in
  # count files as well as directories
  -d | --directory | --directories)
    find -- . \
      -path './*/*' -prune -o \
      ! -name '.DS_Store' \
      -print |
      grep \
        -c \
        -e '/'
    ;;

  # count only regular, non-directory files
  *)
    # https://unix.stackexchange.com/a/1126
    find -- . \
      -path './*/*' -prune -o \
      ! -name '.DS_Store' \
      ! -type d \
      -print |
      grep \
        -c \
        -e '/'
    ;;
  esac
}

date_s() {
  # POSIX-compliant implementation of `date +%s`
  # https://web.archive.org/web/0id_/etalabs.net/sh_tricks.html
  printf -- '%d\n' "$(($(
    LANG='C' LC_ALL='C' date -u -- '+( (%Y - 1600) * 365 + (%Y - 1600) / 4 - (%Y - 1600) / 100 + (%Y - 1600) / 400 + %j - 135140) * 86400 + %H * 3600 + %M * 60 + %S'
  )))"
}

# define
alias d >/dev/null 2>&1 &&
  unalias -- d
command -v -- _which >/dev/null 2>&1 &&
  compdef -- define='which' >/dev/null 2>&1 &&
  compdef -- d='define' >/dev/null 2>&1
define() {
  for query in "${@:-define}"; do

    case "${query-}" in
    --)
      shift 1
      ;;

    *)
      # # `hash` (POSIX)
      # printf -- 'hash:\n%d\n' "$(
      #   hash -- "${query-}" >/dev/null 2>&1
      #   printf -- '%d\n' "${?:-1}"
      # )"

      # `type` (System V; POSIX)
      test "$(type -- "${query-}" 2>/dev/null)" != '' &&
        printf -- 'type:\n%s\n' "$(
          type -- "${query-}"
        )"

      # `command -V` (POSIX)
      test "$(command -V -- "${query-}" 2>/dev/null)" != "$(printf -- '%s not found' "${query-}")" &&
        printf -- '———\ncommand -V:\n%s\n' "$(
          command -V -- "${query-}"
        )"

      # `command -v` (POSIX)
      test "$(command -v -- "${query-}")" != '' &&
        printf -- '———\ncommand -v:\n%s\n' "$(
          command -v -- "${query-}"
        )"

      # `which` (C shell)
      test "$(command which -a -- "${query-}" 2>/dev/null)" != '' &&
        printf -- '———\nwhich -a:\n%s\n' "$(
          command which -a -- "${query-}"
        )"

      {
        # shellcheck disable=SC3044
        # `functions | bash | shfmt`
        if builtin declare -f -- "${query-}" >/dev/null 2>&1 &&
          bash --pretty-print -- "${query-}" >/dev/null 2>&1 &&
          shfmt -- "${query-}" >/dev/null 2>&1; then
          builtin declare -f -- "${query-}" |
            bash --pretty-print |
            sed \
              -e 's/\&\& /\&\&\n/g' \
              -e 's/\|\| /||\n/g' \
              -e '# these expressions are escaped on the search (that is, ˋs/\&\&...ˋ and ˋs/\|\|...ˋ instead of ˋs/&&...ˋ and ˋs/||...ˋ) so that ˋdefine defineˋ will not insert newlines into the presentation of the sed expressions. For the ampersands, the replacement string requires escaping or will print both the search then the replacement (ˋ&& &&\nˋ instead of ˋ&&\nˋ)' |
            shfmt --indent 2 --language-dialect bash --simplify -- -

        # `functions | shfmt`
        elif builtin declare -f -- "${query-}" 2>/dev/null |
          sed \
            -e 's/\&\& /\&\&\n/g' \
            -e 's/\|\| /||\n/g' |
          shfmt >/dev/null 2>&1; then
          builtin declare -f -- "${query-}" |
            sed \
              -e 's/\&\& /\&\&\n/g' \
              -e 's/\|\| /||\n/g' \
              -e '# these expressions are escaped on the search (that is, ˋs/\&\&...ˋ and ˋs/\|\|...ˋ instead of ˋs/&&...ˋ and ˋs/||...ˋ) so that ˋdefine defineˋ will not insert newlines into the presentation of the sed expressions. For the ampersands, the replacement string requires escaping or will print both the search then the replacement (ˋ&& &&\nˋ instead of ˋ&&\nˋ)' |
            shfmt --indent 2 --language-dialect bash --simplify -- -

        # `functions -x2`
        # because in Zsh,
        # `declare -f`     = `functions`, but
        # `declare -f -x` != `functions -x`
        elif builtin functions -x 2 -- "${query-}" >/dev/null 2>&1; then
          builtin functions -x 2 -- "${query-}"

        # `functions`
        elif builtin declare -f -- "${query-}" >/dev/null 2>&1; then
          builtin declare -f -- "${query-}"

        fi

      } |
        sed \
          -e '# find single spaces between single quotes, replace with newline and indent' \
          -e 's/'\'' '\''\([[:alnum:]]*sh[^[:space:]]*\)/'\''\n          '\''\1/g' \
          -e '# also move the first shell to be called onto its own indented line' \
          -e 's/" '\''zsh/"\n          '\''zsh/' | {
        bat \
          --decorations=never \
          --language=sh \
          --paging=never \
          - 2>/dev/null ||
          cat \
            -- \
            -
      }
      ;;
    esac
  done |
    awk -- 'BEGIN {
  found = 0
}
NF {
  print $0
  found = 1
}
END {
  exit ! found
}'
}
alias d='define'

alias diff >/dev/null 2>&1 &&
  unalias -- diff
alias diff='git -c core.quotePath=false diff --color-words --no-index'
diffy() {
  test "${#}" -eq 2 ||
    # EX_USAGE
    return 64
  diff \
    --side-by-side \
    --suppress-common-lines \
    --width="$((COLUMNS / 2 - 1 + COLUMNS / 2 - 1))" \
    "${@}"
}
command -v -- _diff >/dev/null 2>&1 &&
  compdef -- diffy='diff' >/dev/null 2>&1
diff_exif() {
  set \
    -o noclobber \
    -o noglob \
    -o nounset \
    -o verbose \
    -o xtrace
  set -- "${1-}" "${2-}" "${XDG_CACHE_HOME:-${HOME%/}/.cache}"'/tmp/diff_exif' &&
    mkdir -p -- "${3-}" &&
    exiftool "${1-}" >"${3-}"'/1' &&
    exiftool "${2-}" >"${3-}"'/2' &&
    diff \
      --side-by-side \
      --suppress-common-lines \
      --width="$((COLUMNS / 2 - 1 + COLUMNS / 2 - 1))" \
      -- \
      "${3-}"'/1' \
      "${3-}"'/2'
  {
    set \
      +o noclobber \
      +o noglob \
      +o nounset \
      +o verbose \
      +o xtrace
  } 2>/dev/null
  rm -f -R -- "${3-}" 2>/dev/null
}

dictionary() {
  # sort as you’d expect to find in a dictionary
  arguments=''
  case "${1-}" in
  --)
    shift 1
    ;;
  -*)
    arguments="${1##*-}"
    shift 1
    ;;
  *)
    LANG='C' LC_ALL='C' sort -u "${1:--}" |
      LANG='C' LC_ALL='C' sort '-f'"${arguments##*-}"
    ;;
  esac
  unset arguments >/dev/null 2>&1 || arguments=''
}

dimensions() {
  # print image file dimensions
  # even for SVGs
  # requires Exiftool
  command -v -- exiftool >/dev/null 2>&1 ||
    # EX_UNAVAILABLE
    return 69
  test "${#}" -gt 0 ||
    # EX_USAGE
    return 64
  for file in "${@}"; do
    test -s "${file-}" &&
      exiftool \
        -ViewBox \
        -short3 \
        -- \
        "${file-}" |
      awk -- '{print $3 "x" $4}'
    exiftool -ImageSize -short3 -- "${file-}" >/dev/null 2>&1 &&
      exiftool \
        -ImageSize \
        -short3 \
        -- \
        "${file-}"
  done
}

dirname_r() {
  test "${#}" -gt 0 ||
    # EX_USAGE
    return 64
  for file in "${@}"; do
    printf -- '%s\n' "${file%/*}"
  done
}

docker_r() {
  # run things like `docker_r --alpine` and `docker_r --ubuntu`
  command -v -- docker >/dev/null 2>&1 ||
    # EX_UNAVAILABLE
    return 69
  test "${#}" -gt 0 ||
    # EX_USAGE
    return 64
  set \
    -o verbose \
    -o xtrace
  case "${1-}" in
  --arch)
    shift 1 &&
      set -- --archlinux "${@}"
    ;;
  --latest)
    docker exec --interactive --tty "$(docker ps "${1-}" --quiet)" "${2:-/bin/zsh}" ||
      docker exec --interactive --tty "$(docker ps "${1-}" --quiet)" "${2:-/usr/bin/zsh}" ||
      docker exec --interactive --tty "$(docker ps "${1-}" --quiet)" "${2:-/bin/sh}"
    ;;
  *)
    {
      docker pull "${1##*--}" &&
        docker run --interactive --tty "${1##*--}"
    } || {
      docker pull -- "${1##*--}"
      docker exec --interactive --tty "$(docker ps --latest --quiet)"
    }
    ;;
  esac
  {
    set \
      +o verbose \
      +o xtrace
  } 2>/dev/null
}

domain_name_from_url() {
  test "${#}" -gt 0 ||
    # EX_USAGE
    return 64
  for url in "${@}"; do
    printf -- '%s\n' "${url-}" |
      sed \
        -e '# remove user@ if any (ultra rare)' \
        -e 's|^.*@||' \
        -e '# remove https:// or http://' \
        -e 's|^.*//||' \
        -e '# remove leading www. from lines containing 2+ dots' \
        -e '/\..*\./ s/^[^\.]*\.//' \
        -e '# remove ports like :80, :443 (rare) and trailing slash and beyond' \
        -e 's|[:/].*$||'
    #####
    ##### consider adding `npm help install`’s examples
    #####          npm install git+ssh://git@github.com:npm/cli.git#v1.0.27
    ##### npm install git+ssh://git@github.com:npm/cli#pull/273
    ##### npm install git+ssh://git@github.com:npm/cli#semver:^5.0
    ##### npm install git+https://isaacs@github.com/npm/cli.git
    ##### npm install git://github.com/npm/cli.git#v1.0.27
    ##### GIT_SSH_COMMAND='ssh -i ~/.ssh/custom_ident' npm install git+ssh://git@github.com:npm/cli.git
    # # remove `user@` if any (ultra rare)
    # url="${url##*@}"
    # # remove `https://` or `http://`
    # url="${url##*//}"
    # # remove leading `www.`
    # url="${url#*www.}"
    # # remove ports like `:80`, `:443` (rare) and trailing slash and beyond
    # url="${url%%[:/]*}"
    # printf -- '%s' "${url-}" &&
    #   printf -- '\n'
  done
}

domain_name_tld_list() {
  {
    curl --location --show-error --silent --url https://www.internic.net/domain/root.zone ||
      wget --hsts-file=/dev/null --output-document=- --quiet -- https://www.internic.net/domain/root.zone
    curl --location --show-error --silent --url https://data.iana.org/TLD/tlds-alpha-by-domain.txt ||
      wget --hsts-file=/dev/null --output-document=- --quiet -- https://data.iana.org/TLD/tlds-alpha-by-domain.txt
  } 2>/dev/null |
    sed \
      -e 's/\.[[:space:]].*//' \
      -e 's/.*\.//' \
      -e '/#/ d' |
    LANG='C' LC_ALL='C' tr -- '[:upper:]' '[:lower:]' |
    awk -- 'BEGIN {
  found = 0
}
NF && ! seen[$0]++ {
  print $0
  found = 1
}
END {
  exit ! found
}'
}

dotfiles_not_found() {
  test "${DOTFILES-}" != '' ||
    # EX_CONFIG
    return 78
  find -- "${DOTFILES-}" \
    -path "${DOTFILES-}"'/*/*' -prune -o \
    -name '.git*' -prune -o \
    -name '.*' \
    -exec sh -c -- 'for file in "${@}"; do test -e "${HOME%/}${file##*"${DOTFILES-}"}" || { printf -- '\''~%s'\'' "${file##*"${DOTFILES-}"}" && printf -- '\'' not found'\'' >&2 && printf -- '\''\n'\''; }; done && false' _ {} +
}
alias find_missing_dotfiles='dotfiles_not_found'

dss() {
  # delete thumbnail cache files
  # does -perm -600 help skip:
  #   find: ‘./Library/CloudStorage/GoogleDrive-lucas.larson@gmail.com/.tmp’: Permission denied
  #   find: ‘./Library/com.apple.internal.ck’: Operation not permitted
  while test "$(
    find -- . \
      '(' \
      -name '.[Dd][Ss]_[Ss][Tt][Oo][Rr][Ee]' -o \
      -name '._.[Dd][Ss]_[Ss][Tt][Oo][Rr][Ee]' -o \
      -name '[Dd][Ee][Ss][Kk][Tt][Oo][Pp].[Ii][Nn][Ii]' -o \
      -name '[Tt][Hh][Uu][Mm][Bb][Ss].[Dd][Bb]' \
      ')' \
      -type f \
      -perm -600 \
      -print
  )" != ''; do
    find -- . \
      '(' \
      -name '.[Dd][Ss]_[Ss][Tt][Oo][Rr][Ee]' -o \
      -name '._.[Dd][Ss]_[Ss][Tt][Oo][Rr][Ee]' -o \
      -name '[Dd][Ee][Ss][Kk][Tt][Oo][Pp].[Ii][Nn][Ii]' -o \
      -name '[Tt][Hh][Uu][Mm][Bb][Ss].[Dd][Bb]' \
      ')' \
      -type f \
      -perm -600 \
      -exec sh -c -- 'for file in "${@}"; do { printf -- '\''removing \342\200\230%s\342\200\231... '\'' "${file-}" >&2 && rm -f -- "${file-}" && printf -- '\''\342\234\223\n'\'' >&2; } || printf -- '\''error removing \342\200\230%s\342\200\231\n'\'' "${file-}" >&2;  done' _ {} +
  done
}

du() {
  # print the human-readable size of a given directory (defaults to current directory)
  dust "${@:--Fsxn$((LINES - 3))}" 2>/dev/null ||
    command -p -- du -h -s -- "${1:-.}"
}

epoch_seconds() {
  # return seconds since the epoch, 1969-12-31 19:00:00 EST
  # https://stackoverflow.com/a/41324810
  # `srand([expr])` will “Set the seed value for `rand` to `expr` or
  # use the time of day if `expr` is omitted.”
  # https://pubs.opengroup.org/onlinepubs/9699919799.2018edition/utilities/awk.html#tag_20_06_13_12
  awk -- 'BEGIN {srand(); print srand()}'
}
epoch_to_date_time() {
  if date -d '@0' >/dev/null 2>&1; then
    LANG='C' LC_ALL='C' date -d '@'"${1:-0}"
  else
    LANG='C' LC_ALL='C' date -r "${1:-0}"
  fi
}

## Esperanto
eo_from() {
  # Convert Cx-like esperanto typography into the correct unicode character (Ĉ ĉ Ĝ ĝ Ĥ ĥ Ĵ ĵ Ŝ ŝ Ŭ ŭ)
  # Xx is convert to x
  # https://github.com/Aeredren/txt2eo/blob/47c4e3a5ec/txt2eo
  command -v -- ed >/dev/null 2>&1 ||
    # EX_UNAVAILABLE
    return 69
  test "${#}" -gt 0 ||
    # EX_USAGE
    return 64
  set \
    -o noclobber \
    -o noglob \
    -o verbose \
    -o xtrace
  for file in "${@}"; do
    test -s "${file-}" &&
      test ! -L "${file-}" &&
      ed -- "${file-}" <<EOF
1,\$ s/Ĉ/Cx/g
1,\$ s/ĉ/cx/g
1,\$ s/Ĝ/Gx/g
1,\$ s/ĝ/gx/g
1,\$ s/Ĥ/Hx/g
1,\$ s/ĥ/hx/g
1,\$ s/Ĵ/Jx/g
1,\$ s/ĵ/jx/g
1,\$ s/Ŝ/Sx/g
1,\$ s/ŝ/sx/g
1,\$ s/Ŭ/Ux/g
1,\$ s/ŭ/ux/g
w
q
EOF
  done
  {
    set \
      +o noclobber \
      +o noglob \
      +o verbose \
      +o xtrace
  } 2>/dev/null
}

eo_to() {
  # Convert Cx-like esperanto typography into the correct unicode character (Ĉ ĉ Ĝ ĝ Ĥ ĥ Ĵ ĵ Ŝ ŝ Ŭ ŭ)
  # Xx is convert to x
  # https://github.com/Aeredren/txt2eo/blob/47c4e3a5ec/txt2eo
  command -v -- ed >/dev/null 2>&1 ||
    # EX_UNAVAILABLE
    return 69
  test "${#}" -gt 0 ||
    # EX_USAGE
    return 64
  set \
    -o noclobber \
    -o noglob \
    -o verbose \
    -o xtrace
  for file in "${@}"; do
    test -s "${file-}" &&
      test ! -L "${file-}" &&
      ed -- "${file-}" <<EOF
1,\$ s/Cx/Ĉ/g
1,\$ s/cx/ĉ/g
1,\$ s/Gx/Ĝ/g
1,\$ s/gx/ĝ/g
1,\$ s/Hx/Ĥ/g
1,\$ s/hx/ĥ/g
1,\$ s/Jx/Ĵ/g
1,\$ s/jx/ĵ/g
1,\$ s/Sx/Ŝ/g
1,\$ s/sx/ŝ/g
1,\$ s/Ux/Ŭ/g
1,\$ s/ux/ŭ/g
w
q
EOF
  done
  {
    set \
      +o noclobber \
      +o noglob \
      +o verbose \
      +o xtrace
  } 2>/dev/null
}

exif_copy_tags() {
  set \
    -o noclobber \
    -o verbose \
    -o xtrace
  test -s "${1-}" &&
    test -s "${2-}" &&
    test ! -L "${2-}" &&
    git rev-parse --is-inside-work-tree >/dev/null 2>&1 &&
    exiftool \
      -preserve \
      -overwrite_original \
      -ImageDescription="$(exiftool -ImageDescription "${1-}" | sed -e 's/[^:]*: //' -e 's/\./\n/g')" \
      -Caption-Abstract="$(exiftool -Caption-Abstract "${1-}" | sed -e 's/[^:]*: //' -e 's/\./\n/g')" \
      "${2-}" &&
    case "${2-}" in
    *.[Pp][Nn][Gg])
      exiftool \
        -preserve \
        -overwrite_original \
        -XMP:Description="$(exiftool -Caption-Abstract "${1-}" | sed -e 's/[^:]*: //' -e 's/\./\n/g')" \
        "${2-}"
      ;;
    *) ;;
    esac
  {
    set \
      +o noclobber \
      +o verbose \
      +o xtrace
  } 2>/dev/null
}
alias convert_exif='exif_copy_tags'

exif_remove() {
  set \
    -o noclobber \
    -o nounset \
    -o xtrace
  for file in "${@:-.}"; do
    test -s "${file-}" &&
      test ! -L "${file-}" &&
      git ls-files --error-unmatch -- "${file-}" >/dev/null 2>&1 &&
      # https://github.com/cirosantilli/dotfiles/blob/60ca745cdc/home/.bashrc#L2838-L2842
      # `-recurse` for when `$file` argument is a directory
      exiftool \
        -all='' \
        -overwrite_original \
        -progress \
        -recurse \
        -v0 \
        -- \
        "${file-}"
  done
  {
    set \
      +o noclobber \
      +o nounset \
      +o xtrace
  } 2>/dev/null
}

exit_codes() {
  # https://github.com/freebsd/freebsd/blob/2321c47418/include/sysexits.h
  # https://sourceware.org/git/?p=glibc.git;hb=6025c399e9;f=misc/sysexits.h
  # https://gist.github.com/235e6a10dad1b122fd147a92b345150e
  # sysexits(3)
  # /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/include/sysexits.h
  # /Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/include/sysexits.h
  # https://tldp.org/LDP/abs/html/exitcodes.html

  # output a table of exit codes and their meanings
  printf -- ' exit code | meaning\n'
  printf -- '-----------+----------\n'
  printf -- '         0 | EX_OK OK successful termination\n'
  printf -- '         1 | the command was aborted due to a signal that was caught (not an exit status of a shell builtin)\n'
  printf -- '         2 | the command was aborted because of a problem with the command-line syntax\n'
  printf -- '        64 | EX__BASE base value for error messages\n'
  printf -- '        64 | EX_USAGE command line usage error\n'
  printf -- '        65 | EX_DATAERR data format error\n'
  printf -- '        66 | EX_NOINPUT cannot open input\n'
  printf -- '        67 | EX_NOUSER addressee unknown\n'
  printf -- '        68 | EX_NOHOST host name unknown\n'
  printf -- '        69 | EX_UNAVAILABLE service unavailable\n'
  printf -- '        70 | EX_SOFTWARE internal software error\n'
  printf -- '        71 | EX_OSERR system error (e.g., unable to fork)\n'
  printf -- '        72 | EX_OSFILE critical OS file missing\n'
  printf -- '        73 | EX_CANTCREAT unable to create (user) output file\n'
  printf -- '        74 | EX_IOERR input/output error\n'
  printf -- '        75 | EX_TEMPFAIL temp failure; user is invited to retry\n'
  printf -- '        76 | EX_PROTOCOL remote error in protocol\n'
  printf -- '        77 | EX_NOPERM permission denied\n'
  printf -- '        78 | EX_CONFIG configuration error\n'
  printf -- '        78 | EX__MAX maximum listed value\n'
  printf -- '       126 | the command was found but not executable\n'
  printf -- '       127 | the command was not found\n'
  printf -- '       128 | the command was found but not executable\n'
  printf -- '       130 | the command was terminated by a signal\n'
  printf -- '       255 | the command was terminated by a signal\n'
}

exponent() {
  # return $(( $1 ** $2 ))
  # base ^ exponent
  # defaults to $1¹ or 0¹
  command -v -- bc >/dev/null 2>&1 ||
    # EX_UNAVAILABLE
    return 69
  printf -- '%f ^ %d\n' "${1:-0}" "${2:-1}" |
    bc -l |
    sed \
      -e '# prepend 0 to results that begin with a decimal point' \
      -e 's/^\./0./' \
      -e '# trim trailing decimal zeroes' \
      -e 's/\(\.[[:digit:]]*[1-9]\)0*$/\1/' \
      -e '# remove trailing dot if fraction becomes empty' \
      -e 's/\.0*$//'
}

export_U() {
  # remove duplicates from colon-delimited arrays
  # (preserving prepended items)
  printf -- '%s:::%s\n' "${1:-${PATH-}}" "${2:-${1:-${PATH-}}}" |
    sed -e 's/:/\n/g' |
    awk -- '! seen[$0]++ && NF {print $0}' |
    paste -d ':' -s -
}
alias \
  typeset_U='export_U' \
  export_u='export_U'

factorial() {
  test "${#}" -eq 1 ||
    # EX_USAGE
    return 64
  printf -- '%s\n' "${1-}" | grep -E -e '^[[:digit:]]+$' >/dev/null 2>&1 ||
    # EX_USAGE
    return 64
  set -- 1 "${1-}" &&
    while test "${2-}" -gt 0; do
      set -- "$((${1-} * ${2-}))" "$((${2-} - 1))"
    done &&
    printf -- '%d\n' "${1-}"
}

filename_extension() {
  test "${#}" -gt 0 ||
    # EX_USAGE
    return 64
  for file in "${@}"; do
    printf -- '%s\n' "${file##*.}"
  done
}

filename_without_extension() {
  test "${#}" -gt 0 ||
    # EX_USAGE
    return 64
  for file in "${@}"; do
    # https://stackoverflow.com/a/12152997
    printf -- '%s\n' "${file%.*}"
  done
}

filename_spaces_to_underscores() {
  find -- . \
    -depth \
    -name '*'"${1:-[[:space:]]}"'*' |
    while IFS='' read -r -- file; do
      mv -i -- "${file-}" "${file%/*}"/"$(
        printf -- '%s\n' "${file##*/}" |
          LANG='C' LC_ALL='C' tr -s -- "${1:-[:space:]}" "${2:-_}"
      )"
    done
}
filename_underscores_to_spaces() {
  find -- . \
    -depth \
    -name '*_*' |
    while IFS='' read -r -- file; do
      mv -i -- "${file-}" "${file%/*}"/"$(
        printf -- '%s\n' "${file##*/}" |
          LANG='C' LC_ALL='C' tr -s -- "${1:-_}" "${2:- }"
      )"
    done
}

file_closes_with_newline() {
  while test "${#}" -gt 0; do
    test -f "${1-}" ||
      # EX_USAGE
      return 64
    find -- "${1-}" \
      -exec sh -c -- 'test "$(tail -c 1 -- "${1-}" | wc -l)" -ne 0 || printf -- '\''%s does not close with a newline\n'\'' "${1-}" >&2' _ {} ';'
    shift 1
  done
}
alias \
  file_ends_with_newline='file_closes_with_newline' \
  newline_file_closes_with='file_closes_with_newline' \
  linelint='file_closes_with_newline' # name inspiration https://github.com/lra/mackup/commit/28811b7440

file_has_trailing_whitespace() {
  while test "${#}" -gt 0; do
    test -f "${1-}" ||
      # EX_USAGE
      return 64
    find -- "${1-}" \
      -exec sh -c -- 'test "$(sed -e '\''s/[[:space:]]*$//'\'' <"${1-}" | wc -l)" -eq "$(sed -e '\''s/[[:space:]]*$//'\'' <"${1-}" | wc -l)" || printf -- '\''%s has trailing whitespace\n'\'' "${1-}" >&2' _ {} ';'
    shift 1
  done
}

f() {
  # try using `fd`, if not then `find`
  if command -v -- fd >/dev/null 2>&1; then
    fd \
      --follow \
      --hidden \
      "${@}"
  else
    while test "${#}" -gt 0; do
      find -L -- . \
        -path '*/.git' -prune -o \
        -path '*/node_modules' -prune -o \
        -path './*' \
        -name '*'"$(printf -- '%s\n' "${1-}" | awk -- '{for (i = 1; i <= length($0); i++) {if (substr($0, i, 1) ~ /[[:alpha:]]/) {printf "[%s%s]", toupper(substr($0, i, 1)), tolower(substr($0, i, 1))} else {printf "%s", substr($0, i, 1)}} printf "\n"}')"'*' \
        -print
      shift 1
    done
  fi
}

fn() {
  if command -v -- fd >/dev/null 2>&1; then
    fd \
      --follow \
      --hidden \
      "${@}"
  else
    find -L -- . \
      -path '*/.*' -prune -o \
      -path '*/.bundle' -prune -o \
      -path '*/.cache' -prune -o \
      -path '*/.cask' -prune -o \
      -path '*/.git' -prune -o \
      -path '*/.hg' -prune -o \
      -path '*/.mypy_cache' -prune -o \
      -path '*/.pytest_cache' -prune -o \
      -path '*/.stack-work' -prune -o \
      -path '*/.svn' -prune -o \
      -path '*/.tox' -prune -o \
      -path '*/.venv' -prune -o \
      -path '*/node_modules' -prune -o \
      -path '*/vendor' -prune -o \
      -name '*'"$(printf -- '%s\n' "${1-}" | awk -- '{for (i = 1; i <= length($0); i++) {if (substr($0, i, 1) ~ /[[:alpha:]]/) {printf "[%s%s]", toupper(substr($0, i, 1)), tolower(substr($0, i, 1))} else {printf "%s", substr($0, i, 1)}} printf "\n"}')"'*' \
      -type f \
      -print 2>/dev/null |
      LANG='C' LC_ALL='C' sort -f
  fi
}

find_audio_files() {
  # these are all the extensions of audio files on my device
  # ∴ that’s everything
  # also includes `eza`’s `Icons::AUDIO`
  find -- . \
    -path '*/.git' -prune -o \
    -path '*/Library' -prune -o \
    -path '*/node_modules' -prune -o \
    '(' \
    -name '*.[Aa][Aa][Cc]' -o \
    -name '*.[Aa][Cc][Cc]' -o \
    -name '*.[Aa][Ii][Ff]' -o \
    -name '*.[Aa][Ii][Ff][Cc]' -o \
    -name '*.[Aa][Ii][Ff][Ff]' -o \
    -name '*.[Aa][Ll][Aa][Cc]' -o \
    -name '*.[Aa][Mm][Rr]' -o \
    -name '*.[Aa][Pp][Ee]' -o \
    -name '*.[Aa][Uu]' -o \
    -name '*.[Cc][Aa][Ff]' -o \
    -name '*.[Dd][Ss][Ff]' -o \
    -name '*.[Ff][Ll][Aa][Cc]' -o \
    -name '*.[Mm]4[Aa]' -o \
    -name '*.[Mm]4[Pp]' -o \
    -name '*.[Mm]4[Rr]' -o \
    -name '*.[Mm][Kk][Aa]' -o \
    -name '*.[Mm][Oo][Dd]' -o \
    -name '*.[Mm][Pp]2' -o \
    -name '*.[Mm][Pp]3' -o \
    -name '*.[Oo][Gg][Gg]' -o \
    -name '*.[Oo][Pp][Uu][Ss]' -o \
    -name '*.[Pp][Cc][Mm]' -o \
    -name '*.[Vv][Oo][Cc]' -o \
    -name '*.[Ww][Aa][Vv]' -o \
    -name '*.[Ww][Mm][Aa]' -o \
    -name '*.[Ww][Vv]' -o \
    -name '*.[Xx][Mm]' \
    ')' \
    -type f \
    -print 2>/dev/null
}

find_binary_files() {
  LC_ALL='C' find -- . \
    -path '*/.git' -prune -o \
    -path '*/node_modules' -prune -o \
    ! -name '.DS_Store' \
    -exec file -- {} + |
    sed \
      -e '/:.*directory/ d' \
      -e '/:.*empty/ d' \
      -e '/:.*JSON/ d' \
      -e '/:.*text/ d' \
      -e '/:.*very long lines/ d' \
      -e '# finally, remove file utility descriptions' \
      -e 's/:.*//'
}

find_broken_symlinks() {
  # https://pubs.opengroup.org/onlinepubs/9699919799.2018edition/utilities/find.html#tag_20_47_18
  # https://gitlab.opengroup.org/the-austin-group/sus_html/blob/783a8fc6d3/html/utilities/find.html#L697
  case "${1-}" in
  -d | --delete)
    find -L -- . \
      -type l \
      -exec sh -c -- 'ls -g -o -- "${1-}" &&
  rm -- "${1-}" &&
  git rm -- "${1-}" 2>/dev/null
' _ {} ';'
    ;;
  *)
    find -L -- . \
      -type l \
      -exec ls -g -o -- {} + 2>/dev/null
    ;;
  esac
}

find_capital_letter_files() {
  case "${1-}" in
  -d | --delete) LC_ALL='C' find -- . \
    -path '*/.git' -prune -o \
    -path '*/node_modules' -prune -o \
    -name '[[:upper:]]*' \
    -type f \
    -exec sh -c -- '{ printf -- '\''removing \342\200\230%s\342\200\231 '\'' "${1-}" >&2 && rm -f -R -- "${1-}" && printf -- '\''\342\234\223\n'\'' >&2; } || printf -- '\''error removing \342\200\230%s\342\200\231\n'\'' "${1-}" >&2' _ {} ';' ;;
  *) LC_ALL='C' find -- . \
    -path '*/.git' -prune -o \
    -path '*/node_modules' -prune -o \
    -name '[[:upper:]]*' \
    -type f \
    -print ;;
  esac
}

find_compressed_files() {
  {
    find -- . \
      -path '*/.git' -prune -o \
      -path '*/Library' -prune -o \
      -path '*/node_modules' -prune -o \
      '(' \
      -name '*.7[Zz]' -o \
      -name '*.[Aa][Aa][Rr]' -o \
      -name '*.[Aa][Pp][Kk]' -o \
      -name '*.[Bb][Rr]' -o \
      -name '*.[Bb][Zz]2' -o \
      -name '*.[Cc][Pp][Ii][Oo]' -o \
      -name '*.[Ee][Aa][Rr]' -o \
      -name '*.[Gg][Zz]' -o \
      -name '*.[Ii][Pp][Aa]' -o \
      -name '*.[Ii][Pp][Ss][Ww]' -o \
      -name '*.[Jj][Aa][Rr]' -o \
      -name '*.[Ll][Zz][Mm][Aa]' -o \
      -name '*.[Rr][Aa][Rr]' -o \
      -name '*.[Rr][Pp][Mm]' -o \
      -name '*.[Tt][Aa][Rr]' -o \
      -name '*.[Tt][Bb][Zz]' -o \
      -name '*.[Tt][Bb][Zz]2' -o \
      -name '*.[Tt][Gg][Zz]' -o \
      -name '*.[Tt][Ll][Zz]' -o \
      -name '*.[Tt][Xx][Zz]' -o \
      -name '*.[Tt][Zz][Ss][Tt]' -o \
      -name '*.[Ww][Aa][Rr]' -o \
      -name '*.[Ww][Hh][Ll]' -o \
      -name '*.[Xx][Pp][Ii]' -o \
      -name '*.[Xx][Zz]' -o \
      -name '*.[Zz]' -o \
      -name '*.[Zz][Ii][Pp]' -o \
      -name '*.[Zz][Mm][Aa]' -o \
      -name '*.[Zz][Ss][Tt]' \
      ')' \
      -type f \
      -print 2>/dev/null
    LANG='C' LC_ALL='C' find -- . \
      -path '*/.git' -prune -o \
      -path '*/Library' -prune -o \
      -path '*/node_modules' -prune -o \
      -type f \
      -exec file -- {} + 2>/dev/null |
      # allow `file` to find .sit `Archive` files by setting `$2` to lowercase before checking its value
      LC_ALL='C' awk -F':' -- '{
  if (tolower($2) ~ /archive|compress/) {
    print $1
  }
}'
  } |
    LANG='C' LC_ALL='C' sort -f |
    awk -- 'BEGIN {
  found = 0
}
NF && ! seen[$0]++ {
  print $0
  found = 1
}
END {
  exit ! found
}'
}

find_debug() {
  {
    printf -- '# find --debug\n' >&2
    printf -- ' find -D opt -- .\n' >&2
    printf -- '  # "\044{arguments-}"\n' >&2
    printf -- '  -print 2>&1 | ' >&2
    printf -- 'sed' >&2
    printf -- ' -n' >&2
    printf -- ' -e \047/^Optim.*command line:/ {\047' >&2
    printf -- ' -e \047n\047' >&2
    printf -- ' -e \047p\047' >&2
    printf -- ' -e \047}\047' >&2
    printf -- ' | ' >&2
    printf -- 'sed' >&2
    printf -- ' -e \047# remove redundant -a operator\047' >&2
    printf -- ' -e \047s/[[:space:]]-a[[:space:]]//g\047' >&2
    printf -- ' -e \047# suppress "[call stat]"\047' >&2
    printf -- ' -e \047s/\134[call stat\134]//g\047' >&2
    printf -- ' -e \047# suppress "[need type]"\047' >&2
    printf -- ' -e \047s/\134[need type\134]//g\047' >&2
    printf -- ' -e \047# suppress "[need inum]"\047' >&2
    printf -- ' -e \047s/\134[need inum\134]//g\047' >&2
    printf -- ' -e \047# remove estimates\047' >&2
    printf -- ' -e \047s/\134[est success rate[^]]*\134]//g\047' >&2
    printf -- ' -e \047# escape parentheses and colons\047' >&2
    printf -- ' -e \047s/\134([()\134;]\134)/\047\134\047\047\\1\047\134\047\047/g\047' >&2
    printf -- ' -e \047# enclose paths and names with single quotes\047' >&2
    printf -- ' -e \047s/\134(-i\134{0,1\134}[np]a[mt][eh]\134)[[:space:]]\134([^[:space:]]*\134)/\\1 \047\134\047\047\\2\047\134\047\047/g\047' >&2
    printf -- ' -e \047s/[[:space:]][[:space:]]*/ /g\047' >&2
    printf -- ' -e \047s/ *\134(.*\134)/#!\134/usr\134/bin\134/env sh\\nfind -- . \\1/g\047 | ' >&2
    printf -- 'shfmt --indent 2 --language-dialect bash --simplify -- - | ' >&2
    printf -- '{ bat --decorations=never --language=sh --paging=never -- - 2>/dev/null || ' >&2
    printf -- 'cat -- -; }\n' >&2
  } 2>&1 | {
    bat \
      --decorations=never \
      --language=sh \
      --paging=never \
      -- \
      - 2>/dev/null ||
      cat \
        -- \
        -
  }
}

find_dot_files() {
  case "${1-}" in
  -d | --delete)
    git rev-parse --is-inside-work-tree >/dev/null 2>&1 ||
      # EX_NOPERM
      return 77
    find -- . \
      -path '*/.git' -prune -o \
      -path '*/node_modules' -prune -o \
      -path './*' \
      -name '.*' \
      ! -name '.gitmodules' \
      -exec sh -c -- 'for file in "${@}"; do { printf -- '\''removing \342\200\230%s\342\200\231 '\'' "${file-}" >&2 && rm -f -R -- "${file-}" && printf -- '\''\342\234\223\n'\'' >&2; } || printf -- '\''error removing \342\200\230%s\342\200\231\n'\'' "${file-}" >&2; done' _ {} +
    ;;
  *)
    find -- . \
      -path '*/.git' -prune -o \
      -path '*/node_modules' -prune -o \
      -path './*' \
      -name '.*' \
      ! -name '.gitmodules' \
      -print 2>/dev/null |
      LANG='C' LC_ALL='C' sort -f |
      awk -- 'BEGIN {
  found = 0
}
NF {
  print $0
  found = 1
}
END {
  exit ! found
}'
    ;;
  esac
}

fdupes() {
  jdupes \
    --ext-filter=nostr:node_modules \
    --no-hidden \
    --one-file-system \
    --order=time \
    --quiet \
    --recurse \
    --size \
    "${@:-.}" \
    2>/dev/null |
    sed -e '/^No duplicates found\.$/ d'
}
find_duplicate_files() {
  # https://linuxjournal.com/content/boost-productivity-bash-tips-and-tricks
  # https://github.com/whodaniel/fuse/blob/b511341/scripts/component-refinement-plan.sh#L81
  find -- . \
    -path '*/.git' -prune -o \
    -path '*/.well-known' -prune -o \
    -path '*/Empty' -prune -o \
    -path '*/Library' -prune -o \
    -path '*/node_modules' -prune -o \
    -path '*/plugins' -prune -o \
    -path '*/t' -prune -o \
    -path '*/Test*' -prune -o \
    -path '*/test*' -prune -o \
    -path '*/themes' -prune -o \
    -path '*/tst*' -prune -o \
    -path '*copilot*' -prune -o \
    -path '*dummy*' -prune -o \
    -path '*vscode*' -prune -o \
    -type f \
    ! -size 0 \
    ! -name '.DS_Store' \
    -exec cksum -- {} + |
    awk -- '{
  checksum = $1
  size = $2
  filename = substr($0, index($0, $3))
  key = checksum FS size
  if (files[key]) {
    files[key] = files[key] RS filename
  } else {
    files[key] = filename
  }
  counts[key]++
}
END {
  separator = ""
  for (key in counts) {
    if (counts[key] > 1) {
      printf "%s%s\n", separator, files[key]
      separator = "\n"
    }
  }
}'
}
alias fdf='find_duplicate_files'

find_duplicate_images() {
  command -v -- findimagedupes >/dev/null 2>&1 ||
    # EX_UNAVAILABLE
    return 69
  findimagedupes \
    --quiet \
    --recurse \
    -- \
    . 2>/dev/null |
    column -t
}
alias fdi='find_duplicate_images'

find_editorconfig() {
  set -- "${PWD%/}" &&
    while test "${1-}" != ''; do
      test -f "${1-}"'/.editorconfig' &&
      printf -- '%s/.editorconfig\n' "${1-}"
      set -- "${1%/*}"
    done |
      awk -- 'BEGIN {
  found = 0
}
NF {
  print $0
  found = 1
}
END {
  exit ! found
}'
}
alias editorconfig_find='find_editorconfig'

find_empty() {
  case "${1-}" in
  -d | --delete)
    # POSIX- and `find`-compliant `find . -path '*/.git' -prune -o -type d -empty -delete`
    # because `-delete` activates `-depth`, and `-depth` overrides `-prune`, which reverses `-prune logic
    printf -- 'are you sure?\n' >&2 &&
      sleep 2 &&
      LC_ALL='C' find -- . \
        ! -path '*/.git*' \
        ! -path '*/Library*' \
        -path './*' \
        -type d \
        -exec sh -c -- 'for directory in "${@}"; do test "$(find -- "${directory-}" -path "${directory-}"'\''/*'\'' -print)" = '\'''\'' && rmdir -- "${directory-}"; done' _ {} +
    ;;
  *)
    # POSIX-compliant `find . -type d -empty`
    LC_ALL='C' find -- . \
      -path '*/.git' -prune -o \
      -path '*/Library' -prune -o \
      -path '*/node_modules' -prune -o \
      -path './*' \
      -type d \
      -exec sh -C -f -u -c -- 'for directory in "${@}"; do test "$(find -- "${directory-}" -path "${directory-}"'\''/*'\'' -print)" = '\'''\'' && printf -- '\''%s\n'\'' "${directory-}"; done' _ {} +
    ;;
  esac
}

find_executable() {
  find -- . \
    -path '*/.git' -prune -o \
    -path '*/.well-known' -prune -o \
    -path '*/Empty' -prune -o \
    -path '*/Library' -prune -o \
    -path '*/node_modules' -prune -o \
    -path '*/plugins' -prune -o \
    -path '*/t' -prune -o \
    -path '*/Test*' -prune -o \
    -path '*/test*' -prune -o \
    -path '*/themes' -prune -o \
    -path '*/tst*' -prune -o \
    -path '*copilot*' -prune -o \
    -path '*dummy*' -prune -o \
    -path '*vscode*' -prune -o \
    -type f \
    -perm -700 \
    -print 2>/dev/null |
    awk -- 'BEGIN {
  found = 0
}
NF {
  print
  found = 1
}
END {
  exit ! found
}'
}
find_executable_gnu() {
  # POSIX emulation of GNU `find -executable`
  # printing the names of all files – including directories – whose permissions meet or exceed 700
  find -- . \
    -perm -700 \
    -print
}

find_files_with_newline() {
  # https://github.com/yutkat/dotfiles/blob/76e4b7cd02/.zsh/rc/function.zsh#L246
  find -- . \
    -path '*/.git' -prune -o \
    -path '*/node_modules' -prune -o \
    ! -name '.DS_Store' \
    -type f \
    -exec sh -c -- 'file -- "${1-}" | grep -v -e '\'':.*executable'\'' >/dev/null 2>&1 && test "$(tail -c 1 -- "${1-}" 2>/dev/null)" = '\'''\'' && printf -- '\''%s\n'\'' "${1-}"' _ {} ';'
}

find_files_without_newline() {
  # https://github.com/yutkat/dotfiles/blob/76e4b7cd02/.zsh/rc/function.zsh#L246
  find -- . \
    -path '*/.git' -prune -o \
    -path '*/node_modules' -prune -o \
    ! -name '.DS_Store' \
    -type f \
    -exec sh -c -- 'file -- "${1-}" | grep -v -e '\'':.*executable'\'' -e '\'':.*image'\'' >/dev/null 2>&1 && test "$(tail -c 1 -- "${1-}" 2>/dev/null)" != '\'''\'' && printf -- '\''%s\n'\'' "${1-}"' _ {} ';'
}

find_files_with_windows_newline() {
  find -- . \
    -path '*/.git' -prune -o \
    -path '*/node_modules' -prune -o \
    ! -name '.DS_Store' \
    -type f \
    -exec sh -c -- 'file -- "${1-}" | grep -v -e '\'':.*-bit '\'' -e '\'':.*binary'\'' -e '\'':.*executable'\'' -e '\'': GIF image'\'' -e '\'': JPEG image'\'' -e '\'': PNG image'\'' -e '\'': RIFF '\'' >/dev/null 2>&1 && grep -l -e "$(printf -- '\''\015\012'\'')" -- "${1-}" 2>/dev/null' _ {} ';'
}

find_gitignore() {
  set -- "${PWD%/}" &&
    while test "${1-}" != ''; do
      test -f "${1-}"'/.gitignore' &&
      printf -- '%s/.gitignore\n' "${1-}"
      set -- "${1%/*}"
    done |
      awk -- 'BEGIN {
  found = 0
}
NF {
  print $0
  found = 1
}
END {
  exit ! found
}'
}
alias gitignore_find='find_gitignore'

# find HTML
find_html_files() {
  find -- . \
    -path '*/.bzr' -prune -o \
    -path '*/.CVS' -prune -o \
    -path '*/.cvs' -prune -o \
    -path '*/.git' -prune -o \
    -path '*/.hg' -prune -o \
    -path '*/.idea' -prune -o \
    -path '*/.svn' -prune -o \
    -path '*/.tox' -prune -o \
    -path '*/node_modules' -prune -o \
    -path '*copilot*' -prune -o \
    -path '*dummy*' -prune -o \
    -path '*vscode*' -prune -o \
    '(' \
    -name '*.html' -o \
    -name '*.[Hh][Tt][Aa]' -o \
    -name '*.[Hh][Tt][Mm]' -o \
    -name '*.[Hh][Tt][Mm][Ll]' -o \
    -name '*.[Hh][Tt][Mm][Ll].[Hh][Ll]' -o \
    -name '*.[Ii][Nn][Cc]' -o \
    -name '*.[Kk][Ii][Tt]' -o \
    -name '*.[Mm][Tt][Mm][Ll]' -o \
    -name '*.[Xx][Hh][Tt]' -o \
    -name '*.[Xx][Hh][Tt][Mm][Ll]' \
    ')' \
    -type f \
    -print 2>/dev/null
}

# find images
find_image_files() {
  # why of course this is the best way. you’re very welcome, future Lucas!
  # includes `eza`’s `Icons::IMAGE`
  find -- . \
    '(' \
    -name '*.[Aa][Ii]' -o \
    -name '*.[Aa][Pp][Nn][Gg]' -o \
    -name '*.[Aa][Rr][Ww]' -o \
    -name '*.[Aa][Vv][Ii][Ff]' -o \
    -name '*.[Bb][Ii][Tt][Mm][Aa][Pp]' -o \
    -name '*.[Bb][Mm][Pp]' -o \
    -name '*.[Bb][Mm][Pp]24' -o \
    -name '*.[Cc][Aa][Rr]' -o \
    -name '*.[Cc][Bb][Rr]' -o \
    -name '*.[Cc][Bb][Zz]' -o \
    -name '*.[Cc][Gg][Mm]' -o \
    -name '*.[Cc][Rr]2' -o \
    -name '*.[Cc][Uu][Rr]' -o \
    -name '*.[Dd][Dd][Ss]' -o \
    -name '*.[Dd][Vv][Ii]' -o \
    -name '*.[Ee][Pp][Ss]' -o \
    -name '*.[Ee][Xx][Rr]' -o \
    -name '*.[Ff][Ii][Gg]' -o \
    -name '*.[Ff][Oo][Dd][Gg]' -o \
    -name '*.[Gg][Ii][Ff]' -o \
    -name '*.[Gg][Ii][Ff]87' -o \
    -name '*.[Gg][Ii][Ff]89' -o \
    -name '*.[Hh][Ee][Ii][Cc]' -o \
    -name '*.[Hh][Ee][Ii][Ff]' -o \
    -name '*.[Ii][Cc][Nn][Ss]' -o \
    -name '*.[Ii][Cc][Oo]' -o \
    -name '*.[Ii][Mm]{1,8,24} Sun raster image' -o \
    -name '*.[Ii][Mm]1' -o \
    -name '*.[Ii][Mm]8' -o \
    -name '*.[Ii][Mm]24' -o \
    -name '*.[Ii][Tt][Cc] Apple Music.app JPEGs' -o \
    -name '*.[Ii][Tt][Cc]' -o \
    -name '*.[Jj]2[Cc]' -o \
    -name '*.[Jj]2[Kk]' -o \
    -name '*.[Jj][Ff][Ii]' -o \
    -name '*.[Jj][Ff][Ii][Ff]' -o \
    -name '*.[Jj][Ii][Ff]' -o \
    -name '*.[Jj][Pp]2' -o \
    -name '*.[Jj][Pp][Cc]' -o \
    -name '*.[Jj][Pp][Ee]' -o \
    -name '*.[Jj][Pp][Ee][Gg]' -o \
    -name '*.[Jj][Pp][Ff]' -o \
    -name '*.[Jj][Pp][Gg]' -o \
    -name '*.[Jj][Pp][Xx]' -o \
    -name '*.[Jj][Xx][Ll]' -o \
    -name '*.[Kk][Rr][Aa]' -o \
    -name '*.[Kk][Rr][Zz]' -o \
    -name '*.[Mm][Vv][Gg] ImageMagick Vector Graphic' -o \
    -name '*.[Mm][Vv][Gg]' -o \
    -name '*.[Nn][Ee][Ff]' -o \
    -name '*.[Oo][Dd][Gg]' -o \
    -name '*.[Oo][Rr][Ff]' -o \
    -name '*.[Pp]7 XV thumbnail image data' -o \
    -name '*.[Pp]7' -o \
    -name '*.[Pp][Bb][Mm]' -o \
    -name '*.[Pp][Gg][Mm]' -o \
    -name '*.[Pp][Ii][Cc]' -o \
    -name '*.[Pp][Ii][Cc][Tt]' -o \
    -name '*.[Pp][Jj][Pp]' -o \
    -name '*.[Pp][Jj][Pp][Ee][Gg]' -o \
    -name '*.[Pp][Jj][Pp][Gg]' -o \
    -name '*.[Pp][Nn][Gg]' -o \
    -name '*.[Pp][Nn][Jj]' -o \
    -name '*.[Pp][Nn][Mm]' -o \
    -name '*.[Pp][Pp][Mm]' -o \
    -name '*.[Pp][Ss][Dd]' -o \
    -name '*.[Pp][Xx][Mm]' -o \
    -name '*.[Qq][Oo][Ii]' -o \
    -name '*.[Rr][Aa][Ww]' -o \
    -name '*.[Rr][Ii][Ff]johnalanwoods/maintained-modern-unix@c43c4b3f29/screenshots/zoxide.riff' -o \
    -name '*.[Rr][Ii][Ff]' -o \
    -name '*.[Rr][Ii][Ff][Ff]' -o \
    -name '*.[Rr][Ll][Ee]' -o \
    -name '*.[Ss][Gg][Ii]' -o \
    -name '*.[Ss][Rr][Ww]' -o \
    -name '*.[Ss][Vv][Gg]' -o \
    -name '*.[Ss][Vv][Gg][Zz]' -o \
    -name '*.[Tt][Gg][Aa]' -o \
    -name '*.[Tt][Hh][Mm]' -o \
    -name '*.[Tt][Ii][Ff]' -o \
    -name '*.[Tt][Ii][Ff][Ff]' -o \
    -name '*.[Ww][Ee][Bb][Pp]' -o \
    -name '*.[Xx][Bb][Mm]' -o \
    -name '*.[Xx][Cc][Ff]' -o \
    -name '*.[Xx][Pp][Mm]' \
    ')' \
    -type f \
    -print 2>/dev/null
  {
    # when the following portion is removed, you may also remove `2>/dev/null` from `find_images_with_incorrect_filename_extensions` probably
    printf -- '#!/usr/bin/env sh\nCDPATH='\''.'\'' cd "\044{HOME-}"'\''/c'\'' >/dev/null 2>&1 &&\n  LC_ALL='\''C'\'' find -L -- . -path '\''*/.git'\'' -prune -o -type f -exec file -- '\''{}'\'' + |\n  LC_ALL='\''C'\'' sed \\\n    -n \\\n    -e '\''/: .* image/ {'\'' \\\n    -e '\''  s/^\\([^:]*\\):.*$/\\1/p'\'' \\\n    -e '\''}'\''\n' |
      bat \
        --decorations=never \
        --language=sh \
        --paging=never \
        -- \
        - >&2 2>/dev/null ||
      cat \
        -- \
        -
  } >&2
}
alias fif='find_image_files'

find_images_with_incorrect_filename_extensions() {
  # 2>/dev/null until `find_image_files` removes post-completion helpful hint
  command -v -- find_image_files >/dev/null 2>&1 ||
    # EX_UNAVAILABLE
    return 69
  find_image_files 2>/dev/null |
    while IFS='' read -r -- file; do
      case "${file-}" in
      *.[Aa][Ii]) file -- "${file-}" | grep -F -e "${file-}"': PDF document' >/dev/null 2>&1 || printf -- '%s\n' "${file-}" ;;
      *.[Aa][Vv][Ii][Ff]) file -- "${file-}" | grep -F -e "${file-}"': ISO Media, AVIF Image' >/dev/null 2>&1 || printf -- '%s\n' "${file-}" ;;
      *.[Bb][Mm][Pp]) file -- "${file-}" | grep -F -e "${file-}"': PC bitmap' >/dev/null 2>&1 || printf -- '%s\n' "${file-}" ;;
      *.[Ee][Pp][Ss]) file -- "${file-}" | grep -F -e "${file-}"': DOS EPS Binary File' -e "${file-}"': PostScript document' >/dev/null 2>&1 || printf -- '%s\n' "${file-}" ;;
      *.[Gg][Ii][Ff]) file -- "${file-}" | grep -F -e "${file-}"': GIF image' >/dev/null 2>&1 || printf -- '%s\n' "${file-}" ;;
      *.[Hh][Ee][Ii][Cc]) file -- "${file-}" | grep -F -e "${file-}"': ISO Media, HEIF Image' >/dev/null 2>&1 || printf -- '%s\n' "${file-}" ;;
      *.[Ii][Cc][Nn][Ss]) file -- "${file-}" | grep -F -e "${file-}"': Mac OS X icon' >/dev/null 2>&1 || printf -- '%s\n' "${file-}" ;;
      *.[Ii][Cc][Oo]) file -- "${file-}" | grep -F -e "${file-}"': MS Windows icon' >/dev/null 2>&1 || printf -- '%s\n' "${file-}" ;;
      *.[Jj][Pp][Ee] | *.[Jj][Pp][Ee][Gg] | *.[Jj][Pp][Gg]) file -- "${file-}" | grep -F -e "${file-}"': JPEG image' >/dev/null 2>&1 || printf -- '%s\n' "${file-}" ;;
      *.[Pp][Bb][Mm] | *.[Pp][Gg][Mm] | *.[Pp][Pp][Mm]) file -- "${file-}" | grep -F -e "${file-}"': Netpbm image' >/dev/null 2>&1 || printf -- '%s\n' "${file-}" ;;
      *.[Pp][Nn][Gg]) file -- "${file-}" | grep -F -e "${file-}"': PNG image' >/dev/null 2>&1 || printf -- '%s\n' "${file-}" ;;
      *.[Pp][Ss][Dd]) file -- "${file-}" | grep -F -e "${file-}"': Adobe Photoshop Image' >/dev/null 2>&1 || printf -- '%s\n' "${file-}" ;;
      *.[Ss][Vv][Gg]) file -- "${file-}" | grep -F -e "${file-}"': SVG Scalable Vector Graphics image' >/dev/null 2>&1 || printf -- '%s\n' "${file-}" ;;
      *.[Tt][Ii][Ff] | *.[Tt][Ii][Ff][Ff]) file -- "${file-}" | grep -F -e "${file-}"': TIFF image' >/dev/null 2>&1 || printf -- '%s\n' "${file-}" ;;
      # `file` calls `.webp` files `RIFF... Web/P`
      *.[Ww][Ee][Bb][Pp]) file -- "${file-}" | grep -F -e "${file-}"': RIFF' 2>/dev/null | grep -e ' Web/P image' >/dev/null 2>&1 || printf -- '%s\n' "${file-}" ;;
      *) printf -- '%s: this test does not yet test \140%s\140 files\n' "${file-}" "$(
        printf -- '%s\n' "${file##*.}" |
          LANG='C' LC_ALL='C' tr -- '[:lower:]' '[:upper:]'
      )" >&2 ;;
      esac
    done
}

find_json_files() {
  find -- . \
    -path '*/.git' -prune -o \
    -path '*/.well-known' -prune -o \
    -path '*/Library' -prune -o \
    -path '*/node_modules' -prune -o \
    -path '*/t' -prune -o \
    -path '*/Test*' -prune -o \
    -path '*/test*' -prune -o \
    -path '*/tst*' -prune -o \
    -path '*copilot*' -prune -o \
    -path '*dummy*' -prune -o \
    '(' \
    -name '*.json' -o \
    -name '*.4[Dd][Ff][Oo][Rr][Mm]' -o \
    -name '*.4[Dd][Pp][Rr][Oo][Jj][Ee][Cc][Tt]' -o \
    -name '*.[Aa][Vv][Ss][Cc]' -o \
    -name '*.[Bb][Aa][Bb][Ee][Ll][Rr][Cc]*' -o \
    -name '*.[Cc][Jj][Ss].[Mm][Aa][Pp]' -o \
    -name '*.[Cc][Oo][Dd][Ee]-[Ww][Oo][Rr][Kk][Ss][Pp][Aa][Cc][Ee]' -o \
    -name '*.[Cc][Ss][Ss].[Mm][Aa][Pp]' -o \
    -name '*.[Cc][Yy]' -o \
    -name '*.[Gg][Ee][Oo][Jj][Ss][Oo][Nn]' -o \
    -name '*.[Gg][Ll][Tt][Ff]' -o \
    -name '*.[Hh][Aa][Rr]' -o \
    -name '*.[Hh][Uu][Jj][Ss][Oo][Nn]' -o \
    -name '*.[Ii][Cc][Ee]' -o \
    -name '*.[Jj][Ss].[Mm][Aa][Pp]' -o \
    -name '*.[Jj][Ss][Oo][Nn]' -o \
    -name '*.[Jj][Ss][Oo][Nn]-[Tt][Mm][Ll][Aa][Nn][Gg][Uu][Aa][Gg][Ee]' -o \
    -name '*.[Jj][Ss][Oo][Nn].[Ee][Xx][Aa][Mm][Pp][Ll][Ee]' -o \
    -name '*.[Jj][Ss][Oo][Nn]5' -o \
    -name '*.[Jj][Ss][Oo][Nn][Ll]' -o \
    -name '*.[Jj][Ss][Oo][Nn][Ll][Dd]' -o \
    -name '*.[Mm][Aa][Xx][Hh][Ee][Ll][Pp]' -o \
    -name '*.[Mm][Aa][Xx][Pp][Aa][Tt]' -o \
    -name '*.[Mm][Aa][Xx][Pp][Rr][Oo][Jj]' -o \
    -name '*.[Mm][Cc][Mm][Ee][Tt][Aa]' -o \
    -name '*.[Mm][Xx][Tt]' -o \
    -name '*.[Nn][Mm][Ff]' -o \
    -name '*.[Rr][Cc][Pp][Rr][Oo][Jj][Ee][Cc][Tt][Dd][Aa][Tt][Aa]' -o \
    -name '*.[Ss][Aa][Rr][Ii][Ff]' -o \
    -name '*.[Ss][Ll][Nn][Ll][Aa][Uu][Nn][Cc][Hh]' -o \
    -name '*.[Ss][Tt][Aa][Tt][Ss]' -o \
    -name '*.[Ss][Tt][Rr][Ii][Nn][Gg][Ss][Dd][Aa][Tt][Aa]' -o \
    -name '*.[Ss][Uu][Bb][Ll][Ii][Mm][Ee]-[Bb][Uu][Ii][Ll][Dd]' -o \
    -name '*.[Ss][Uu][Bb][Ll][Ii][Mm][Ee]-[Cc][Oo][Ll][Oo][Rr]-[Ss][Cc][Hh][Ee][Mm][Ee]' -o \
    -name '*.[Ss][Uu][Bb][Ll][Ii][Mm][Ee]-[Cc][Oo][Mm][Mm][Aa][Nn][Dd][Ss]' -o \
    -name '*.[Ss][Uu][Bb][Ll][Ii][Mm][Ee]-[Cc][Oo][Mm][Pp][Ll][Ee][Tt][Ii][Oo][Nn][Ss]' -o \
    -name '*.[Ss][Uu][Bb][Ll][Ii][Mm][Ee]-[Kk][Ee][Yy][Mm][Aa][Pp]' -o \
    -name '*.[Ss][Uu][Bb][Ll][Ii][Mm][Ee]-[Mm][Aa][Cc][Rr][Oo]' -o \
    -name '*.[Ss][Uu][Bb][Ll][Ii][Mm][Ee]-[Mm][Ee][Nn][Uu]' -o \
    -name '*.[Ss][Uu][Bb][Ll][Ii][Mm][Ee]-[Mm][Oo][Uu][Ss][Ee][Mm][Aa][Pp]' -o \
    -name '*.[Ss][Uu][Bb][Ll][Ii][Mm][Ee]-[Pp][Rr][Oo][Jj][Ee][Cc][Tt]' -o \
    -name '*.[Ss][Uu][Bb][Ll][Ii][Mm][Ee]-[Ss][Ee][Tt][Tt][Ii][Nn][Gg][Ss]' -o \
    -name '*.[Tt][Aa][Cc][Tt]' -o \
    -name '*.[Tt][Ee][Rr][Nn]-[Pp][Rr][Oo][Jj][Ee][Cc][Tt]' -o \
    -name '*.[Tt][Ff][Ss][Tt][Aa][Tt][Ee]' -o \
    -name '*.[Tt][Ff][Ss][Tt][Aa][Tt][Ee].[Bb][Aa][Cc][Kk][Uu][Pp]' -o \
    -name '*.[Tt][Oo][Pp][Oo][Jj][Ss][Oo][Nn]' -o \
    -name '*.[Tt][Ss].[Mm][Aa][Pp]' -o \
    -name '*.[Tt][Ss][Bb][Uu][Ii][Ll][Dd][Ii][Nn][Ff][Oo]' -o \
    -name '*.[Ww][Ee][Bb][Aa][Pp][Pp]' -o \
    -name '*.[Ww][Ee][Bb][Mm][Aa][Nn][Ii][Ff][Ee][Ss][Tt]' -o \
    -name '*.[Xx][Aa][Mm][Ll][Ss][Tt][Yy][Ll][Ee][Rr]' -o \
    -name '*.[Xx][Cc][Ss][Cc][Mm][Bb][Ll][Uu][Ee][Pp][Rr][Ii][Nn][Tt]' -o \
    -name '*.[Xx][Cc][Tt][Ee][Ss][Tt][Pp][Ll][Aa][Nn]' -o \
    -name '*.[Yy][Tt][Dd][Ll]' -o \
    -name '*.[Yy][Yy]' -o \
    -name '*.[Yy][Yy][Pp]' -o \
    -name '*[Aa][Pp][Pp]-[Ss][Ii][Tt][Ee]-[Aa][Ss][Ss][Oo][Cc][Ii][Aa][Tt][Ii][Oo][Nn]' -o \
    -name '.[Aa][Ll][Ll]-[Cc][Oo][Nn][Tt][Rr][Ii][Bb][Uu][Tt][Oo][Rr][Ss][Rr][Cc]' -o \
    -name '.[Aa][Rr][Cc][Cc][Oo][Nn][Ff][Ii][Gg]' -o \
    -name '.[Aa][Uu][Tt][Oo]-[Cc][Hh][Aa][Nn][Gg][Ee][Ll][Oo][Gg]' -o \
    -name '.[Bb][Oo][Ww][Ee][Rr][Rr][Cc]' -o \
    -name '.[Cc]8[Rr][Cc]' -o \
    -name '.[Cc][Aa][Rr][Dd][Ii][Nn][Aa][Ll][Rr][Cc]' -o \
    -name '.[Cc][Oo][Uu][Cc][Hh][Aa][Pp][Pp][Rr][Cc]' -o \
    -name '.[Dd][Cc][Cc][Aa][Cc][Hh][Ee]' -o \
    -name '.[Dd][Oo][Cc][Kk][Ee][Rr][Cc][Ff][Gg]' -o \
    -name '.[Ee][Ss][Ll][Ii][Nn][Tt][Cc][Aa][Cc][Hh][Ee]' -o \
    -name '.[Ee][Ss][Ll][Ii][Nn][Tt][Rr][Cc]' -o \
    -name '.[Ff][Ll][Uu][Tt][Tt][Ee][Rr]' -o \
    -name '.[Ff][Ll][Uu][Tt][Tt][Ee][Rr]_[Tt][Oo][Oo][Ll]_[Ss][Tt][Aa][Tt][Ee]' -o \
    -name '.[Ff][Tt][Pp][Cc][Oo][Nn][Ff][Ii][Gg]' -o \
    -name '.[Gg][Uu][Tt][Tt][Ee][Rr]-[Tt][Hh][Ee][Mm][Ee]' -o \
    -name '.[Hh][Tt][Mm][Ll][Hh][Ii][Nn][Tt][Rr][Cc]' -o \
    -name '.[Ii][Mm][Gg][Bb][Oo][Tt][Cc][Oo][Nn][Ff][Ii][Gg]' -o \
    -name '.[Jj][Rr][Nn][Ll]_[Cc][Oo][Nn][Ff][Ii][Gg]' -o \
    -name '.[Jj][Ss][Cc][Ss][Rr][Cc]' -o \
    -name '.[Jj][Ss][Hh][Ii][Nn][Tt][Rr][Cc]' -o \
    -name '.[Nn][Yy][Cc][Rr][Cc]' -o \
    -name '.[Pp][Rr][Ee][Tt][Tt][Ii][Ee][Rr][Rr][Cc]' -o \
    -name '.[Rr][Ee][Ll][Ee][Aa][Ss][Ee][Rr][Cc]' -o \
    -name '.[Rr][Ee][Mm][Aa][Rr][Kk][Rr][Cc]' -o \
    -name '.[Ss][Tt][Yy][Ll][Ee][Ll][Ii][Nn][Tt][Rr][Cc]' -o \
    -name '.[Tt][Ee][Rr][Nn]-[Cc][Oo][Nn][Ff][Ii][Gg]' -o \
    -name '.[Tt][Ee][Rr][Nn]-[Pp][Rr][Oo][Jj][Ee][Cc][Tt]' -o \
    -name '.[Tt][Ee][Xx][Tt][Ll][Ii][Nn][Tt][Rr][Cc]' -o \
    -name '.[Vv][Ss]-[Ll][Ii][Vv][Ee][Ss][Hh][Aa][Rr][Ee]-[Kk][Ee][Yy][Cc][Hh][Aa][Ii][Nn]' -o \
    -name '.[Vv][Ss][Cc][Oo][Nn][Ff][Ii][Gg]' -o \
    -name '.[Ww][Aa][Tt][Cc][Hh][Mm][Aa][Nn][Cc][Oo][Nn][Ff][Ii][Gg]' -o \
    -name '.[Ww][Hh][Ii][Tt][Ee][Ss][Oo][Uu][Rr][Cc][Ee]' -o \
    -name '.[Yy][Aa][Rr][Nn]-[Ii][Nn][Tt][Ee][Gg][Rr][Ii][Tt][Yy]' -o \
    -name '[Cc][Oo][Mm][Pp][Oo][Ss][Ee][Rr].[Ll][Oo][Cc][Kk]' -o \
    -name '[Dd][Ee][Nn][Oo].[Ll][Oo][Cc][Kk]' -o \
    -name '[Ee][Ss][Ll][Ii][Nn][Tt][Rr][Cc]' -o \
    -name '[Ff][Ll][Aa][Kk][Ee].[Ll][Oo][Cc][Kk]' -o \
    -name '[Mm][Cc][Mm][Oo][Dd].[Ii][Nn][Ff][Oo]' -o \
    -name '[Mm][Oo][Dd][Uu][Ll][Ee].[Bb][Aa][Zz][Ee][Ll].[Ll][Oo][Cc][Kk]' -o \
    -name '[Pp][Aa][Cc][Kk][Aa][Gg][Ee].[Rr][Ee][Ss][Oo][Ll][Vv][Ee][Dd]' -o \
    -name '[Pp][Ii][Pp][Ff][Ii][Ll][Ee].[Ll][Oo][Cc][Kk]' -o \
    -name '[Pp][Rr][Oo][Ss][Ee][Ll][Ii][Nn][Tt][Rr][Cc]' -o \
    -name '[Tt][Ll][Dd][Rr][Rr][Cc]' \
    ')' \
    -type f \
    -print 2>/dev/null |
    awk -- 'BEGIN {
  found = 0
}
NF {
  print $0
  found = 1
}
END {
  exit ! found
}'
}

find_largest_files() {
  (
    find -- . \
      -path '*/.git' -prune -o \
      -path '*/node_modules' -prune -o \
      -path '*copilot*' -prune -o \
      ! -name '.DS_Store' \
      -type f \
      -exec ls -n -S -- {} + 2>/dev/null &
  ) |
    head -n "$((${LINES:-"$(
      tput -- lines 2>/dev/null ||
        printf -- '10 + 2'
    )"} - 3))" "${@}"
}

find_markdown_files() {
  find -- . \
    -path '*/.git' -prune -o \
    -path '*/node_modules' -prune -o \
    '(' \
    -name '*.md' -o \
    -name '*.[Ll][Ii][Vv][Ee][Mm][Dd]' -o \
    -name '*.[Mm][Aa][Rr][Kk][Dd][Nn]' -o \
    -name '*.[Mm][Aa][Rr][Kk][Dd][Oo][Ww][Nn]' -o \
    -name '*.[Mm][Dd]' -o \
    -name '*.[Mm][Dd][Oo][Ww][Nn]' -o \
    -name '*.[Mm][Dd][Ww][Nn]' -o \
    -name '*.[Mm][Dd][Xx]' -o \
    -name '*.[Mm][Kk][Dd]' -o \
    -name '*.[Mm][Kk][Dd][Nn]' -o \
    -name '*.[Mm][Kk][Dd][Oo][Ww][Nn]' -o \
    -name '*.[Rr][Oo][Nn][Nn]' -o \
    -name '*.[Ss][Cc][Dd]' -o \
    -name '*.[Ww][Oo][Rr][Kk][Bb][Oo][Oo][Kk]' -o \
    -name '[Cc][Oo][Nn][Tt][Ee][Nn][Tt][Ss].[Ll][Rr]' \
    ')' \
    -type f \
    -print 2>/dev/null
}

find_microsoft_files() {
  find -- . \
    -path '*/.git' -prune -o \
    -path '*/node_modules' -prune -o \
    '(' \
    -name '*.[Dd][Oo][Cc]' -o \
    -name '*.[Dd][Oo][Cc][Xx]' -o \
    -name '*.[Pp][Pp][Tt]' -o \
    -name '*.[Pp][Pp][Tt][Xx]' -o \
    -name '*.[Xx][Ll][Ss]' -o \
    -name '*.[Xx][Ll][Ss][Xx]' \
    ')' \
    -type f \
    -print 2>/dev/null
}

find_files_with_no_extension() {
  find -- . \
    -path '*/.git' -prune -o \
    -path '*/node_modules' -prune -o \
    ! -name '*.*' \
    ! -type d \
    -print 2>/dev/null
}
alias fnx='find_files_with_no_extension'

find_files_with_the_same_names() {
  LC_ALL='C' find -- . \
    -path '*/.git' -prune -o \
    -path '*/node_modules' -prune -o \
    ! -name '.DS_Store' \
    -type f \
    -exec sh -c -- 'for file in "${@}"; do
  # treat all as identical: `file.txt`, `file 1.txt`, `file.text`
  #        was `basename -- "${file%.*}"`
  basename -- "${file%[0-9]*.*}"
done' _ {} + |
    LANG='C' LC_ALL='C' sort |
    LC_ALL='C' uniq -d

  LC_ALL='C' find -- . \
    -path '*/.git' -prune -o \
    -path '*/node_modules' -prune -o \
    ! -name '.DS_Store' \
    -type f \
    -print |
    LC_ALL='C' sed \
      -e '# convert "foo/bar.baz" into "bar"' \
      -e 's/.*\/\([^/]*\)\.[^.]*$/\1/' |
    LC_ALL='C' sed \
      -e 's/ 1$//' |
    LANG='C' LC_ALL='C' sort |
    LC_ALL='C' uniq -d
}

find_files_with_the_same_sizes() {
  set -o noglob
  LC_ALL='C' find -- . \
    -path '*/.git' -prune -o \
    -path '*/node_modules' -prune -o \
    ! -name '.DS_Store' \
    -type f \
    ! -size 0 \
    -exec cksum -- {} + |
    # cksum prints 3+ columns; we want all but the first
    LC_ALL='C' sed \
      -e 's/^[[:space:]]\{0,\}[[:digit:]]\{1,\}[[:space:]]\{1,\}\([[:digit:]]\{1,\}\)[[:space:]]\{1,\}\(.*\)$/\1 \2/' |
    LANG='C' LC_ALL='C' sort -n |
    LC_ALL='C' awk -- '{
  sizes[$1]++
  if (lines[$1]) {
    lines[$1] = lines[$1] RS $0
  } else {
    lines[$1] = $0
  }
}
END {
  for (size in sizes) {
    if (sizes[size] > 1) {
      # print duplicates in groups
      printf "\n%s\n", lines[size]
    }
  }
}'
  {
    set +o noglob
  } 2>/dev/null
}
alias \
  find_duplicate_sizes='find_files_with_the_same_sizes' \
  fds='find_files_with_the_same_sizes'

find_oldest_files() {
  (
    find -- . \
      -path '*/.git' -prune -o \
      -path '*/node_modules' -prune -o \
      -type f \
      -exec ls -o -r -t -- {} + 2>/dev/null &
  ) |
    head -n "${1:-10}"
}
alias find_oldest_file='find_oldest_files'

find_newest_files() {
  (
    find -- . \
      -path '*/.git' -prune -o \
      -path '*/.well-known' -prune -o \
      -path '*/Library' -prune -o \
      -path '*/node_modules' -prune -o \
      -path '*/t' -prune -o \
      -path '*/Test*' -prune -o \
      -path '*/test*' -prune -o \
      -path '*/tst*' -prune -o \
      -path '*copilot*' -prune -o \
      -path '*dummy*' -prune -o \
      -path '*vscode*' -prune -o \
      ! -name "$(printf -- 'Icon\015\012')" \
      ! -name '.DS_Store' \
      ! -name 'Desktop.ini' \
      ! -name 'desktop.ini' \
      ! -name 'Thumbs.db' \
      ! -name 'thumbs.db' \
      -type f \
      -exec ls -o -t -- {} + 2>/dev/null &
  ) |
    head -n "${1:-10}"
}
alias \
  find_newest_file='find_newest_files' \
  fnf='find_newest_files'

find_perl_files() {
  # via `find_ruby_files` via `perltidy` 2024-08
  # using 2024-08 `linguist`
  {
    find -- . \
      -path '*/.bundle' -prune -o \
      -path '*/.cabal-sandbox' -prune -o \
      -path '*/.cache' -prune -o \
      -path '*/.cask' -prune -o \
      -path '*/.git' -prune -o \
      -path '*/.hg' -prune -o \
      -path '*/.mypy_cache' -prune -o \
      -path '*/.pytest_cache' -prune -o \
      -path '*/.stack-work' -prune -o \
      -path '*/.svn' -prune -o \
      -path '*/.tox' -prune -o \
      -path '*/.venv' -prune -o \
      -path '*/.well-known' -prune -o \
      -path '*/Library' -prune -o \
      -path '*/node_modules' -prune -o \
      -path '*/t' -prune -o \
      -path '*/Test*' -prune -o \
      -path '*/test*' -prune -o \
      -path '*/tst*' -prune -o \
      -path '*/vendor' -prune -o \
      -path '*copilot*' -prune -o \
      -path '*dummy*' -prune -o \
      -path '*vscode*' -prune -o \
      '(' \
      -name '*.pl' -o \
      -name '*.6[Pp][Ll]' -o \
      -name '*.6[Pp][Mm]' -o \
      -name '*.[Aa][Ll]' -o \
      -name '*.[Cc][Gg][Ii]' -o \
      -name '*.[Ff][Cc][Gg][Ii]' -o \
      -name '*.[Nn][Qq][Pp]' -o \
      -name '*.[Pp][Ee][Rr][Ll]' -o \
      -name '*.[Pp][Hh]' -o \
      -name '*.[Pp][Ll]' -o \
      -name '*.[Pp][Ll]6' -o \
      -name '*.[Pp][Ll][Xx]' -o \
      -name '*.[Pp][Mm]' -o \
      -name '*.[Pp][Mm]6' -o \
      -name '*.[Pp][Oo][Dd]' -o \
      -name '*.[Pp][Oo][Dd]6' -o \
      -name '*.[Pp][Ss][Gg][Ii]' -o \
      -name '*.[Pp]6' -o \
      -name '*.[Pp]6[Ll]' -o \
      -name '*.[Pp]6[Mm]' -o \
      -name '*.[Rr][Aa][Kk][Uu]' -o \
      -name '*.[Rr][Aa][Kk][Uu][Dd][Oo][Cc]' -o \
      -name '*.[Rr][Aa][Kk][Uu][Mm][Oo][Dd]' -o \
      -name '*.[Rr][Aa][Kk][Uu][Tt][Ee][Ss][Tt]' -o \
      -name '*.[Tt]' -o \
      -name '*.[Xx][Ss]' -o \
      -name '.[Ll][Aa][Tt][Ee][Xx][Mm][Kk][Rr][Rr][Cc]' -o \
      -name '[Aa][Cc][Kk]' -o \
      -name '[Cc][Pp][Aa][Nn][Ff][Ii][Ll][Ee]' -o \
      -name '[Ll][Aa][Tt][Ee][Xx][Mm][Kk][Rr][Cc]' -o \
      -name '[Mm][Aa][Kk][Ee][Ff][Ii][Ll][Ee].[Pp][Ll]' -o \
      -name '[Rr][Ee][Xx][Ff][Ii][Ll][Ee]' \
      ')' \
      ! -type d \
      -print \
      2>/dev/null
    {
      utility="$(
        command -v -- github-linguist ||
          command -v -- git-linguist ||
          command -v -- linguist
      )"
      command -v -- "${utility-}" >/dev/null 2>&1 &&
        "${utility-}" --breakdown -- . 2>/dev/null |
        sed \
          -e '# print all lines from Perl: to the last line' \
          -e '1,/^Perl:/ d' \
          -e '# suppress lines after the first blank line' \
          -e '/^$/,$ d' \
          -e '# do not prepend each filename with ./' \
          -e '#        s/^/.\//' &&
        unset utility >/dev/null 2>&1 || utility=''
    } |
      sed \
        -e '# prepend each line with dot slash' \
        -e 's/^/.\//'
  } |
    LANG='C' LC_ALL='C' sort -u |
    LANG='C' LC_ALL='C' sort -f
}

find_animated_png() {
  find -- . \
    -path '*/.git' -prune -o \
    -name '*.[Pp][Nn][Gg]' \
    -type f \
    -exec file -- {} + |
    sed \
      -n \
      -e '/: *PNG .*animated/ {' \
      -e '  s/:.*//p' \
      -e '}'
}
alias find_png_animated='find_animated_png'

find_plist_files() {
  # https://bit.ly/apple_property_list_filename_extensions
  find -- . \
    -path '*/.git' -prune -o \
    -path '*/node_modules' -prune -o \
    '(' \
    -name '*.plist' -o \
    -name '*.[Aa][Aa][Ee]' -o \
    -name '*.[Aa][Pp][Pp][Ee][Xx]' -o \
    -name '*.[Bb][Bb][Cc][Oo][Ll][Oo][Rr][Ss][Cc][Hh][Ee][Mm][Ee]' -o \
    -name '*.[Cc][Aa][Aa][Rr]' -o \
    -name '*.[Cc][Oo][Dd][Ee][Ss][Nn][Ii][Pp][Pp][Ee][Tt]' -o \
    -name '*.[Ee][Nn][Tt][Ii][Tt][Ll][Ee][Mm][Ee][Nn][Tt][Ss]' -o \
    -name '*.[Ff][Ii][Ll][Ee][Ll][Oo][Cc]' -o \
    -name '*.[Gg][Ll][Yy][Pp][Hh][Ss]' -o \
    -name '*.[Ii][Dd][Ee][Kk][Ee][Yy][Bb][Ii][Nn][Dd][Ii][Nn][Gg][Ss]' -o \
    -name '*.[Ii][Nn][Ee][Tt][Ll][Oo][Cc]' -o \
    -name '*.[Ii][Nn][Tt][Ee][Nn][Tt][Dd][Ee][Ff][Ii][Nn][Ii][Tt][Ii][Oo][Nn]' -o \
    -name '*.[Ii][Tt][Ee][Rr][Mm][Cc][Oo][Ll][Oo][Rr][Ss]' -o \
    -name '*.[Ll][Oo][Cc][Tt][Aa][Bb][Ll][Ee]' -o \
    -name '*.[Mm][Oo][Bb][Ii][Ll][Ee][Cc][Oo][Nn][Ff][Ii][Gg]' -o \
    -name '*.[Mm][Oo][Mm]' -o \
    -name '*.[Pp][Ll][Ii][Ss][Tt]' -o \
    -name '*.[Pp][Ll][Ii][Ss][Tt].[Ii][Nn]' -o \
    -name '*.[Ss][Cc][Rr][Ii][Pp][Tt][Ss][Uu][Ii][Tt][Ee]' -o \
    -name '*.[Ss][Tt][Rr][Ii][Nn][Gg][Ss]' -o \
    -name '*.[Ss][Tt][Rr][Ii][Nn][Gg][Ss][Dd][Ii][Cc][Tt]' -o \
    -name '*.[Ss][Tt][Tt][Hh][Ee][Mm][Ee]' -o \
    -name '*.[Tt][Aa][Gg][Pp][Oo][Oo][Ll]' -o \
    -name '*.[Tt][Aa][Gg][Ss][Ee][Tt]' -o \
    -name '*.[Tt][Ee][Xx][Tt][Cc][Ll][Ii][Pp][Pp][Ii][Nn][Gg]' -o \
    -name '*.[Tt][Mm][Cc][Oo][Mm][Mm][Aa][Nn][Dd]' -o \
    -name '*.[Tt][Mm][Ll][Aa][Nn][Gg][Uu][Aa][Gg][Ee]' -o \
    -name '*.[Tt][Mm][Mm][Aa][Cc][Rr][Oo]' -o \
    -name '*.[Tt][Mm][Pp][Rr][Ee][Ff][Ee][Rr][Ee][Nn][Cc][Ee][Ss]' -o \
    -name '*.[Tt][Mm][Ss][Nn][Ii][Pp][Pp][Ee][Tt]' -o \
    -name '*.[Tt][Mm][Tt][Hh][Ee][Mm][Ee]' -o \
    -name '*.[Tt][Tt][Pp][Ss]' -o \
    -name '*.[Ww][Aa][Vv][Ee][Ff][Oo][Rr][Mm]' -o \
    -name '*.[Ww][Ee][Bb][Aa][Rr][Cc][Hh][Ii][Vv][Ee]' -o \
    -name '*.[Ww][Ee][Bb][Ll][Oo][Cc]' -o \
    -name '*.[Ww][Ff][Ll][Oo][Ww]' -o \
    -name '*.[Xx][Cc][Cc][Hh][Ee][Cc][Kk][Oo][Uu][Tt]' -o \
    -name '*.[Xx][Cc][Cc][Oo][Ll][Oo][Rr][Tt][Hh][Ee][Mm][Ee]' -o \
    -name '*.[Xx][Cc][Cc][Uu][Rr][Rr][Ee][Nn][Tt][Vv][Ee][Rr][Ss][Ii][Oo][Nn]' -o \
    -name '*.[Xx][Cc][Pp][Rr][Ii][Vv][Aa][Cc][Yy]' -o \
    -name '*.[Xx][Cc][Ss][Ee][Tt][Tt][Ii][Nn][Gg][Ss]' -o \
    -name '*.[Xx][Cc][Uu][Ss][Ee][Rr][Ss][Tt][Aa][Tt][Ee]' \
    ')' \
    -type f \
    -print 2>/dev/null |
    awk -- 'BEGIN {
  found = 0
}
NF {
  print $0
  found = 1
}
END {
  exit ! found
}'
}

find_powershell_files() {
  find -- . \
    '(' \
    -name '*.ps1' -o \
    -name '*.[Pp][Ss]1' -o \
    -name '*.[Pp][Ss][Dd]1' -o \
    -name '*.[Pp][Ss][Mm]1' -o \
    -name '*.[Pp][Ss][Rr][Cc]' -o \
    -name '*.[Pp][Ss][Ss][Cc]' \
    ')' \
    ! -type d \
    -print 2>/dev/null
}

find_ruby_files() {
  {
    # https://github.com/github-linguist/linguist/blob/2b40a3acbd/lib/linguist/languages.yml#L6022-L6079
    find -- . \
      -path '*/.bundle' -prune -o \
      -path '*/.cabal-sandbox' -prune -o \
      -path '*/.cache' -prune -o \
      -path '*/.cask' -prune -o \
      -path '*/.git' -prune -o \
      -path '*/.hg' -prune -o \
      -path '*/.mypy_cache' -prune -o \
      -path '*/.pytest_cache' -prune -o \
      -path '*/.stack-work' -prune -o \
      -path '*/.svn' -prune -o \
      -path '*/.tox' -prune -o \
      -path '*/.venv' -prune -o \
      -path '*/.well-known' -prune -o \
      -path '*/Library' -prune -o \
      -path '*/node_modules' -prune -o \
      -path '*/t' -prune -o \
      -path '*/Test*' -prune -o \
      -path '*/test*' -prune -o \
      -path '*/tst*' -prune -o \
      -path '*/vendor' -prune -o \
      -path '*copilot*' -prune -o \
      -path '*dummy*' -prune -o \
      -path '*vscode*' -prune -o \
      '(' \
      -name '*.rb' -o \
      -name '.Brewfile' -o \
      -name '.irbrc' -o \
      -name '.pryrc' -o \
      -name '.simplecov' -o \
      -name '*.builder' -o \
      -name '*.eye' -o \
      -name '*.fcgi' -o \
      -name '*.gemspec' -o \
      -name '*.god' -o \
      -name '*.jbuilder' -o \
      -name '*.mspec' -o \
      -name '*.pluginspec' -o \
      -name '*.podspec' -o \
      -name '*.prawn' -o \
      -name '*.rabl' -o \
      -name '*.rake' -o \
      -name '*.rbi' -o \
      -name '*.rbuild' -o \
      -name '*.rbw' -o \
      -name '*.rbx' -o \
      -name '*.ru' -o \
      -name '*.ruby' -o \
      -name '*.spec' -o \
      -name '*.thor' -o \
      -name '*.watchr' -o \
      -name 'Appraisals' -o \
      -name 'Berksfile' -o \
      -name 'Brewfile' -o \
      -name 'buildfile' -o \
      -name 'Buildfile' -o \
      -name 'Capfile' -o \
      -name 'Dangerfile' -o \
      -name 'Deliverfile' -o \
      -name 'Fastfile' -o \
      -name 'Gemfile' -o \
      -name 'Guardfile' -o \
      -name 'Jarfile' -o \
      -name 'Mavenfile' -o \
      -name 'Podfile' -o \
      -name 'Puppetfile' -o \
      -name 'Rakefile' -o \
      -name 'Snapfile' -o \
      -name 'Steepfile' -o \
      -name 'Thorfile' -o \
      -name 'Vagrantfile' \
      ')' \
      ! -type d \
      -print \
      2>/dev/null
    {
      utility="$(
        command -v -- github-linguist ||
          command -v -- git-linguist ||
          command -v -- linguist
      )"
      command -v -- "${utility-}" >/dev/null 2>&1 &&
        "${utility-}" --breakdown -- . 2>/dev/null |
        sed \
          -e '# print all lines from Ruby: to the last line' \
          -e '1,/^Ruby:/ d' \
          -e '# suppress lines after the first blank line' \
          -e '/^$/,$ d' \
          -e '# [do not] prepend each filename with ./' \
          -e '# s/^/.\//' &&
        unset utility >/dev/null 2>&1 || utility=''
      rubocop \
        --list-target-files
    } |
      awk -- '{print "./" $0}'
  } |
    LANG='C' LC_ALL='C' sort -u |
    LANG='C' LC_ALL='C' sort -f
}

find_shell_scripts() {
  git rev-parse >/dev/null 2>&1 || return "${?:-1}"
  CDPATH='.' cd "$(
    git rev-parse --path-format=relative --show-toplevel |
      sed -e '1 q'
  )" >/dev/null 2>&1 ||
    CDPATH='.' cd "$(
      git rev-parse --show-toplevel
    )" >/dev/null 2>&1 ||
    return "${?:-1}"
  # @TODO because this appears to work even outside a Git repository
  # exit 1

  {
    # all files with `linguist` Shell filename extensions
    find -- . \
      -path '*/.git' -prune -o \
      -path '*/node_modules' -prune -o \
      '(' \
      -path '*/etc/profile' -o \
      -path '*/bat/config' -o \
      -name '*.ash' -o \
      -name '*.bash' -o \
      -name '*.bash_aliases' -o \
      -name '*.bash_completions' -o \
      -name '*.bash_functions' -o \
      -name '*.bash_history' -o \
      -name '*.bash_login' -o \
      -name '*.bash_logout' -o \
      -name '*.bash_profile' -o \
      -name '*.bash_variables' -o \
      -name '*.bashrc' -o \
      -name '*.bats' -o \
      -name '*.cgi' -o \
      -name '*.command' -o \
      -name '*.dash' -o \
      -name '*.ebuild' -o \
      -name '*.eclass' -o \
      -name '*.env' -o \
      -name '*.env.ci' -o \
      -name '*.env.dev' -o \
      -name '*.env.development' -o \
      -name '*.env.development.local' -o \
      -name '*.env.example' -o \
      -name '*.env.local' -o \
      -name '*.env.prod' -o \
      -name '*.env.production' -o \
      -name '*.env.sample' -o \
      -name '*.env.staging' -o \
      -name '*.env.template' -o \
      -name '*.env.test' -o \
      -name '*.env.testing' -o \
      -name '*.envrc' -o \
      -name '*.fcgi' -o \
      -name '*.flaskenv' -o \
      -name '*.ksh' -o \
      -name '*.kshrc' -o \
      -name '*.lksh' -o \
      -name '*.login' -o \
      -name '*.logout' -o \
      -name '*.mksh' -o \
      -name '*.pacscript' -o \
      -name '*.pdksh' -o \
      -name '*.profile' -o \
      -name '*.rc' -o \
      -name '*.sbatch' -o \
      -name '*.sh' -o \
      -name '*.sh.in' -o \
      -name '*.slurm' -o \
      -name '*.textmate_init' -o \
      -name '*.tmux' -o \
      -name '*.tmux.conf' -o \
      -name '*.tool' -o \
      -name '*.zlogin' -o \
      -name '*.zlogout' -o \
      -name '*.zprofile' -o \
      -name '*.zsh' -o \
      -name '*.zsh-theme' -o \
      -name '*.zshenv' -o \
      -name '*.zshrc' -o \
      -name '.aliases' -o \
      -name '.xinitrc' -o \
      -name '.xsession' -o \
      -name '9fs' -o \
      -name 'APKBUILD' -o \
      -name 'bash_aliases' -o \
      -name 'bash_functions' -o \
      -name 'bash_login' -o \
      -name 'bash_logout' -o \
      -name 'bash_profile' -o \
      -name 'bashrc' -o \
      -name 'ebuild' -o \
      -name 'eclass' -o \
      -name 'envrc' -o \
      -name 'gradlew' -o \
      -name 'kshrc' -o \
      -name 'login' -o \
      -name 'man' -o \
      -name 'mvnw' -o \
      -name 'os-release' -o \
      -name 'PKGBUILD' -o \
      -name 'profile' -o \
      -name 'tmux.conf' -o \
      -name 'xinitrc' -o \
      -name 'xsession' -o \
      -name 'zlogin' -o \
      -name 'zlogout' -o \
      -name 'zprofile' -o \
      -name 'zshenv' -o \
      -name 'zshrc' \
      ')' \
      -type f \
      -print 2>/dev/null

    # files whose first lines resemble those of shell scripts
    # https://stackoverflow.com/a/9612232
    # https://stackoverflow.com/q/307015#comment14013364_307154
    # https://unix.stackexchange.com/a/480738
    find -- . \
      -path '*/.git' -prune -o \
      -path '*/.well-known' -prune -o \
      -path '*/Library' -prune -o \
      -path '*/node_modules' -prune -o \
      -path '*/t' -prune -o \
      -path '*/Test*' -prune -o \
      -path '*/test*' -prune -o \
      -path '*/tst*' -prune -o \
      -path '*copilot*' -prune -o \
      -path '*dummy*' -prune -o \
      -path '*vscode*' -prune -o \
      -path '*/etc/profile' -prune -o \
      -path '*/bat/config' -prune -o \
      ! -name '*.[Ff][Ii][Ss][Hh]' \
      ! -name '*.[Rr][Ss]' \
      -type f \
      -exec sh -c -- 'for file in "${@}"; do LC_ALL='\''C'\'' sed -e '\''# does the first non-empty line resemble a shell directive?'\'' -e '\''/./,$! d'\'' -e '\''q'\'' -- "${file-}" | grep -e '\''^#!.*bin.*[^c]sh'\'' -e '\''^[[:space:]]*\(function[[:space:]]\)\{0,1\}[[:space:]]*[A-Za-z_][-A-Za-z_0-9]*()[[:space:]]*{.*$'\'' -e '\''autoload'\'' -e '\''compdef'\'' -e '\''openrc'\'' >/dev/null 2>&1 && printf -- '\''%s\n'\'' "${file-}"; done' _ {} +

    ## combine `shfmt -f` and `linguist --breakdown`:
    # - they both require a prepended `./`
    # - send errors for both to `/dev/null` once
    {
      shfmt --find -- .

      # https://github.com/bzz/LangID/blob/37c4960/README.md#collect-the-data
      github-linguist --breakdown -- . | # --json -- . |

        # https://web.archive.org/web/20210904183309id_/earthly.dev/blog/jq-select/#cb22
        # https://github.com/stedolan/jq/issues/1735#issuecomment-427863218
        # jq --raw-output '.Shell.files[]' # |
        sed \
          -e '# print all lines from Shell: to the last line' \
          -e '1,/^Shell:/ d' \
          -e '# suppress lines after the first blank line' \
          -e '/^$/,$ d' \
          -e '# [do not] prepend each filename with ./ because that is done below' \
          -e '# s/^/.\//' \
          -e '# remove only the two leading spaces' \
          -e '# because processing text output may be easier than emulating jq' \
          -e 's/^  //' \
          -e '# until Linguist learns that Fish is not Shell' \
          -e '/\.fish$/ d'
    } 2>/dev/null |

      # prepend filenames with `./`
      awk -- '{print "./" $0}'
    # @TODO!: consider alternatively `sed -e 's/^\(\.\/\)\{0,1\}/.\/&/'` to prepend `./` to each line iff it needs it
    # @TODO!consider additionally `grep -v` to hide unwanted results faster

  } |
    # suppress Fish files,
    # suppress duplicates, and
    # fail if there is no output
    awk -- 'BEGIN {
  found = 0
}
NF && ! seen[$0]++ && ! /\.[Ff][Ii][Ss][Hh]$/ {
  print $0
  found = 1
}
END {
  exit ! found
}'
}

find_smallest_files() {
  (
    find -- . \
      -path '*/.git' -prune -o \
      -path '*/node_modules' -prune -o \
      ! -name '.DS_Store' \
      -type f \
      -exec ls -n -r -S -- {} + 2>/dev/null &
  ) |
    head -n "$((${LINES:-"$(
      tput -- lines 2>/dev/null ||
        printf -- '10 + 2'
    )"} - 3))" "${@}"
}

find_text_files() {
  {
    find -- . \
      -path '*/.git' -prune -o \
      -path '*/.well-known' -prune -o \
      -path '*/Empty*' -prune -o \
      -path '*/Library' -prune -o \
      -path '*/node_modules' -prune -o \
      -path '*/t' -prune -o \
      -path '*/Test*' -prune -o \
      -path '*/test*' -prune -o \
      -path '*/tst*' -prune -o \
      -path '*copilot*' -prune -o \
      -path '*dummy*' -prune -o \
      -path '*vscode*' -prune -o \
      '(' \
      -name '*.txt' -o \
      -name '*.crc32' -o \
      -name '*.fr' -o \
      -name '*.md2' -o \
      -name '*.md4' -o \
      -name '*.md5' -o \
      -name '*.nb' -o \
      -name '*.ncl' -o \
      -name '*.no' -o \
      -name '*.sha1' -o \
      -name '*.sha2' -o \
      -name '*.sha224' -o \
      -name '*.sha256' -o \
      -name '*.sha256sum' -o \
      -name '*.sha3' -o \
      -name '*.sha384' -o \
      -name '*.sha512' -o \
      -name 'CITATION' -o \
      -name 'CITATIONS' -o \
      -name 'cksums' -o \
      -name 'click.me' -o \
      -name 'COPYING' -o \
      -name 'COPYING.regex' -o \
      -name 'COPYRIGHT.regex' -o \
      -name 'delete.me' -o \
      -name 'FONTLOG' -o \
      -name 'INSTALL' -o \
      -name 'INSTALL.mysql' -o \
      -name 'keep.me' -o \
      -name 'LICENSE' -o \
      -name 'LICENSE.mysql' -o \
      -name 'MD5SUMS' -o \
      -name 'NEWS' -o \
      -name 'package.mask' -o \
      -name 'package.use.mask' -o \
      -name 'package.use.stable.mask' -o \
      -name 'read.me' -o \
      -name 'readme.1st' -o \
      -name 'README.me' -o \
      -name 'README.mysql' -o \
      -name 'README.nss' -o \
      -name 'README.pc' -o \
      -name 'SHA1SUMS' -o \
      -name 'SHA256SUMS' -o \
      -name 'SHA512SUMS' -o \
      -name 'test.me' -o \
      -name 'use.mask' -o \
      -name 'use.stable.mask' \
      ')' \
      -type f \
      -print
    # find text files https://stackoverflow.com/a/6419372
    LANG='C' LC_ALL='C' find -- . \
      -path '*/.git' -prune -o \
      -path '*/node_modules' -prune -o \
      -type f \
      -exec file -- {} + |
      awk -F':' -- '$2 ~ /^  *ASCII text$/ {print $1}'
  } 2>/dev/null |
    LANG='C' LC_ALL='C' sort -f |
    awk -- 'BEGIN {
  found = 0
}
NF && ! seen[$0]++ {
  print $0
  found = 1
}
END {
  exit ! found
}'
}

find_video_files() {
  # these are all the extensions of video files supported by Google Drive
  # ∴ that’s everything
  # also includes `eza`’s `Icons::VIDEO`
  find -- . \
    -path '*/.git' -prune -o \
    -path '*/Library' -prune -o \
    -path '*/node_modules' -prune -o \
    '(' \
    -name '*.3[Gg][Pp]' -o \
    -name '*.3[Gg][Pp][Pp]' -o \
    -name '*.[Aa][Vv][Ii]' -o \
    -name '*.[Dd][Ii][Vv]' -o \
    -name '*.[Dd][Ii][Vv][Xx]' -o \
    -name '*.[Ff][Ll][Vv]' -o \
    -name '*.[Hh]264' -o \
    -name '*.[Hh][Ee][Ii][Cc][Ss]' -o \
    -name '*.[Mm]2[Tt][Ss]' -o \
    -name '*.[Mm]2[Vv]' -o \
    -name '*.[Mm]4[Pp]' -o \
    -name '*.[Mm]4[Vv]' -o \
    -name '*.[Mm][Kk][Vv]' -o \
    -name '*.[Mm][Oo][Vv]' -o \
    -name '*.[Mm][Pp]4' -o \
    -name '*.[Mm][Pp][Ee]' -o \
    -name '*.[Mm][Pp][Ee][Gg]' -o \
    -name '*.[Mm][Pp][Ee][Gg]4' -o \
    -name '*.[Mm][Pp][Ee][Gg][Pp][Ss]' -o \
    -name '*.[Mm][Pp][Gg]' -o \
    -name '*.[Mm][Pp][Gg]4' -o \
    -name '*.[Mm][Tt][Ss]' -o \
    -name '*.[Oo][Gg][Mm]' -o \
    -name '*.[Oo][Gg][Vv]' -o \
    -name '*.[Rr][Ee][Cc]' -o \
    -name '*.ts will not always be a video file, but if you are already performing that search, then you want exhaustive results' -o \
    -name '*.[Tt][Ss]' -o \
    -name '*.[Vv][Ii][Dd][Ee][Oo]' -o \
    -name '*.[Vv][Oo][Bb]' -o \
    -name '*.[Ww][Ee][Bb][Mm]' -o \
    -name '*.[Ww][Mm][Vv]' \
    ')' \
    -type f \
    -print 2>/dev/null
}

find_xargs() {
  # https://etalabs.net/sh_tricks.html
  {
    printf -- '#!/usr/bin/env sh\n' >&2
    printf -- '# find | xargs\n' >&2
    printf -- '# https://etalabs.net/sh_tricks.html\n' >&2
    printf -- ' find -- . \\\n' >&2
    printf -- '  # "\044{arguments-}"\n' >&2
    printf -- '  -print 2>&1 | ' >&2
    printf -- 'sed' >&2
    printf -- ' -e \047s/./\\\\&/g\047' >&2
    printf -- ' | ' >&2
    printf -- 'xargs \\\n' >&2
    printf -- '  # "\044{command-}"\n' >&2
  } 2>&1 | {
    bat \
      --decorations=never \
      --language=sh \
      --paging=never \
      -- \
      - 2>/dev/null ||
      cat \
        -- \
        -
  }
}

find_yaml_files() {
  find -- . \
    '(' \
    -name '*.yml' -o \
    -name '*.CFF' -o \
    -name '*.cff' -o \
    -name '*.mir' -o \
    -name '*.reek' -o \
    -name '*.rviz' -o \
    -name '*.sublime-syntax' -o \
    -name '*.syntax' -o \
    -name '*.YAML' -o \
    -name '*.yaml' -o \
    -name '*.yaml-tmlanguage' -o \
    -name '*.yaml.sed' -o \
    -name '*.YML' -o \
    -name '*.yml.mysql' -o \
    -name '.clang-format' -o \
    -name '.clang-tidy' -o \
    -name '.clangd' -o \
    -name '.gemrc' -o \
    -name '.releaserc' -o \
    -name '.yamllint' -o \
    -name 'docker_fish_history' -o \
    -name 'fish_history' -o \
    -name 'glide.lock' -o \
    -name 'pixi.lock' -o \
    -name 'yarn.lock' \
    ')' \
    ! -type d \
    -print \
    2>/dev/null
}

## first
first_word() {
  # print the first word of a string
  # https://unix.stackexchange.com/a/201744
  # much faster than `awk`, `cut`, `sed` (when using the builtin)
  while test "${#}" -gt 0; do
    printf -- '%s\n' "${1%% *}"
    shift 1
  done
}
first_character() {
  while test "${#}" -gt 0; do
    # https://stackoverflow.com/a/27791633
    printf -- '%.1s\n' "${1-}"
    shift 1
  done
}

fish_r() {
  command -v -- fish_indent >/dev/null 2>&1 ||
    # EX_UNAVAILABLE
    return 69
  PS4=' ' find -- . \
    -name '*.fish' \
    -type f \
    -exec sh -x -c -- 'for file in "${@}"; do
git ls-files --error-unmatch -- "${file-}" >/dev/null 2>&1 ||
  ! git rev-parse --is-inside-work-tree >/dev/null 2>&1 &&
  fish_indent --write -- "${file-}"
done' _ {} +
}

flawfinder_r() {
  command -v -- flawfinder >/dev/null 2>&1 ||
    # EX_UNAVAILABLE
    return 69
  find -- . \
    -path '*/.git' -prune -o \
    -path '*/.rbenv' -prune -o \
    -path '*/.venv' -prune -o \
    -path '*/.well-known' -prune -o \
    -path '*/__pycache__' -prune -o \
    -path '*/Library' -prune -o \
    -path '*/node_modules' -prune -o \
    -path '*/t' -prune -o \
    -path '*/Test*' -prune -o \
    -path '*/test*' -prune -o \
    -path '*/tst*' -prune -o \
    -path '*copilot*' -prune -o \
    -path '*dummy*' -prune -o \
    -path '*vscode*' -prune -o \
    '(' \
    -name '*.ada' -o \
    -name '*.adb' -o \
    -name '*.ads' -o \
    -name '*.asm' -o \
    -name '*.ast' -o \
    -name '*.bc' -o \
    -name '*.C' -o \
    -name '*.C.in' -o \
    -name '*.c' -o \
    -name '*.c.in' -o \
    -name '*.C++' -o \
    -name '*.c++' -o \
    -name '*.c++m' -o \
    -name '*.cake' -o \
    -name '*.cats' -o \
    -name '*.CC' -o \
    -name '*.cc' -o \
    -name '*.cc.in' -o \
    -name '*.ccm' -o \
    -name '*.cl' -o \
    -name '*.clcpp' -o \
    -name '*.cp' -o \
    -name '*.CPP' -o \
    -name '*.cpp' -o \
    -name '*.CPP.in' -o \
    -name '*.cpp.in' -o \
    -name '*.cppm' -o \
    -name '*.CS' -o \
    -name '*.cs' -o \
    -name '*.csx' -o \
    -name '*.cu' -o \
    -name '*.cuh' -o \
    -name '*.cui' -o \
    -name '*.CXX' -o \
    -name '*.cxx' -o \
    -name '*.CXX.in' -o \
    -name '*.cxx.in' -o \
    -name '*.cxxm' -o \
    -name '*.ec' -o \
    -name '*.ecp' -o \
    -name '*.edc' -o \
    -name '*.F' -o \
    -name '*.f' -o \
    -name '*.F03' -o \
    -name '*.f03' -o \
    -name '*.F08' -o \
    -name '*.f08' -o \
    -name '*.F77' -o \
    -name '*.f77' -o \
    -name '*.F90' -o \
    -name '*.f90' -o \
    -name '*.F95' -o \
    -name '*.f95' -o \
    -name '*.FOR' -o \
    -name '*.for' -o \
    -name '*.FPP' -o \
    -name '*.fpp' -o \
    -name '*.gch' -o \
    -name '*.gml' -o \
    -name '*.H' -o \
    -name '*.h' -o \
    -name '*.H.in' -o \
    -name '*.h.in' -o \
    -name '*.h++' -o \
    -name '*.hh' -o \
    -name '*.hh.in' -o \
    -name '*.hip' -o \
    -name '*.hlsl' -o \
    -name '*.HP' -o \
    -name '*.hp' -o \
    -name '*.HPP' -o \
    -name '*.hpp' -o \
    -name '*.HPP.in' -o \
    -name '*.hpp.in' -o \
    -name '*.hxx' -o \
    -name '*.hxx.in' -o \
    -name '*.i' -o \
    -name '*.idc' -o \
    -name '*.ifs' -o \
    -name '*.ii' -o \
    -name '*.iih' -o \
    -name '*.iim' -o \
    -name '*.inc' -o \
    -name '*.inl' -o \
    -name '*.ino' -o \
    -name '*.ipp' -o \
    -name '*.ixx' -o \
    -name '*.jav' -o \
    -name '*.java' -o \
    -name '*.jsh' -o \
    -name '*.lib' -o \
    -name '*.linq' -o \
    -name '*.ll' -o \
    -name '*.M' -o \
    -name '*.m' -o \
    -name '*.metal' -o \
    -name '*.mi' -o \
    -name '*.mii' -o \
    -name '*.MM' -o \
    -name '*.mm' -o \
    -name '*.nut' -o \
    -name '*.pcc' -o \
    -name '*.pch' -o \
    -name '*.pcm' -o \
    -name '*.pfo' -o \
    -name '*.pgc' -o \
    -name '*.protodevel' -o \
    -name '*.re' -o \
    -name '*.S' -o \
    -name '*.s' -o \
    -name '*.tcc' -o \
    -name '*.td' -o \
    -name '*.tlh' -o \
    -name '*.tli' -o \
    -name '*.tpp' -o \
    -name '*.ts' -o \
    -name '*.cts' -o \
    -name '*.mts' -o \
    -name '*.tsx' -o \
    -name '*.txx' -o \
    -name '*.xbm' -o \
    -name '*.xpm' \
    ')' \
    -type f \
    -exec sh -x -c -- 'for file in "${@}"; do
  git ls-files --error-unmatch -- "${file-}" >/dev/null 2>&1 ||
    ! git rev-parse --is-inside-work-tree >/dev/null 2>&1 &&
    flawfinder --error-level=1 --minlevel=0 -- "${file-}"
done' _ {} +
}

## font
font_bold() {
  { { test "${#}" -eq 0 && cat -- -; } || printf -- '%s' "${*-}"; } |
    IFS='' LANG='C' LC_ALL='C' tr \
      -- \
      'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz ' \
      '𝗔𝗕𝗖𝗗𝗘𝗙𝗚𝗛𝗜𝗝𝗞𝗟𝗠𝗡𝗢𝗣𝗤𝗥𝗦𝗧𝗨𝗩𝗪𝗫𝗬𝗭𝗮𝗯𝗰𝗱𝗲𝗳𝗴𝗵𝗶𝗷𝗸𝗹𝗺𝗻𝗼𝗽𝗾𝗿𝘀𝘁𝘂𝘃𝘄𝘅𝘆𝘇 ' &&
    printf -- '\n' >&2
}
alias bold='font_bold'
font_italic() {
  { { test "${#}" -eq 0 && cat -- -; } || printf -- '%s' "${*-}"; } |
    IFS='' LANG='C' LC_ALL='C' tr \
      -- \
      'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz ' \
      '𝘈𝘉𝘊𝘋𝘌𝘍𝘎𝘏𝘐𝘑𝘒𝘓𝘔𝘕𝘖𝘗𝘘𝘙𝘚𝘛𝘜𝘝𝘞𝘟𝘠𝘡𝘢𝘣𝘤𝘥𝘦𝘧𝘨𝘩𝘪𝘫𝘬𝘭𝘮𝘯𝘰𝘱𝘲𝘳𝘴𝘵𝘶𝘷𝘸𝘹𝘺𝘻 ' &&
    printf -- '\n' >&2
}
alias italic='font_italic'

## GIF
to_gif() {
  test "${#}" -gt 0 ||
    # EX_USAGE
    return 64
  set \
    -o noclobber \
    -o noglob \
    -o verbose \
    -o xtrace
  for file in "${@}"; do
    ffmpeg \
      -ss 0 \
      -i "${file-}" \
      -vf 'scale='"$(exiftool -ImageWidth -short -short -short -- "${file-}")"':-1:flags=lanczos' \
      -loop 0 \
      -- \
      "${file%.*}"'.gif'
  done
  {
    set \
      +o noclobber \
      +o noglob \
      +o verbose \
      +o xtrace
  } 2>/dev/null
}
gif_webp_r() {
  test "${#}" -gt 0 ||
    # EX_USAGE
    return 64
  set \
    -o noclobber \
    -o noglob \
    -o verbose \
    -o xtrace
  for file in "${@}"; do
    gif2webp \
      -q 100 \
      -m 6 \
      -metadata all \
      -loop_compatibility \
      -mt \
      -v \
      "${file-}" \
      -o "${file-}"'.webp'
  done
  {
    set \
      +o noclobber \
      +o noglob \
      +o verbose \
      +o xtrace
  } 2>/dev/null
}

# Git
alias g >/dev/null 2>&1 &&
  unalias -- g
# https://github.com/zph/dotfiles/blob/735c49534e/home/dot_zsh.d/git.zsh
command -v -- _git >/dev/null 2>&1 &&
  compdef -- g='git' >/dev/null 2>&1 &&
  compdef _git gm='git-merge' >/dev/null 2>&1 &&
  compdef _git gd='git-diff' >/dev/null 2>&1 &&
  compdef _git gds='git-diff' >/dev/null 2>&1
g() {
  case "${1-}" in
  clone | config | help | init | version | -*)
    git "${@}"
    ;;
  *)
    git rev-parse --is-inside-work-tree >/dev/null 2>&1 ||
      return "${?:-1}"
    # if first argument is a file, then perform `git status` on it
    if test -e "${1-}"; then
      git status -- "${@}"
    else
      git -c color.status=always -c core.quotePath=false "${@:-status}" |
        sed -e '$ d'
    fi
    ;;
  esac
}
alias \
  g.='git -c color.status=auto -c core.quotePath=false status .' \
  gss='git -c color.status=auto -c core.quotePath=false status --porcelain=v1'
guo() {
  git -c color.status=always -c core.quotePath=false status --untracked-files=no |
    sed -e '$ d'
}

# git add
git_add() {
  case "${1-}" in
  -p | --patch)
    shift 1
    git add --verbose --patch "${@:-.}"
    ;;
  -A | --all)
    # to prevent data loss as much as possible,
    # first add non-repository files
    git_add --others &&
      # then add modified files
      git_add --modified &&
      shift 1
    ;;
  -D | --deleted)
    # https://gist.github.com/8775224
    git ls-files -z --deleted |
      LANG='C' LC_ALL='C' tr -- '\0' '\n' |
      while IFS='' read -r -- file; do
        # `git-rm`(1) instead of `git-add`(1) for fewer errors and because
        # there is no risk of losing files that are indexed but already removed
        git rm -- "${file-}"
      done &&
      shift 1
    ;;
  -m | --modified | --update)
    shift 1 &&
      git add --update --verbose -- "${@:-.}"
    ;;
  -o | --others | --untracked)
    while test "$(git ls-files -z --exclude-standard --others)" != ''; do
      git ls-files -z --exclude-standard --others |
        LANG='C' LC_ALL='C' tr -- '\0' '\n' |
        while IFS='' read -r -- file; do
          git add --verbose -- "${file-}"
        done
    done &&
      shift 1
    ;;
  '')
    git add --verbose --patch -- .
    ;;
  *)
    # do not default to everything in the current directory and below
    git add --verbose "${@}"
    ;;
  esac &&
    git -c color.status=always -c core.quotePath=false status --untracked-files=no |
    sed -e '$ d'
}
alias \
  ga='git_add' \
  gaa='git_add --all' \
  gaaa='git_add --all --force' \
  gaf='git_add --force' \
  gao='git_add --others' \
  gap='git_add --patch' \
  gpa='gap' \
  gau='git_add --modified' \
  git_add_deleted='git_add --deleted' \
  git_add_modified='git_add --modified' \
  git_add_others='git_add --others' \
  git_add_patch='git_add --patch' \
  git_add_untracked='git_add --others' \
  git_rm_missing_files='git_add --deleted'

git_all_files_ever() {
  # list all files that ever existed in the repository
  # inspiration: https://gist.github.com/8775224
  # -A: all added
  # -a: all not added
  # -B: all broken
  # -b: all not broken
  # -C: all copied
  # -c: all not copied
  # -D: all deleted
  # -d: all not deleted
  # -M: all modified
  # -m: all not modified
  # -R: all renamed
  # -r: all not renamed
  # -T: all type changed
  # -t: all type not changed
  # -U: all unmerged
  # -u: all not unmerged
  # -X: all unknown
  # -x: all not unknown
  git -c core.quotePath=false log \
    --all \
    --diff-filter="${1-}" \
    --find-copies \
    --find-renames \
    --format='' \
    --name-only |
    # print only unique, non-blank entries and prepend them with dot-slash
    awk -- '! seen[$0]++ && $0 != "" {print "./" $0}' |
    LANG='C' LC_ALL='C' sort -f
}

git_attic() {
  # git-attic [-M] [PATH] - list deleted files of Git repositories
  # https://web.archive.org/web/0id_/chneukirchen.org/dotfiles/bin/git-attic
  # Use `-M` to hide renamed files, and other git-log(1) options as you like.
  # The output is designed to be copied and pasted: Pass the second field to
  # git show to display the file contents, or just select the hash without ^ to
  # see the commit where removal happened
  git -c core.quotePath=false log \
    --date=short \
    --diff-filter=D \
    --format='%h %cd' \
    --no-renames \
    --raw \
    -- \
    "${@}" |
    awk -- 'BEGIN {
  found = 0
}
/^[[:xdigit:]]/ {
  commit = $1
  date = $2
}
/^:/ && $5 == "D" {
  filename = substr($0, index($0, $6))
  print date, commit "\047^\047:\047./" filename "\047"
  found = 1
}
END {
  exit ! found
}'
}

# git blame
alias gblame='git blame'

alias \
  gba='git branch --all' \
  gbD='git branch --delete --force'

git_branches_by_date() {
  git for-each-ref --format='%(committerdate:format:%F) %(refname:short)' refs/heads |
    LANG='C' LC_ALL='C' sort -n
  printf -- '\n ———\n\n' >&2
  git for-each-ref --format='%(committerdate:format:%F) %(refname:short)' refs/remotes |
    LANG='C' LC_ALL='C' sort -n
}

# git checkout more safely
gco() {
  case "${1-}" in
  '.')
    number_of_changed_files="$(
      git -c core.ignoreCase=false -c core.quotePath=false status \
        -z \
        --ignore-submodules \
        --porcelain=v2 \
        --untracked-files=no |
        IFS='' LANG='C' LC_ALL='C' tr -- '\0' '\n' |
        grep \
          -c \
          -e '^1 \.D ' \
          -e '^1 \.M ' \
          -e '^1 \.T '
    )"
    if test "${number_of_changed_files:-5}" -ge 5; then
      printf -- 'warning: too many modified files; check them out atomically\n' >&2
      unset number_of_changed_files >/dev/null 2>&1 || number_of_changed_files=''
      return 1
    elif test "${number_of_changed_files:-5}" -ge 0 &&
      test "${number_of_changed_files:-5}" -le 5; then
      git checkout --progress "${@}"
    else
      unset number_of_changed_files >/dev/null 2>&1 || number_of_changed_files=''
      return 65
    fi
    ;;
  *)
    unset number_of_changed_files >/dev/null 2>&1 || number_of_changed_files=''
    git checkout --progress "${@}"
    ;;
  esac
  unset number_of_changed_files >/dev/null 2>&1 || number_of_changed_files=''
}

# `git checkout` the default branch
alias gcom='git checkout --progress "$(git-default-branch)"'

# git cherry-pick
alias \
  gcp='git cherry-pick' \
  gcpa='git cherry-pick --abort' \
  gcpc='git cherry-pick --continue' \
  gcpn='git cherry-pick --no-commit'

# git clone
git_clone() {
  case "${1-}" in
  -h | --help)
    printf -- 'Usage: git_clone <git_url> [<dir_name>]\n' >&2
    ;;
  -1 | --shallow)
    shift 1
    { mkdir "${2:-$(basename -- "${1-}" .git)}" >/dev/null 2>&1 || return 73; } &&
      printf -- 'moving into %s...\n' "${2:-$(basename -- "${1-}" .git)}" >&2 &&
      CDPATH='.' cd "${2:-$(basename -- "${1-}" .git)}" >/dev/null 2>&1 &&
      # using `--quiet` plus `--progress` to
      # hide the surprising the `Cloning into '.'...`
      git -c core.ignoreCase=false clone --depth 1 --progress --quiet --shallow-submodules --template='' -- "${1%.git}" "${PWD%/}"
    ;;
  -b | --branches)
    git branch --remotes |
      awk -- 'NF == 1 {print $1}' |
      while IFS='' read -r -- remote_branch; do
        git branch --list |
          # emulate non-standard `grep -q -w`
          awk -vremote_branch="${remote_branch##*/}" -- 'BEGIN {found = 0} $NF == remote_branch {found = 1} END {exit ! found}' ||
          git branch --track "${remote_branch##*/}" "${remote_branch-}"
      done
    ;;
  *)
    { mkdir "${2:-$(basename -- "${1-}" .git)}" >/dev/null 2>&1 || return 73; } &&
      printf -- 'moving into %s...\n' "${2:-$(basename -- "${1-}" .git)}" >&2 &&
      CDPATH='.' cd "${2:-$(basename -- "${1-}" .git)}" >/dev/null 2>&1 &&
      git -c core.ignoreCase=false clone --progress --recursive --template='' -- "${1%.git}" "${PWD%/}"
    ;;
  esac
}
alias \
  gcl='git_clone' \
  gcl1='git_clone -1'

# git commit
git_commit() {
  case "${1-}" in
  --amend | '')
    ### does `--signoff` obviate the need for `--trailer`? 2024-02-02
    ### git commit ### --signoff ### --verbose \
    git commit \
      --verbose \
      --trailer='Signed-off-by: '"$(git config --get -- user.name)"' <'"$(git config --get -- user.email)"'>' \
      "${@}" ||
      # ancient git cannot do trailer
      git commit \
        --signoff \
        --verbose \
        "${@}" ||
      return 3
    ;;
  --count)
    # https://github.com/unixorn/git-extra-commands/commit/87fc4b2cac
    git rev-list --all "${@}" &&
      return
    ;;
  *)
    git commit \
      --signoff \
      --verbose \
      -m "${@}" \
      --message="${IFS-}" \
      --message="$(printf -- '%s\n' "${IFS-}")" ||
      return 5
    ;;
  esac
  git -c color.status=always -c core.quotePath=false status --untracked-files=no |
    sed -e '$ d'
}
alias \
  gc='git_commit' \
  gca='git_commit --amend' \
  git_commit_count='git_commit --count'

git_config_file_locations() {
  for scope in system global local worktree command; do
    # do not return `.git/config` if called from outside a git repository
    test "$(git config --list --show-scope --"${scope-}" 2>/dev/null)" = '' ||
      printf -- '%-9s%s\n' "${scope-}" "$(
        git config --list --show-origin --"${scope-}" 2>/dev/null |
          sed \
            -e 's|file:||' \
            -e 's|\t.*||' \
            -e 's|^\.|./.|' \
            -e 's|'"${custom-}"'|$\custom|' \
            -e 's|'"${DOTFILES-}"'|$\DOTFILES|' \
            -e 's|'"${XDG_CONFIG_HOME-}"'|$\XDG_CONFIG_HOME|' \
            -e 's|'"${HOME%/}"'|~|' |
          LANG='C' LC_ALL='C' sort -u
      )"
  done
}

alias gdb >/dev/null 2>&1 &&
  unalias -- gdb
gdb() {
  (
    set \
      -o verbose \
      -o xtrace
    printf -- 'main\nmaster\ntrunk\nHEAD\nmainline\ndefault\ndevelopment\n' | while IFS='' read -r -- branch; do
      {
        test "$(git branch --list -- "${branch-}")" != '' &&
          printf -- '%s\n' "${branch-}" &&
          return 0
      } || {
        printf -- 'error\n' >&2
        return 1
      }
    done
  )
}

alias gd >/dev/null 2>&1 &&
  unalias -- gd
gd() {
  if test "$(git diff --shortstat "${@}" 2>/dev/null)" != ''; then
    git -c core.quotePath=false diff --color-words --word-diff "${@}"
  else
    git -c core.quotePath=false diff --cached --color-words --word-diff "${@}"
  fi
}
alias gds >/dev/null 2>&1 &&
  unalias -- gds
gds() {
  if test "$(git diff --cached --shortstat "${@}" 2>/dev/null)" != ''; then
    git -c core.quotePath=false diff --cached --color-words --word-diff "${@}"
  else
    git -c core.quotePath=false diff --color-words --word-diff "${@}"
  fi
}
git_diff_with_filesizes() {
  {
    test "$(git diff --stat "${@}")" != '' &&
      git -c core.quotePath=false diff --stat "${@}"
  } ||
    git -c core.quotePath=false diff --cached --stat "${@}"
}
git_diff_staged_with_filesizes() {
  {
    test "$(git diff --cached --stat "${@}")" != '' &&
      git -c core.quotePath=false diff --cached --stat "${@}"
  } ||
    git -c core.quotePath=false diff --stat "${@}"
}

alias gdm='git -c core.quotePath=false diff "$(git-default-branch)" --'
gdom() {
  git -c core.quotePath=false diff "$(git config --get branch."$(git symbolic-ref --quiet --short HEAD -- 2>/dev/null)".remote || git branch --list --remotes | sed -n -e 's/^[[:space:]]*\([^[:space:]]*\)\/HEAD -> [^[:space:]]*$/\1/p')"/"$(git-default-branch)" "${@}"
}
gdmom() {
  git -c core.quotePath=false diff "$(git-default-branch)" "$(git config --get branch."$(git symbolic-ref --quiet --short HEAD -- 2>/dev/null)".remote || git remote --verbose | grep -e ' (push)$' | awk -- '{print $0}' | sed -e '1 q')"/"$(git-default-branch)" "${@:---}"
}

gf() {
  git fetch \
    --all \
    --keep \
    --multiple \
    --progress \
    --prune \
    --verbose \
    "${@}"
}
gfgs() {
  git fetch \
    --all \
    --keep \
    --multiple \
    --progress \
    --prune \
    --verbose \
    "${@}" &&
    git -c color.status=always -c core.quotePath=false status --untracked-files=no |
    sed -e '$ d'
}

# git parents, git child
git_find_child() {
  # return the commit hash that occurred after the given one (default current)
  # usage: git_find_child [<commit>]
  git rev-list --ancestry-path "${1:-HEAD}".."$(git-default-branch)" |
    tail -n 1
}
git_find_parent() {
  # return the hash prior to the current commit
  # if an argument is provided, return the commit prior to that commit
  # usage: git_find_parent [<commit>]
  git rev-list --max-count=1 "${1:-"$(git rev-parse HEAD)"}"'^' --
}
git_find_parents() {
  # return all hashes prior to the current commit
  # if an argument is provided, return all commits prior to that commit
  # usage: git_find_parents [<commit>]
  git rev-list "${1:-"$(git rev-parse HEAD)"}"'^' --
}
alias \
  git_parent='git_find_parent' \
  gfp='git_find_parent' \
  gfc='git_find_child' \
  git_parents='git_find_parents'

git_find_deleted_string() {
  test "${#}" -gt 0 ||
    # EX_USAGE
    return 64
  # https://stackoverflow.com/a/12591569
  git log --cc -S"${1-}" "${2:-.}"
}
alias git_find_deleted_text='git_find_deleted_string'

git_garbage_collection() {
  if git rev-parse --is-inside-work-tree >/dev/null 2>&1; then
    # see `git gc` and other wrapping commands behind-the-scene mechanics
    # https://github.com/git/git/blob/49eb8d3/contrib/examples/README#L14-L16
    GIT_TRACE=1 GIT_TRACE_PACK_ACCESS=1 GIT_TRACE_PACKET=1 GIT_TRACE_PERFORMANCE=1 GIT_TRACE_SETUP=1 \
      git fetch \
      --prune \
      --verbose
    GIT_TRACE=1 GIT_TRACE_PACK_ACCESS=1 GIT_TRACE_PACKET=1 GIT_TRACE_PERFORMANCE=1 GIT_TRACE_SETUP=1 \
      git reflog expire \
      --all \
      --expire-unreachable=now
    GIT_TRACE=1 GIT_TRACE_PACK_ACCESS=1 GIT_TRACE_PACKET=1 GIT_TRACE_PERFORMANCE=1 GIT_TRACE_SETUP=1 \
      git prune \
      --expire=now \
      --progress \
      --verbose
    GIT_TRACE=1 GIT_TRACE_PACK_ACCESS=1 GIT_TRACE_PACKET=1 GIT_TRACE_PERFORMANCE=1 GIT_TRACE_SETUP=1 \
      git prune-packed
    GIT_TRACE=1 GIT_TRACE_PACK_ACCESS=1 GIT_TRACE_PACKET=1 GIT_TRACE_PERFORMANCE=1 GIT_TRACE_SETUP=1 \
      git repack \
      -a \
      -d \
      -F \
      -f \
      --depth=4095 \
      --window="$(getconf -- UINT_MAX)"
    GIT_TRACE=1 GIT_TRACE_PACK_ACCESS=1 GIT_TRACE_PACKET=1 GIT_TRACE_PERFORMANCE=1 GIT_TRACE_SETUP=1 \
      git gc \
      --aggressive \
      --prune=now
    git maintenance start >/dev/null 2>&1 &&
      GIT_TRACE=1 GIT_TRACE_PACK_ACCESS=1 GIT_TRACE_PACKET=1 GIT_TRACE_PERFORMANCE=1 GIT_TRACE_SETUP=1 \
        git maintenance run \
        --task gc \
        --task loose-objects \
        --task incremental-repack \
        --task pack-refs
    git maintenance unregister --force >/dev/null 2>&1
    set \
      -o verbose \
      -o xtrace
    command -v -- cleanup >/dev/null 2>&1 &&
      cleanup
    command -v -- dss >/dev/null 2>&1 &&
      dss
    {
      set \
        +o verbose \
        +o xtrace
    } 2>/dev/null
    git -c color.status=always -c core.quotePath=false status --untracked-files=no |
      sed -e '$ d'
  else
    return "${?:-1}"
  fi
}
alias ggc='git_garbage_collection'

## initial commits
# find initial commit
git_find_initial_commit() {
  git rev-list --max-parents=0 HEAD --
}
alias gic='git_find_initial_commit'

# commit initial commit
git_commit_initial_commit() {
  # usage: git_commit_initial_commit [yyyy-mm-dd[Thh:mm:ss]]]
  # create initial commits: one empty root, then the rest
  # https://news.ycombinator.com/item?id=25515963
  git \
    -c init.defaultBranch=main \
    -c core.ignoreCase=false \
    init \
    --template='' &&
    if test "${#}" -eq 1; then
      # @TODO!: permit BSD date if GNU fails
      gdate="$(
        command -v -- "${HOMEBREW_PREFIX-}"'/opt/uutils-coreutils/libexec/uubin/date' ||
          command -v -- udate ||
          command -v -- "${HOMEBREW_PREFIX-}"'/opt/coreutils/libexec/gnubin/date' ||
          command -v -- gdate ||
          command -v -- date ||
          date
      )"
      export gdate
      git_time="$(LANG='C' LC_ALL='C' gdate -d '@'"$(($(LANG='C' LC_ALL='C' gdate -d "${1:-$(LANG='C' LC_ALL='C' gdate -- '+%Y-%m-%d')}" -- '+%s')))" -- '+%c %z')"
      export GIT_AUTHOR_DATE="${git_time-}"
      export GIT_COMMITTER_DATE="${git_time-}"
    fi
  # create empty root commit
  git commit --allow-empty --signoff --verbose --message="$(printf -- '\360\237\214\263\302\240 root commit')" &&
    # ...and add a signed v0.0.0 tag to it
    git tag --annotate --sign "${2:-v0.0.0}" --message='' &&
    # ...and if there are files present, then add them...
    git add --verbose -- . &&
    # ...and commit them
    git commit --signoff --verbose --message="$(printf -- '\342\234\250\302\240 initial commit')" &&
    # ...and add a signed v0.0.1 tag
    git tag --annotate --sign "${3:-v0.0.1}" --message=''
  unset gdate >/dev/null 2>&1 || gdate=''
  unset git_time >/dev/null 2>&1 || git_time=''
  # unset GIT_AUTHOR_DATE >/dev/null 2>&1 || GIT_AUTHOR_DATE=''
  # unset GIT_COMMITTER_DATE >/dev/null 2>&1 || GIT_COMMITTER_DATE=''
}
alias \
  gcic='git_commit_initial_commit' \
  ginit='git -c init.defaultBranch=main init --template='\'''\'' && git status'

# git ls
alias gls >/dev/null 2>&1 &&
  unalias -- gls
gls() {
  {
    if git rev-parse --is-inside-work-tree >/dev/null 2>&1; then
      git -c core.quotePath=false ls-files "${@}" |
        awk -- '{print "./" $0}'
    elif command -v -- eza >/dev/null 2>&1; then
      eza \
        --all \
        --classify \
        --color=always \
        --color-scale=all \
        --git \
        --icons \
        --no-permissions \
        --no-user \
        --octal-permissions \
        --oneline \
        --time-style=long-iso \
        "${@}"
    else
      ls -1 "${@}"
    fi
  } |
    LANG='C' LC_ALL='C' sort -f
}

git_ls_modified() {
  git ls-files --deduplicate | while IFS='' read -r -- file; do
    git --no-pager log \
      --date=local \
      --max-count=1 \
      --format='%ai%x09./'"${file-}" \
      -- \
      "${file-}"
  done
  # https://gist.github.com/8775224
  git ls-tree --name-only HEAD -- . | while IFS='' read -r -- file; do
    printf -- '%s\t./%s\n' "$(git log --format='%ci' --max-count=1 -- "${file-}")" "${file-}"
  done
}

#########
# git log
alias \
  glog='git log --all --decorate --graph --oneline' \
  glod='git log --all --decorate --graph --oneline --format='\''%C(yellow bold)%h%Creset%C(auto)%d%Creset %s %Cgreen%ad%Creset'\'' --date=short'
glof() {
  test "${#}" -gt 0 ||
    # EX_USAGE
    return 64
  for file in "${@}"; do
    # follow files even in other directories
    git -C "$(realpath -- "$(dirname -- "${file-}")")" log --all --decorate --oneline --follow -- "$(realpath -- "${file-}")" 2>/dev/null ||
      git -C "${file%/*}" log --all --decorate --oneline --follow -- "${file-}" 2>/dev/null ||
      git -C "$(dirname -- "${file-}")" log --all --decorate --oneline --follow -- "${file-}"
  done
}
# git log
#########

# git mailmap
git_mailmap() {
  git log --format='%an <%ae>%n%cn <%ce>' |
    LANG='C' LC_ALL='C' sort |
    uniq -c |
    LANG='C' LC_ALL='C' sort -n -r |
    sed \
      -e 's/^[[:space:]]*[1-9][[:digit:]]*[[:space:]]*//' \
      -e 's/\[bot\] / /' \
      -e 's/github-actions /GitHub /'
  # overline
  printf -- '\342\200\276\342\200\276\342\200\276\342\200\276\342\200\276\n' >&2
  git shortlog --all --email --numbered --summary |
    sed \
      -e 's/^[[:space:]]*[1-9][[:digit:]]*[[:space:]]*//' \
      -e 's/\[bot\] / /' \
      -e 's/github-actions /GitHub /'
  printf -- '\342\200\276\342\200\276\342\200\276\342\200\276\342\200\276\n' >&2
  printf -- 'https://gist.github.com/fcea3c4301ec5100460ac571a5fe99c4\n' >&2
}

# git merge
alias gm >/dev/null 2>&1 &&
  unalias -- gm
# https://github.com/alexsanford/config/blob/1f917be788/zsh_aliases#L46
gm() {
  # https://news.ycombinator.com/item?id=5512864
  git merge --no-ff --log --overwrite-ignore --progress --rerere-autoupdate --signoff --strategy-option=patience --verbose "${@}" ||
    git merge "${@}"
}
alias \
  gma='git merge --abort' \
  gmc='git merge --continue'

# git merge with default branch
gmm() {
  git merge --no-ff --log --overwrite-ignore --progress --rerere-autoupdate --signoff --strategy-option=patience --verbose "$(git-default-branch)"
}
# git move
git_move() {
  if git mv --force --verbose "${@}" 2>/dev/null; then
    git -c color.status=always -c core.quotePath=false status --untracked-files=no |
      sed -e '$ d'
  elif mv -i "${@}"; then
    return 0
  else
    return 1
  fi
}
alias gmv='git_move'

gopen() {
  case "${1-}" in
  --)
    shift 1
    ;;
  -d | --dependabot)
    url="$(
      printf -- '%s/network/updates#dependabot-updates\n' "$(
        git open --print |
          cut -d '/' -f -5
      )"
    )"
    ;;
  -c | --commit | -i | --issue | -s | --suffix | -p | --print)
    git open "${@}"
    ;;
  *)
    url="$(git open --print "${@}" 2>/dev/null)"
    ;;
  esac
  # https://github.com/travis-ci/travis-build/blob/5f10098/lib/travis/build/bash/travis_setup_env.bash#L22-L38
  case "$(uname | LANG='C' LC_ALL='C' tr -- '[:upper:]' '[:lower:]')" in
  darwin*)
    # MacOS
    open -- "${url-}"
    ;;
  msys*)
    # Git-Bash on Windows
    Start-Process "${url-}"
    ;;
  *microsoft*)
    # Windows Subsystem for Linux
    powershell.exe -c 'Start-Process "'"${url-}"'"' 2>/dev/null ||
      powershell -c 'Start-Process "'"${url-}"'"' 2>/dev/null ||
      pwsh.exe -c 'Start-Process "'"${url-}"'"' 2>/dev/null ||
      pwsh -c 'Start-Process "'"${url-}"'"'
    ;;
  *)
    # fallback to Linux `xdg-open`
    xdg-open -- "${url-}" 2>/dev/null ||
      xdg-open "${url-}"
    ;;
  esac
}
alias gopend='gopen --dependabot'

# git pull
git_pull() {
  # https://github.com/ohmyzsh/ohmyzsh/commit/3d2542f
  {
    git pull --all --autostash --ff-only --gpg-sign --log --progress --prune --rebase --signoff --verbose --verify "${@}"
  } || {
    git rebase --abort 2>/dev/null
    git pull --all --autostash --ff --gpg-sign --log --progress --prune --rebase --signoff --verbose --verify "${@}"
  } || {
    git rebase --abort 2>/dev/null
    git pull --all --autostash --gpg-sign --log --progress --prune --rebase --signoff --verbose --verify "${@}"
  } || {
    git rebase --abort 2>/dev/null
    git pull --all --autostash --prune --rebase --verbose "${@}"
  } || {
    git rebase --abort 2>/dev/null
    git pull --autostash --prune --rebase --verbose "${@}"
  } || {
    git rebase --abort 2>/dev/null
    git rebase --strategy-option=theirs --update-refs
  } || {
    git rebase --abort 2>/dev/null
    git rebase --strategy-option=theirs
  }
  git -c color.status=always -c core.quotePath=false status --untracked-files=no |
    sed -e '$ d'
}
alias gp='git_pull'

git_current_remote() {
  git config --get branch."$({ git symbolic-ref --quiet --short HEAD -- || git rev-parse --short HEAD || git rev-parse --abbrev-ref HEAD; } 2>/dev/null)".remote
  # works in $TRASH and in new branches without remotes
  git branch --list --remotes | sed -n -e 's/^[[:space:]]*\([^[:space:]]*\)\/HEAD -> [^[:space:]]*$/\1/p'
  ##### git config --get "$(git config --get-regexp --name-only '^branch\..*\.remote$' | sed -e '1 q')" || git rev-parse --abbrev-ref --symbolic-full-name '@{upstream}' 2>/dev/null | sed -e 's/\/.*//' || git branch --remotes | sed -e '/->/! d' -e 's/  \([^\/ ]*\)\/.*/\1/' -e 'q'
  # 1st is the only that’ll work in a submodule
  # 1st is the only that won’t work if you do
  # `git branch --set-upstream-to=NOT_DEFAULT/"$(git_current_branch)"`
  git branch --remotes |
    sed -n -e 's/.* -> \(.*\)\/.*/\1/p'
  git rev-parse --abbrev-ref --symbolic-full-name '@{upstream}' |
    sed -e 's/\(.*\)\/.*/\1/'
  git config --get branch."$(git rev-parse --abbrev-ref HEAD)".remote
  git config --get branch."$({ git symbolic-ref --quiet --short HEAD || git rev-parse --short HEAD; } 2>/dev/null)".remote
  ##### git config --get branch."$(git-default-branch 2>/dev/null)".remote
  git config --get branch."$(git symbolic-ref --quiet --short HEAD 2>/dev/null || git rev-parse --short HEAD 2>/dev/null || git-default-branch)".remote
  ##### git config --get "$(git config --get-regexp --name-only '^branch\..*\.remote$' | sed -e '1q')"
  git rev-parse --symbolic-full-name '@{upstream}' |
    sed -e 's/^refs\/remotes\/*\(.*\)\/.*/\1/'
  # won't work if the current remote is named a/b/c/d
  # find -- "${GIT_DIR:-./.git}"'/refs/remotes' -name 'HEAD' -type f -exec sh -c -- 'basename -- "${1%/*}"' _ {} ';'

  # not sure if this works if remote's default branch has a slash in it
  find -- "${GIT_DIR:-./.git}"'/refs/remotes' -name 'HEAD' -type f -exec sed -e 's/ref: refs\/remotes\/\(.*\)\/[^\/]*/\1/' {} ';'
}

gdr() {
  {
    git config --get --worktree -- checkout.defaultRemote ||
      git config --get --local -- checkout.defaultRemote ||
      git config --get --system -- checkout.defaultRemote ||
      git config --get --global checkout.defaultRemote ||
      git config --get -- branch."$(git symbolic-ref --quiet --short HEAD -- 2>/dev/null)".remote
  } 2>/dev/null ||
    git config --default origin --get -- branch."$(
      git symbolic-ref --quiet --short HEAD 2>/dev/null ||
        git rev-parse --short HEAD 2>/dev/null
    )".remote
  # https://gitlab.com/engmark/root/commit/ca5e6f02ca2
  git config --get --default=origin -- checkout.defaultRemote
}
alias \
  git-default-remote='gdr' \
  git-default-origin='gdr'

# git push
git_push() {
  case "${1-}" in
  -r | --all-remotes)
    git remote show |
      while IFS='' read -r -- remote; do
        git -c push.autoSetupRemote=true push "${remote-}" "$(
          git symbolic-ref --quiet --short HEAD -- 2>/dev/null
        )" --atomic --follow-tags --no-thin --progress --prune --recurse-submodules=check --signed=if-asked --tags --verbose --verify
      done
    ;;
  # https://github.com/ohmyzsh/ohmyzsh/commit/ae21102030
  *)
    git -c push.autoSetupRemote=true push --progress --verbose "${@}"
    ;;
  esac
  git -c color.status=always -c core.quotePath=false status --untracked-files=no |
    sed -e '$ d'
}
alias gps='git_push'

alias \
  grba='git rebase --abort' \
  grbi='git rebase --interactive --update-refs 2>/dev/null || git rebase --interactive' \
  grbc='git rebase --continue --update-refs 2>/dev/null || git rebase --continue' \
  gref='git reflog'

# git rm
alias grm >/dev/null 2>&1 &&
  unalias -- grm
alias grm='rm'
git_rm_r() {
  git rev-parse --is-inside-work-tree >/dev/null 2>&1 ||
    return "${?:-1}"
  set -o xtrace
  PS4=' ' find -- . -path '*/.git' -prune -o -path './*/*' -prune -o -path './*' -exec rm -R -- {} + &&
    PS4=' ' find -- . -path '*/.git/hooks/*' -type f -exec rm -- {} + &&
    PS4=' ' find -- . -path '*/.git/hooks' -exec rmdir -- {} + &&
    PS4=' ' find -- . -path '*/.git/modules' -exec rm -f -R -- {} +
  {
    set +o xtrace
  } 2>/dev/null
  command -v -- cleanup >/dev/null 2>&1 &&
    cleanup
  git reset --quiet HEAD -- . &&
    git -c color.status=always -c core.quotePath=false status --untracked-files=no |
    sed -e '$ d'
}
alias grm.='git_rm_r'

git_remote_verbose() {
  # print `git remote -v` into columns as narrow as possible
  git remote --verbose |
    awk -vmax="$(git remote | awk -- 'BEGIN {max = 0} {if (length($0) > max) {max = length($0)} } END {print max}' -)" \
      -- \
      '! seen[$2]++ {printf "%-" max "s %s\n", $1, $2}' -
}
alias grv='git_remote_verbose'

git_restore() {
  case "${1-}" in
  -d | --deleted)
    git -c core.quotePath=false ls-files -z --deleted |
      sed -e 's/./\\&/g' |
      xargs git checkout --progress --
    ;;
  --)
    shift 1 &&
      git_restore "${@}"
    ;;
  *)
    while test "${#}" -gt 0; do
      git checkout --progress -- "${1-}"
      shift 1
    done
    ;;
  esac
  git -c color.status=always -c core.quotePath=false "${@:-status}" |
    sed -e '$ d'
}
alias \
  grs='git_restore' \
  grsd='git_restore --deleted'

git_search() {
  # search all repository content since its creation
  git rev-list --all |
    while IFS='' read -r -- commit; do
      # I: skip binary files
      git --no-pager grep \
        -I \
        --perl-regexp \
        --ignore-case \
        --line-number \
        "${@}" \
        "${commit-}" --
    done
}
alias gsearch='git_search'

git_shallow() {
  # Shallow .gitmodules submodule installations
  # Mauricio Scheffer https://stackoverflow.com/a/2169914
  git submodule init &&
    git submodule |
    awk -- '{print $2}' |
      while IFS='' read -r -- submodule; do
        # using `--progress`, `--verbose` and `--no-quiet` because
        # we’re not already in the target directory
        git -c core.ignoreCase=false clone \
          --depth 1 \
          --progress \
          --shallow-submodules \
          --template='' \
          --verbose \
          -- \
          "$(git config --file ./.gitmodules --get -- submodule."${submodule-}".url)" \
          "$(git config --file ./.gitmodules --get -- submodule."${submodule-}".path)"
      done &&
    git submodule update
}

git_show() {
  case "${1-}" in

  --date)
    shift 1
    git log --max-count=1 --format='%ci'
    ;;

  --files)
    # remove `--files` from the argument string
    shift 1

    # https://stackoverflow.com/a/424142
    git diff-tree -B -C -M -r --find-copies-harder --name-only --no-commit-id --root --text "${@:-HEAD}" -- |
      LANG='C' LC_ALL='C' sort -f |
      sed -e 's/^/.\//'
    ;;
  *)
    # if `gsh $(gic)` returns >1 results, then show them all
    # but default to `HEAD` if no arguments are given
    if test "${#}" -eq 0; then
      set -- HEAD
    fi
    git show "${1-}" 2>/dev/null ||
      git show "${1-}" --
    # shift <- no. because it will allow this to run twice
    ;;
  esac
}
alias \
  gsh='git_show' \
  gshd='git_show --date' \
  gshf='git_show --files'

# `git stash`
git_stash_save_all() {
  # https://github.com/ohmyzsh/ohmyzsh/commit/69ba6e4359
  git stash push -m "${@}" 2>/dev/null ||
    git stash push
}
alias gstall='git_stash_save_all'
git_stash_save_keep() {
  git stash push --keep-index -m "${@}" 2>/dev/null ||
    git stash push --keep-index
}
alias gstk='git_stash_save_keep'
gst_c() {
  git stash clear &&
    find -- "${GIT_DIR:-./.git}" \
      -depth \
      -path './*/*' \
      '(' \
      -name '._*' -o \
      -name '.gitstatus.*' -o \
      -name 'index.lock' -o \
      -name 'index.stash.*' \
      ')' \
      -delete
}
git_stash_pop() {
  # https://stackoverflow.com/q/51275777
  git stash pop || {
    git stash show --patch |
      git -c color.status=always -c core.quotePath=false apply --3
  } || {
    git -c color.status=always -c core.quotePath=false checkout stash -- .
  } || {
    git -c core.quotePath=false diff "$(git_current_branch)" stash:**/* |
      git -c color.status=always -c core.quotePath=false apply --3
  } || {
    git -c color.status=always -c core.quotePath=false diff "$(git_current_branch)" stash:**/*
  } || {
    git -c core.quotePath=false show stash:**/* >./tmp-"$(LANG='C' LC_ALL='C' date -- '+%Y%m%d%H%M%S')"
  }
}
alias \
  gsta='git -c color.status=always -c core.quotePath=false stash apply --index stash@'\''{'\''0'\''}'\''' \
  gstp='git_stash_pop'

git_submodule_cleanup() {
  set -o xtrace
  while test "$(
    find -- . \
      '(' \
      -path '*/.git/modules/*index.lock' -o \
      -path '*/.git/modules/*index.stash.*' -o \
      -path '*/.git/modules/*.gitstatus.*' \
      ')' \
      -print 2>/dev/null
  )" != ''; do
    printf -- 'deleting %s...\n' "$(
      find -- . \
        '(' \
        -path '*/.git/modules/*index.lock' -o \
        -path '*/.git/modules/*index.stash.*' -o \
        -path '*/.git/modules/*.gitstatus.*' \
        ')' \
        -print 2>/dev/null
    )" >&2 &&
      find -- . \
        '(' \
        -path '*/.git/modules/*index.lock' -o \
        -path '*/.git/modules/*index.stash.*' -o \
        -path '*/.git/modules/*.gitstatus.*' \
        ')' \
        -delete
  done
  git submodule foreach --recursive 'git reset --hard --recurse-submodules'
  git submodule foreach --recursive 'git stash clear'
  command -v -- git_update >/dev/null 2>&1 &&
    git_update "${@}"
  {
    set +o xtrace
  } 2>/dev/null
}
alias gsc='git_submodule_cleanup'

git_submodule_update() {
  # @TODO!: ensure this harmonizes with `git_update`’s submodule updater below
  git submodule update --init --remote "${@}" &&
    git submodule sync "${@}" &&
    git -c color.status=always -c core.quotePath=false status --untracked-files=no |
    sed -e '$ d'
}
alias gsu='git_submodule_update'

alias gtag='git --no-pager tag --sort=creatordate'

git_tag_edit() {
  # https://stackoverflow.com/a/14130875
  git tag "${1-}" "${1-}"'^'{} --annotate --force --sign
}

git_tags_by_date() {
  # https://github.com/crowdbotics-apps/firemeapp-3088/blob/cad844a221/client/app/components/linux/Sourcetree-Beta.app/Contents/Resources/git-tags-by-date.sh
  git tag --list | while IFS='' read -r -- tag; do
    printf -- '%s\t%s\n' "$(git log --max-count=1 --format='%cd' --date=format:'%F' "${tag-}" --)" "${tag-}"
  done | {
    case "${1-}" in
    -r | --reverse)
      LANG='C' LC_ALL='C' sort -n -r
      ;;
    *)
      LANG='C' LC_ALL='C' sort -n
      ;;
    esac
  }
}
alias gtags_by_date='git_tags_by_date'

git_time() {
  # convert yyyy-mm-dd at the current time to Git’s preferred format
  # show the 2 variables need to be set as what – interactive shell only @TODO!
  # printf -- 'GIT_AUTHOR_DATE="%s" GIT_COMMITTER_DATE="%s"'
  # git_time="$(gdate -d '@'"$(($(gdate -d "${1:-$(date '+%Y-%m-%d')}" '+%s') + 12 * 60 * 60))" -- '+%c %z')"
  case "${1-}" in
  -h | --help)
    printf -- 'Usage: git_time [date] [time]\n'
    ;;
  [1-9][0-9][0-9][0-9]-[0-1][0-9]-[0-3][0-9] | [1-9][0-9][0-9][0-9][0-1][0-9][0-3][0-9])
    shift 1
    LANG='C' LC_ALL='C' /usr/local/opt/coreutils/libexec/gnubin/date -d "${1:-+%Y-%m-%d}"'T'"${2:-%H:%M:%S}"'Z' '+%c %z'
    ;;
  [1-9][0-9][0-9][0-9]-[0-1][0-9]-[0-3][0-9]T[0-2][0-9]:[0-5][0-9]:[0-5][0-9]Z)
    shift 1
    LANG='C' LC_ALL='C' /usr/local/opt/coreutils/libexec/gnubin/date -d "${1-}"T"${2-}"Z '+%c %z'
    ;;
  *)
    printf -- ' GIT_AUTHOR_DATE=\047%s\047 GIT_COMMITTER_DATE=\047%s\047 \n' "$(LANG='C' LC_ALL='C' /usr/local/opt/coreutils/libexec/gnubin/date -d '@'"$(LANG='C' LC_ALL='C' /usr/local/opt/coreutils/libexec/gnubin/date -d "${1:-$(LANG='C' LC_ALL='C' date -- '+%Y-%m-%dT%H:%M:%S')}" -- '+%s')" -- '+%c %z')" "$(LANG='C' LC_ALL='C' /usr/local/opt/coreutils/libexec/gnubin/date -d '@'"$(LANG='C' LC_ALL='C' /usr/local/opt/coreutils/libexec/gnubin/date -d "${1:-$(LANG='C' LC_ALL='C' date -- '+%Y-%m-%dT%H:%M:%S')}" -- '+%s')" -- '+%c %z')"
    printf -- ' GIT_AUTHOR_DATE=\047%s\047 GIT_COMMITTER_DATE=\047%s\047 \n' "$(LANG='C' LC_ALL='C' /usr/local/opt/coreutils/libexec/gnubin/date -d '@'"$(LANG='C' LC_ALL='C' /usr/local/opt/coreutils/libexec/gnubin/date -d "${1:-$(LANG='C' LC_ALL='C' date -- '+%Y-%m-%d %H:%M:%S')}" -- '+%s')" -- '+%c %z')" "$(LANG='C' LC_ALL='C' /usr/local/opt/coreutils/libexec/gnubin/date -d '@'"$(LANG='C' LC_ALL='C' /usr/local/opt/coreutils/libexec/gnubin/date -d "${1:-$(LANG='C' LC_ALL='C' date -- '+%Y-%m-%d %H:%M:%S')}" -- '+%s')" -- '+%c %z')"
    printf -- ' GIT_AUTHOR_DATE=\047%s\047 GIT_COMMITTER_DATE=\047%s\047 \n' "$(LANG='C' LC_ALL='C' /usr/local/opt/coreutils/libexec/gnubin/date -d '@'$(($(LANG='C' LC_ALL='C' /usr/local/opt/coreutils/libexec/gnubin/date -d "${1:-$(LANG='C' LC_ALL='C' date -- '+%Y-%m-%d %H:%M:%S')}" -- '+%s'))) -- '+%c %z')" "$(LANG='C' LC_ALL='C' /usr/local/opt/coreutils/libexec/gnubin/date -d '@'$(($(LANG='C' LC_ALL='C' /usr/local/opt/coreutils/libexec/gnubin/date -d "${1:-$(LANG='C' LC_ALL='C' date -- '+%Y-%m-%d %H:%M:%S')}" -- '+%s'))) -- '+%c %z')"
    ;;
  esac
}
alias git-date='git_time'

git_undo() {
  git reset HEAD@'{'"${1:-1}"'}'
}
alias gundo='git_undo'

git_update() {
  set \
    -o noclobber \
    -o noglob \
    -o xtrace
  # run only from within a Git repository
  # https://stackoverflow.com/a/53809163
  if git rev-parse --is-inside-work-tree >/dev/null 2>&1; then

    command -v -- cleanup >/dev/null 2>&1 &&
      set +o noclobber &&
      cleanup
    set -o noclobber

    git fetch --all --keep --multiple --progress --prune --verbose --update-shallow

    # `git submodule update` with `--remote` appears to slow Git to a crawl
    # https://docs.google.com/spreadsheets/d/14W8w71DK0YpsePbgtDkyFFpFY1NVrCmVMaw06QY64eU
    case "${1-}" in
    -r | --remote)
      shift 1
      git submodule update --init --recursive --remote "${@}"
      ;;
    *)
      git submodule update --init --recursive "${@}"
      ;;
    esac
    git submodule sync --recursive "${@}"
  fi
  {
    set \
      +o noclobber \
      +o noglob \
      +o xtrace
  } 2>/dev/null
  git -c color.status=always -c core.quotePath=false status --untracked-files=no |
    sed -e '$ d'
}
alias gu='git_update'

gvc() {
  # https://github.com/tarunsk/dotfiles/blob/5b31fd6/.always_forget.txt#L1957
  # if there is an argument (commit hash), use it
  # otherwise check `HEAD`
  git verify-commit "${1:-HEAD}"
}

alias ghs='gh status'

github_search() {
  set -- 'https://github.com/search?type=code&q='"${*-}"
  xdg-open -- "${1-}" 2>/dev/null ||
    open -- "${1-}"
}

gofmt_r() {
  command -v -- gofumpt >/dev/null 2>&1 ||
    # EX_UNAVAILABLE
    return 69
  set \
    -o verbose \
    -o xtrace
  PS4=' ' find -- . \
    -path '*/.git' -prune -o \
    -path '*/Library' -prune -o \
    -path '*/node_modules' -prune -o \
    -path '*/t' -prune -o \
    -path '*/Test*' -prune -o \
    -path '*/test*' -prune -o \
    -path '*/tst*' -prune -o \
    -path '*/vendor' -prune -o \
    -name '*.go' \
    -type f \
    -exec sh -C -e -f -u -x -c -- 'git ls-files --error-unmatch -- "${1-}" >/dev/null 2>&1 ||
  ! git rev-parse --is-inside-work-tree >/dev/null 2>&1 &&
  gofumpt -extra -w -- "${1-}"
' _ {} ';'
  {
    set \
      +o verbose \
      +o xtrace
  } 2>/dev/null
}

google() {
  set -- 'https://ddg.gg/?kp=-2&q='"${*-}"
  xdg-open -- "${1-}" 2>/dev/null ||
    open -- "${1-}"
}

## GraphicConverter
gcr() {
  open -a "$(
    {
      set \
        +o verbose \
        +o xtrace
    } 2>/dev/null
    (
      find -- /Applications \
        -path '/Applications/*/*' -prune -o \
        -name 'GraphicConverter*' \
        -type d \
        -exec ls -d -1 -t -- {} + 2>/dev/null \
        &
    ) |
      sed \
        -n \
        -e '/1/ {' \
        -e '  s/^\/Applications\///' \
        -e '  s/\.app$//' \
        -e '}' \
        -e 'p'
  )" -- "${@}"
}

######
# grep

ggr() {
  # riffing on the above while not feeling great # 2022-09-14
  git --no-pager grep \
    -I \
    --break \
    --extended-regexp \
    --ignore-case \
    --line-number \
    --no-index \
    --recurse-submodules \
    --recursive \
    "${@}"
}

rg() {
  test "${#}" -gt 0 ||
    # EX_USAGE
    return 64
  env -i -- sh -c -- 'command -v -- rga || command -v -- rg' >/dev/null 2>&1 || {
    find -- . \
      -path '*/.git' -prune -o \
      -path '*/node_modules' -prune -o \
      ! -name '.DS_Store' \
      -type f \
      -exec grep -E "${@}" {} +
    return "${??}"
  }
  "$(env -i -- sh -c -- 'command -v -- rga || command -v -- rg')" \
    --glob '!**.git' \
    --glob '!**node_modules' \
    --glob '!**copilot*' \
    --glob '!**dummy*' \
    --glob '!**vscode*' \
    --hidden \
    --pcre2 \
    "${@}" 2>/dev/null
}
rgv() {
  test "${#}" -gt 0 ||
    # EX_USAGE
    return 64
  env -i -- sh -c -- 'command -v -- rga || command -v -- rg' >/dev/null 2>&1 || {
    grep -E -v "${@}"
    return "${??}"
  }
  "$(env -i -- sh -c -- 'command -v -- rga || command -v -- rg')" \
    -v \
    --glob '!**.git' \
    --glob '!**node_modules' \
    --glob '!**copilot*' \
    --glob '!**dummy*' \
    --glob '!**vscode*' \
    --hidden \
    --pcre2 \
    "${@}" 2>/dev/null
}
command -v -- _rg >/dev/null 2>&1 &&
  compdef -- rga='rg' >/dev/null 2>&1

grep_o() {
  # POSIX-compliant implementation of GNU `grep -o`
  # https://github.com/acmesh-official/acmetest/blob/b00e8f1875/letest.sh#L169
  { { test "${#}" -eq 0 && cat -- -; } || test "${#}" -eq 2 && printf -- '%s\n' "${@}"; } |
    sed \
      -n \
      -e 's/.*\('"${1-}"'\).*/\1/p' "${2:--}"
}

# grep
######

hash_abbreviate() {
  # abbreviate commit hash and copy to clipboard
  # usage: hash_abbreviate [-l <length>] <hash> [<hash> ...]
  test "${#}" -gt 0 ||
    # EX_USAGE
    return 64
  while getopts -- 'l:' opt; do
    case "${opt-}" in
    l)
      length="${OPTARG-}"
      ;;
    *)
      printf -- 'Usage: hash_abbreviate [-l <length>] <hash> [<hash> ...]\n' >&2
      return
      ;;
    esac
  done
  shift "$((OPTIND - 1))"
  for hash in "${@}"; do
    if printf -- '%s\n' "${hash-}" | grep -E -e '^[[:xdigit:]]{4,}$' >/dev/null 2>&1; then
      printf -- '%.'"${length:-"$(git config --get --default=7 -- core.abbrev)"}"'s\n' "${hash-}"
      # prevent copying trailing newline with `tr` and
      # hide clipboard errors because `pbcopy` is not common
      printf -- '%.'"${length:-"$(git config --get --default=7 -- core.abbrev)"}"'s' "${hash-}" |
        pbcopy 2>/dev/null
    else
      return 1
    fi
  done
  unset length >/dev/null 2>&1 || length=''
}
alias h7='hash_abbreviate'

hashlookup() {
  command -v -- curl >/dev/null 2>&1 &&
    command -v -- jq >/dev/null 2>&1 &&
    {
      command -v -- sha1sum >/dev/null 2>&1 ||
        command -v -- shasum >/dev/null 2>&1
    } ||
    # EX_UNAVAILABLE
    return 69
  test "${#}" -gt 0 ||
    # EX_USAGE
    return 64
  for file in "${@}"; do
    test -f "${file-}" ||
      # EX_NOINPUT
      return 66
    curl \
      --header 'Accept: application/json' \
      --show-error \
      --silent \
      --url 'https://hashlookup.circl.lu/lookup/sha1/'"$(
        {
          sha1sum -- "${file-}" ||
            shasum -- "${file-}"
        } 2>/dev/null |
          awk -- '{print $1}'
      )" |
      jq --raw-output '.parents[]' 2>/dev/null
  done
}

head() {
  case "${1-}" in
  -*)
    command -p -- head "${@}"
    ;;
  *)
    command -p -- head -n "$((${LINES:-"$(
      tput -- lines 2>/dev/null ||
        printf -- '10 + 2'
    )"} - 2))" "${@}"
    ;;
  esac
}
alias \
  h1='head -n 1' \
  h2='head -n 2' \
  h3='head -n 3'
head_c() {
  test "$((${1-} + 0))" -eq "${1-}" ||
    # EX_DATAERR
    return 65
  dd bs=1 count="${1-}" <"${2-}" 2>/dev/null ||
    test -f "${2-}" ||
    # EX_NOINPUT
    return 66
}

headers() {
  command -v -- curl >/dev/null 2>&1 ||
    # EX_UNAVAILABLE
    return 69
  test "${#}" -gt 0 ||
    # EX_USAGE
    return 64
  set \
    -o noclobber \
    -o noglob \
    -o nounset \
    -o verbose \
    -o xtrace
  for host in "${@}"; do
    # https://github.com/wincent/wincent/commit/fb6c4e8713
    curl \
      --dump-header - \
      --location \
      --output /dev/null \
      --show-error \
      --silent \
      --url "${host-}"
  done
  {
    set \
      +o noclobber \
      +o noglob \
      +o nounset \
      +o verbose \
      +o xtrace
  } 2>/dev/null
}

hooks_r() {
  git -C "${HOME%/}"'/c/hooks' rev-parse --is-inside-work-tree >/dev/null 2>&1 &&
    test -d "${PWD%/}"'/.git' &&
    mkdir -p -- "${PWD%/}"'/.git/hooks' &&
    # cp -p to preserve permissions
    find -- "${HOME%/}"'/c/hooks' \
      -path "${HOME%/}"'/c/hooks/.*' -prune -o \
      -path "${HOME%/}"'/c/hooks/*/*' -prune -o \
      -path "${HOME%/}"'/c/hooks/*' \
      -type f \
      -perm -700 \
      -exec sh -x -c -- 'cp -p -- "${1-}" ./.git/hooks' _ {} ';' 2>&1 |
    sed \
      -e 's|'"${custom-}"'|$\custom|' \
      -e 's|'"${DOTFILES-}"'|$\DOTFILES|' \
      -e 's|'"${XDG_CONFIG_HOME-}"'|$\XDG_CONFIG_HOME|' \
      -e 's|'"${HOME%/}"'|~|' \
      -e 's|[[:space:]][[:space:]]*->[[:space:]][[:space:]]*| → |' \
      -e 's|'\''||g' \
      >&2
}

hw() {
  set -o xtrace
  printf -- 'Hello,%sworld!\n' "${IFS-}"
  {
    set +o xtrace
  } 2>/dev/null
}

htail() {
  test "${HISTFILE-}" != '' ||
    # EX_CONFIG
    return 78
  test -s "${HISTFILE-}" ||
    # EX_NOINPUT
    return 66
  tail -n "$((${LINES:-"$(
    tput -- lines 2>/dev/null ||
      printf -- '10 + 2'
  )"} - 3))" -- "${HISTFILE-}"
}
hundo() {
  ## remove the last entry from `$HISTFILE`
  command -v -- ed >/dev/null 2>&1 ||
    # EX_UNAVAILABLE
    return 69
  test "${HISTFILE-}" != '' ||
    # EX_CONFIG
    return 78
  test -s "${HISTFILE-}" ||
    # EX_NOINPUT
    return 66
  # create a temporary location for the file
  mkdir -p -- "${XDG_DATA_HOME:-${HOME%/}/.local/share}"'/Trash' &&
    # move old copy if any
    find -- "${XDG_DATA_HOME:-${HOME%/}/.local/share}"'/Trash' \
      -name "${HISTFILE##*/}" \
      -type f \
      -exec sh -c -- 'mv -f -- {} {}.bak' ';'

  # create the copy
  # use the target directory AND target filename for less jarring stderr messages
  cp -f -p -- "${HISTFILE-}" "${XDG_DATA_HOME:-${HOME%/}/.local/share}"'/Trash/'"${HISTFILE##*/}" &&
    printf -- '\044{HISTFILE-}:\t%s\n' "${HISTFILE-}" &&
    # remove only the second-to-last line (the last line is now this command)
    # https://claude.ai/chat/93b3785b-0342-4f1e-8d0a-6b553832ddd3
    # \$-1d:
    #     \: escapes the following dollar sign
    #     $: refers to the last line of the file
    #    -1: moves the cursor one line up (to the second-to-last line)
    #     d: deletes that line
    ed -s -- "${HISTFILE-}" <<EOF
\$-1d
w
q
EOF
  case "${?:-1}" in
  0)
    # `! diff` instead of `diff` because two different files actually indicates success
    ! diff -- "${XDG_DATA_HOME:-${HOME%/}/.local/share}"'/Trash/'"${HISTFILE##*/}" "${HISTFILE-}"
    ;;
  *)
    return "${?:-126}"
    ;;
  esac
}

## .icns files
# convert to .png
icns_to_png() {
  command -v -- sips >/dev/null 2>&1 ||
    command -v -- icns2png >/dev/null 2>&1 ||
    # EX_UNAVAILABLE
    return 69
  test "${#}" -gt 0 ||
    # EX_USAGE
    return 64
  set \
    -o noclobber \
    -o noglob \
    -o xtrace
  for file in "${@}"; do
    test -s "${file-}" &&
      test ! -L "${file-}" &&
      case "${file-}" in
      *.[Ii][Cc][Nn][Ss])
        # https://web.archive.org/web/0id_/simplehelp.net/?p=4870
        command -v -- sips >/dev/null 2>&1 &&
          sips \
            --debug \
            --setProperty format png \
            --setProperty formatOptions 100 \
            "${file-}" \
            --addIcon \
            --out "${file%.*}"'.sips.png'
        command -v -- icns2png >/dev/null 2>&1 &&
          # icns2png output Goldilocks:
          #   `--list` increases verbosity
          #   `2>/dev/null` reduces verbosity
          icns2png \
            --list \
            --extract \
            -- \
            "${file-}" 2>/dev/null
        ;;
      *)
        # EX_DATAERR
        return 65
        ;;
      esac
  done
  {
    set \
      +o noclobber \
      +o noglob \
      +o xtrace
  } 2>/dev/null
}

# identify the current machine
identify_os() {
  {
    uname -a
    sw_vers
    lsb_release --all
    hostnamectl
    cat -- \
      '/etc/os-release' \
      '/usr/lib/os-release' \
      '/proc/version' \
      '/etc/issue'
    # https://github.com/dotnet/vscode-dotnet-runtime/blob/d37513361d/dotnetcore-acquisition-library/scripts/determine-linux-distro.sh
    if command -v -- zypper >/dev/null 2>&1; then
      printf -- 'openSUSE\n'
    elif command -v -- apt-get >/dev/null 2>&1; then
      printf -- 'Debian\n'
    elif command -v -- yum >/dev/null 2>&1; then
      printf -- 'RedHat\n'
    elif command -v -- pacman >/dev/null 2>&1; then
      printf -- 'ArchLinux\n'
    elif command -v -- eopkg >/dev/null 2>&1; then
      printf -- 'Solus\n'
    elif command -v -- apk >/dev/null 2>&1; then
      printf -- 'Alpine\n'
    fi
  } 2>/dev/null
}

# install() {
#   set \
#     -o verbose \
#     -o xtrace
#   case "${1-}" in
#   caveat*)
#     shift 1
#     {
#       set \
#         +o verbose \
#         +o xtrace
#     } 2>/dev/null
#     case "${1-}" in
#     environment*)
#       brew list -1 --formula | while IFS='' read -r -- formula; do
#         if brew info --formula -- "${formula-}" |
#           grep \
#             -e 'print the names of formulae where there is a § Caveats' \
#             -e ' Caveats' \
#             >/dev/null 2>&1; then
#           printf -- '%s\n' "${formula-}"
#         fi
#       done
#       ;;
#     *)
#       brew list -1 --formula | while IFS='' read -r -- formula; do
#         if brew info --formula -- "${formula-}" |
#           grep \
#             -e 'print the names of formulae where environmental-variable modification is suggested' \
#             -e '[[:upper:]]=' \
#             >/dev/null 2>&1; then
#           printf -- '%s\n' "${formula-}"
#         fi
#       done
#       ;;
#     esac
#     ;;
#   file*)
#     shift 1
#     set \
#       -o noclobber \
#       -o verbose \
#       -o xtrace
#     brew bundle dump \
#       --cask \
#       --debug \
#       --file=- \
#       --force \
#       --formula \
#       --mas \
#       --no-restart \
#       --tap \
#       "${@}" |
#       # move each package name onto the comment line above it, if any
#       sed \
#         -e '$! N' \
#         -e '/^#.*\n[^#]/ s/\n/\t/' \
#         -e 'P' \
#         -e 'D' |
#       # swap the package and the comment
#       sed \
#         -e 's/\(.*\)\t\(.*\)/\2\1/' |
#       # prepend each category with a number for sorting
#       sed \
#         -e 's/^\(tap\)/1\1/' \
#         -e 's/^\(brew\)/2\1/' \
#         -e 's/^\(cask\)/3\1/' |
#       # sort output by package name
#       LANG='C' LC_ALL='C' sort -f | {
#       printf -- '#!/usr/bin/env ruby\n'
#       printf -- '# frozen_string_literal: true\n\n'
#       sed \
#         -e '# remove the prepended numbers' \
#         -e 's/^[[:digit:]]//' \
#         -e '# restore each comment to a line above its package' \
#         -e 's/\([^#]*\)\(#.*\)/\2\n\1/' \
#         -e '# remove end-of-line “, args: ["HEAD"]”' \
#         -e 's/, args: \["HEAD"\]$//' \
#         -e '# remove @beta, @canary, @dev, etc., but not @2 or @3, etc.' \
#         -e 's/\(.*\)@[[:alpha:]]\{1,\}/\1/g'
#     } >|"${HOMEBREW_BUNDLE_FILE_GLOBAL:-${HOMEBREW_BUNDLE_FILE:-${HOME%/}/.Brewfile}}" &&
#       chmod -- 755 "${HOMEBREW_BUNDLE_FILE_GLOBAL:-${HOMEBREW_BUNDLE_FILE:-${HOME%/}/.Brewfile}}"
#     {
#       set \
#         +o noclobber \
#         +o verbose \
#         +o xtrace
#     } 2>/dev/null
#     ;;
#   HEAD*)
#     shift 1
#     {
#       set \
#         +o verbose \
#         +o xtrace
#     } 2>/dev/null
#     brew list -1 --formula | while IFS='' read -r -- formula; do
#       if brew info --formula -- "${formula-}" |
#         grep \
#           -e 'print the names of formulae where --HEAD is available' \
#           -e '^--HEAD$' \
#           >/dev/null 2>&1; then
#         printf -- '%s\n' "${formula-}"
#       fi
#     done
#     ;;
#   search)
#     shift 1
#     brewsearch "${@}"
#     ;;
#   info)
#     brew "${@}"
#     ;;
#   --)
#     shift 1
#     ;;
#   *)
#     # @TODO! this should allow for  install --search  -- 𝑥
#     #                               install --info    -- 𝑥
#     #                               install           -- 𝑥
#     #                  and perhaps  install --install -- 𝑥

#     # Homebrew
#     if command -v -- brew >/dev/null 2>&1; then
#       brew install "${@}"
#     # search brew search --debug --verbose --desc git; brew search git

#     # Alpine Linux
#     elif command -v -- apk >/dev/null 2>&1; then
#       apk add "${@}"

#     # Ubuntu, Debian
#     elif command -v -- apt >/dev/null 2>&1; then
#       sudo -- apt install "${@}"
#     elif command -v -- apt-get >/dev/null 2>&1; then
#       # https://clarkgrubb.com/package-managers#pkg-managers
#       sudo -- apt-get install -y "${@}"

#     # Arch Linux
#     elif command -v -- pacman >/dev/null 2>&1; then
#       # https://unix.stackexchange.com/a/34607
#       # if Arch fails here, try `pacman --sync -yy`
#       pacman --sync -yy "${@}"
#     else
#       printf -- 'unable to detect system software installer\n'
#       sleep 1
#       printf -- 'aborting\n'
#       return 1
#     fi
#     ;;
#   esac
#   {
#     set \
#       +o verbose \
#       +o xtrace
#   } 2>/dev/null
# }
# alias i='install'
# brewsearch() {
#   test "${#}" -gt 0 ||
#     # EX_USAGE
#     return 64
#   while test "${#}" -ne 0; do
#     brew search --formula --verbose "${1-}"
#     shift 1
#   done
# }

## invisible
# make files invisible to Finder
# -h apply to symlinks, not targets
# -x stay on current system
# -vv be verbose and print old and new flags
alias \
  invisible='chflags -h -v -v -x hidden' \
  uninvisible='chflags -h -v -v -x nohidden'

image_color_count() {
  # print the number of unique colors found in the image
  # usage: image_color_count image.jpg
  command -v -- magick >/dev/null 2>&1 ||
    # EX_UNAVAILABLE
    return 69
  test "${#}" -gt 0 ||
    # EX_USAGE
    return 64
  for file in "${@}"; do
    case "${file-}" in
    --)
      shift 1
      ;;
    *)
      magick "${file-}" txt:- |
        # if column 3 is a hashed hexadecimal color,
        # that has not yet been printed,
        # then print it
        awk -- '$3 ~ /^#[[:xdigit:]]{6,8}$/ && ! seen[$3]++ {print $3}' |
        LANG='C' LC_ALL='C' sort -f |
        LANG='C' LC_ALL='C' tr -- '[:upper:]' '[:lower:]' |
        LC_ALL='C' nl
      ;;
    esac
  done
}

image_color_frequency() {
  command -v -- magick >/dev/null 2>&1 ||
    # EX_UNAVAILABLE
    return 69
  test "${#}" -gt 0 ||
    # EX_USAGE
    return 64
  for file in "${@}"; do
    case "${file-}" in
    --)
      shift 1
      ;;
    *)
      magick "${file-}" txt:- |
        awk -- '$3 ~ /^#[[:xdigit:]]{6,8}$/ {print $3}' |
        LANG='C' LC_ALL='C' sort |
        LC_ALL='C' uniq -c |
        LANG='C' LC_ALL='C' sort -n |
        # %10d allows columnar output iff each frequency occurs fewer than 10^9 times
        awk -- '{printf "%10d %s\n", $1, $2}' |
        LANG='C' LC_ALL='C' tr -- '[:upper:]' '[:lower:]'
      ;;
    esac
  done
}

image_color_list() {
  # print the number of unique colors found in the image
  # usage: image_color_count image.jpg
  command -v -- magick >/dev/null 2>&1 ||
    # EX_UNAVAILABLE
    return 69
  test "${#}" -gt 0 ||
    # EX_USAGE
    return 64
  for file in "${@}"; do
    case "${file-}" in
    --)
      shift 1
      ;;
    *)
      magick "${file-}" txt:- |
        # if column 3 is a hashed hexadecimal color,
        # that has not yet been printed,
        # then print it
        awk -- '$3 ~ /^#[[:xdigit:]]{6,8}$/ && ! seen[$3]++ {print $3}' |
        LANG='C' LC_ALL='C' sort -f |
        LANG='C' LC_ALL='C' tr -- '[:upper:]' '[:lower:]'
      ;;
    esac
  done
}

image_get_pixel() {
  # https://github.com/cirosantilli/dotfiles/blob/60ca745cdc/home/.bashrc#L2829-L2836
  # $ image_get_pixel file.png 10 20
  # to obtain the color of the pixel at x=10, y=20
  magick -- "${1-}" -crop 1x1'+'"${2:-1}"'+'"${3:-1}" rgba:- |
    od -A n -t x1 |
    sed \
      -e 's/^[[:space:]]*//' \
      -e 'q'
}

ip() {
  test "${IPINFO_TOKEN-}" != '' ||
    # EX_CONFIG
    return 78
  # https://web.archive.org/web/2022/news.ycombinator.com/item?id=29848744
  set -- 'https://ipinfo.io/'"${1-}"'?token='"${IPINFO_TOKEN-}"
  {
    curl \
      --fail \
      --show-error \
      --silent \
      --url "${1-}" ||
      wget \
        --content-on-error \
        --hsts-file=/dev/null \
        --output-document=- \
        --quiet \
        -- \
        "${1-}"
  } 2>/dev/null |
    sed \
      -n \
      -e '/ipinfo/ d' \
      -e 's/.*"\(.*\)".*/\1/p'
}

javascript_prettier_r() {
  command -v -- prettier >/dev/null 2>&1 ||
    # EX_UNAVAILABLE
    return 69
  find -- . \
    -path '*/.git' -prune -o \
    -path '*/node_modules' -prune -o \
    -path '*/coverage' -prune -o \
    -path '*/vendor' -prune -o \
    '(' \
    -name '*.js' -o \
    -name '*._[Jj][Ss]' -o \
    -name '*.[Bb][Oo][Nn][Ee][Ss]' -o \
    -name '*.[Cc][Jj][Ss]' -o \
    -name '*.[Ee][Ss]' -o \
    -name '*.[Ee][Ss]6' -o \
    -name '*.[Ff][Rr][Aa][Gg]' -o \
    -name '*.[Gg][Jj][Ss]' -o \
    -name '*.[Gg][Ss]' -o \
    -name '*.[Jj][Aa][Kk][Ee]' -o \
    -name '*.[Jj][Aa][Kk][Ee][Ff][Ii][Ll][Ee]' -o \
    -name '*.[Jj][Aa][Vv][Aa][Ss][Cc][Rr][Ii][Pp][Tt]' -o \
    -name '*.[Jj][Ss]' -o \
    -name '*.[Jj][Ss][Bb]' -o \
    -name '*.[Jj][Ss][Cc][Aa][Dd]' -o \
    -name '*.[Jj][Ss][Ff][Ll]' -o \
    -name '*.[Jj][Ss][Ll][Ii][Bb]' -o \
    -name '*.[Jj][Ss][Mm]' -o \
    -name '*.[Jj][Ss][Pp][Rr][Ee]' -o \
    -name '*.[Jj][Ss][Ss]' -o \
    -name '*.[Jj][Ss][Xx]' -o \
    -name '*.[Mm][Jj][Ss]' -o \
    -name '*.[Nn][Jj][Ss]' -o \
    -name '*.[Pp][Aa][Cc]' -o \
    -name '*.[Ss][Jj][Ss]' -o \
    -name '*.[Ss][Ss][Jj][Ss]' -o \
    -name '*.[Xx][Ss][Jj][Ss]' -o \
    -name '*.[Xx][Ss][Jj][Ss][Ll][Ii][Bb]' \
    ')' \
    ! -name '*-[Mm][Ii][Nn].[Jj][Ss]' \
    ! -name '*.[Mm][Ii][Nn].[Jj][Ss]' \
    -type f \
    -exec sh -x -c -- 'for file in "${@}"; do
  git ls-files --error-unmatch -- "${file-}" >/dev/null 2>&1 ||
    ! git rev-parse --is-inside-work-tree >/dev/null 2>&1 &&
    prettier --log-level log --write -- "${file-}"
done' _ {} +
}
alias standard_r='javascript_prettier_r'

## JPEG
to_jpg() {
  command -v -- magick >/dev/null 2>&1 ||
    # EX_UNAVAILABLE
    return 69
  test "${#}" -gt 0 ||
    # EX_USAGE
    return 64
  set \
    -o noclobber \
    -o noglob \
    -o xtrace
  for file in "${@}"; do
    test -s "${file-}" &&
      test ! -L "${file-}" &&
      magick \
        -quality 100 \
        -verbose \
        -- \
        "${file-}" \
        "${file%.*}"'.jpg'
  done
  {
    set \
      +o noclobber \
      +o noglob \
      +o xtrace
  } 2>/dev/null
}

guetzli_r() {
  command -v -- guetzli >/dev/null 2>&1 ||
    # EX_UNAVAILABLE
    return 69
  test "${#}" -gt 0 ||
    # EX_USAGE
    return 64
  set \
    -o noclobber \
    -o noglob \
    -o xtrace
  for file in "${@}"; do
    test -s "${file-}" &&
      test ! -L "${file-}" &&
      test ! -e "${file%.*}"'-guetzli.jpg' &&
      case "${file-}" in
      *.[Jj][Pp][Ee][Gg] | *.[Jj][Pp][Gg])
        guetzli \
          --nomemlimit \
          --quality 100 \
          --verbose \
          -- \
          "${file-}" \
          "${file%.*}"'-guetzli.jpg'
        ;;
      *)
        # EX_DATAERR
        return 65
        ;;
      esac
  done
  {
    set \
      +o noclobber \
      +o noglob \
      +o xtrace
  } 2>/dev/null
}
## JPEG

jsonlint_r() {
  command -v -- find_json_files >/dev/null 2>&1 &&
    command -v -- prettier >/dev/null 2>&1 ||
    # EX_UNAVAILABLE
    return 69
  find_json_files | while IFS='' read -r -- file; do
    git ls-files --error-unmatch -- "${file-}" >/dev/null 2>&1 ||
      ! git rev-parse --is-inside-work-tree >/dev/null 2>&1 &&
      prettier --log-level log --parser json --write -- "${file-}"
  done
}

## last
alias last_character='tail -c -1'
last_word() {
  test "${#}" -gt 0 ||
    # EX_USAGE
    return 64
  while test "${#}" -gt 0; do
    printf -- '%s\n' "${1##* }"
    shift 1
  done
}

length_of_longest_line() {
  # https://unix.stackexchange.com/a/523516
  # `$1` is a file as an argument and
  # `-` is stdin
  awk -- 'BEGIN {max = 0} {if (length($0) > max) {max = length($0)} } END {print max}' "${1:--}"
}
sort_by_line_length() {
  awk -- '{print length($0), $0}' "${1:--}" |
    LANG='C' LC_ALL='C' sort -k 1,2 -n "${2:--}"
}
alias length_of_line_sort='sort_by_line_length'

# linguist
breakdown() {
  utility="$(
    command -v -- github-linguist ||
      command -v -- git-linguist ||
      command -v -- linguist
  )"
  test "${utility-}" = '' &&
    # EX_UNAVAILABLE
    return 69
  git rev-parse --is-inside-work-tree >/dev/null 2>&1 ||
    return "${?:-1}"
  case "${1-}" in
  -s | --summary)
    shift 1
    "${utility-}" "${@}" "$(
      git rev-parse --path-format=relative --show-toplevel |
        sed -e '1 q'
    )" 2>/dev/null ||
      "${utility-}" "${@}" "$(git rev-parse --show-toplevel)" 2>/dev/null
    ;;
  *)
    "${utility-}" --breakdown "${@}" "$(
      git rev-parse --path-format=relative --show-toplevel |
        sed -e '1 q'
    )" 2>/dev/null ||
      "${utility-}" --breakdown "${@}" "$(git rev-parse --show-toplevel)" 2>/dev/null |
      sed -e '$ d'
    ;;
  esac
  unset utility >/dev/null 2>&1 || utility=''
}
alias \
  bdo='breakdown' \
  bdos='breakdown --summary'

# list files
alias ld >/dev/null 2>&1 &&
  unalias -- ld
alias l >/dev/null 2>&1 &&
  unalias -- l
if eza --color=auto >/dev/null 2>&1; then
  alias \
    l='eza --all --bytes --classify --color=auto --color-scale=all --icons --long --no-permissions --no-user --octal-permissions --time-style=long-iso' \
    ld='eza --all --bytes --classify --color=auto --color-scale=all --icons --long --no-permissions --no-user --octal-permissions --only-dirs --time-style=long-iso --total-size' \
    lg='eza --all --bytes --classify --color=auto --color-scale=all --git --icons --long --no-permissions --no-user --octal-permissions --time-style=long-iso' \
    lgs='eza --all --bytes --classify --color=auto --color-scale=all --git --icons --long --no-permissions --no-user --octal-permissions --sort=size --time-style=long-iso' \
    lm='eza --all --bytes --classify --color=auto --color-scale=all --icons --long --no-permissions --no-user --octal-permissions --sort=modified --time-style=long-iso'
elif command gls --color=auto >/dev/null 2>&1; then
  alias \
    l='command gls -A -F -g -o --color=auto' \
    ld='find -- . -path '\''./*/*'\'' -prune -o -path '\''*/.git'\'' -prune -o -path '\''./*'\'' -type d -exec gls -A -F -d -g -o --color=auto -- {} +'
elif ls --color=auto >/dev/null 2>&1; then
  alias \
    l='ls -A -F -g -o --color=auto' \
    ld='find -- . -path '\''./*/*'\'' -prune -o -path '\''*/.git'\'' -prune -o -path '\''./*'\'' -type d -exec ls -A -F -d -g -o --color=auto -- {} +'
elif ls -o >/dev/null 2>&1; then
  alias \
    l='ls -A -F -g -o' \
    ld='find -- . -path '\''./*/*'\'' -prune -o -path '\''*/.git'\'' -prune -o -path '\''./*'\'' -type d -exec ls -A -F -d -g -o -- {} +'
else
  alias \
    l='ls -A -F -g' \
    ld='find -- . -path '\''./*/*'\'' -prune -o -path '\''*/.git'\'' -prune -o -path '\''./*'\'' -type d -exec ls -A -F -d -g -- {} +'
fi

list_functions() {
  # print the names of functions found in a shell script file
  test "${#}" -gt 0 ||
    # EX_USAGE
    return 64
  for file in "${@}"; do
    sed \
      -e '# does the first non-empty line resemble a shell directive?' \
      -e '/./,$! d' \
      -e '1 q' \
      "${file-}" |
      grep \
        -e '^#!.*bin.*[^c]sh' \
        -e '^[[:space:]]*\(function[[:space:]]\)\{0,1\}[[:space:]]*[A-Za-z_][-A-Za-z_0-9]*()[[:space:]]*{.*$' \
        -e 'autoload' \
        -e 'compdef' \
        -e 'openrc' \
        >/dev/null 2>&1 &&
      LC_ALL='C' sed \
        -n \
        -e '# https://github.com/jschauma/cs615asa/commit/2a54687425' \
        -e '# the last dot star is for one-line functions like in hblock but has not been well tested' \
        -e 's/^\([[:alpha:]_][[:alpha:][:digit:]_]*\)()[[:space:]]*{.*/\1/p' \
        "${file-}" |
      LANG='C' LC_ALL='C' sort -f
  done
}

alias list_all_functions='print ${(F)${(-)${(k)functions}}}'

list_uniform_type_identifiers() {
  # https://github.com/moretension/duti/blob/46a5b28913/duti.1#L295-L300
  find -- /System/Library/Frameworks \
    -name 'lsregister' \
    -type f \
    -exec sh -c -- '{} -dump' ';' |
    LANG='C' LC_ALL='C' sort -f |
    awk -- '/^uti:/ && ! seen[$2]++ {print $2}'
}
alias list_utis='list_uniform_type_identifiers'

literoj() {
  LC_ALL='eo' printf -- 'ĈĉĜĝĤĥĴĵŜŝŬŭ\n'
}

# list --others
lso() {
  git -c color.status=always -c core.quotePath=false ls-files --exclude-standard --others "${@}" |
    awk -- '{print "./" $0}'
}

## M4A
to_m4a() {
  command -v -- ffmpeg >/dev/null 2>&1 ||
    # EX_UNAVAILABLE
    return 69
  test "${#}" -gt 0 ||
    # EX_USAGE
    return 64
  set \
    -o noclobber \
    -o verbose \
    -o xtrace
  for file in "${@}"; do
    # https://stackoverflow.com/a/55478355
    ffmpeg \
      -nostdin \
      -i "${file-}" \
      -b:a 320k \
      -c:a alac \
      -c:v copy \
      -- \
      "${file%.*}"'.m4a'
  done
  {
    set \
      +o noclobber \
      +o verbose \
      +o xtrace
  } 2>/dev/null
}

## any audio to MP3
to_mp3() {
  command -v -- ffmpeg >/dev/null 2>&1 ||
    # EX_UNAVAILABLE
    return 69
  test "${#}" -gt 0 ||
    # EX_USAGE
    return 64
  set \
    -o noclobber \
    -o noglob \
    -o verbose \
    -o xtrace
  for file in "${@}"; do
    # `-vn`: no video if any
    # `-c:a libmp3lame` a high-quality MP3 encoder
    # `-q:a 0`: 0 = lossless
    # "${file%.*}": filename without extension
    ffmpeg \
      -i "${file-}" \
      -vn \
      -c:a libmp3lame \
      -q:a 0 \
      "${file%.*}"'.mp3'
  done
  {
    set \
      +o noclobber \
      +o noglob \
      +o verbose \
      +o xtrace
  } 2>/dev/null
}

to_mp4() {
  command -v -- ffmpeg >/dev/null 2>&1 ||
    # EX_UNAVAILABLE
    return 69
  test "${#}" -gt 0 ||
    # EX_USAGE
    return 64
  set \
    -o noclobber \
    -o noglob \
    -o xtrace
  # https://stackoverflow.com/a/66248591
  for file in "${@}"; do
    ffmpeg \
      -i "${file-}" \
      -crf 0 \
      "${file%.*}"'mp4' ||
      ffmpeg \
        -i "${file-}" \
        -crf 18 \
        -filter:v format=yuv420p \
        "${file%.*}"'.mp4'
  done
  {
    set \
      +o noclobber \
      +o noglob \
      +o xtrace
  } 2>/dev/null
}

## mackup
mu() {
  command -v -- mackup >/dev/null 2>&1 ||
    # EX_UNAVAILABLE
    return 69
  test "${DOTFILES-}" != '' ||
    # EX_CONFIG
    return 78
  CDPATH='.' cd "${DOTFILES-}" >/dev/null 2>&1 ||
    return 1
  command -v -- cleanup >/dev/null 2>&1 &&
    cleanup
  mackup backup --force --root --verbose |
    sed \
      -e 's|'"${custom-}"'|$\custom|' \
      -e 's|'"${DOTFILES-}"'|$\DOTFILES|' \
      -e 's|'"${XDG_CONFIG_HOME-}"'|$\XDG_CONFIG_HOME|' \
      -e 's|'"${HOME%/}"'|~|'
  git fetch --all --keep --multiple --progress --prune --verbose --update-shallow
  git submodule update --init --recursive
  git submodule sync --recursive
  git -c color.status=always -c core.quotePath=false status --untracked-files=no |
    sed -e '$ d'
}

# dotfiles
dot() {
  test "${DOTFILES-}" != '' ||
    # EX_CONFIG
    return 78
  CDPATH='.' cd "${DOTFILES-}" >/dev/null 2>&1 ||
    return 1
  l 2>/dev/null ||
    ls -A -F -g -o 2>/dev/null
  git -c color.status=always -c core.quotePath=false status --untracked-files=no 2>/dev/null |
    sed -e '$ d'
}
alias \
  .f='{ test -d "${HOME%/}"'\''/c/.f'\'' && CDPATH='\''.'\'' cd "${HOME%/}"'\''/c/.f'\'' >/dev/null 2>&1; } || return "${?:-1}"' \
  .m='{ test -d "${HOME%/}"'\''/c/.m'\'' && CDPATH='\''.'\'' cd "${HOME%/}"'\''/c/.m'\'' >/dev/null 2>&1; } || return "${?:-1}"' \
  .g='{ test -d "${_GITHUB:-${HOME%/}/c/.g}" && CDPATH='\''.'\'' cd "${_GITHUB:-${HOME%/}/c/.g}" >/dev/null 2>&1; } || return "${?:-1}"'

## Maestral && 1Password somehow
command -v -- maestral >/dev/null 2>&1 && {
  command -v -- _maestral >/dev/null 2>&1 || {
    maestral completion "$(basename -- "${SHELL%%[0-9-]*}")" >/dev/null 2>&1 &&
      test "${FPATH-}" != '' &&
      case ':'"${FPATH-}"':' in
      *:/usr/local/share/"$(basename -- "${SHELL%%[0-9-]*}")"/site-functions:*)
        maestral completion "$(basename -- "${SHELL%%[0-9-]*}")" >/usr/local/share/"$(basename -- "${SHELL%%[0-9-]*}")"/site-functions/_maestral
        ;;
      *) ;;
      esac
  }
}
ms() {
  command -v -- maestral >/dev/null 2>&1 ||
    # EX_UNAVAILABLE
    return 69
  maestral status |
    sed \
      -e '/^$/ N' \
      -e '/\n$/ D' \
      -e '/Path *Error/,$ d'
}
command -v -- op >/dev/null 2>&1 && {
  command -v -- _op >/dev/null 2>&1 || {
    op completion "$(basename -- "${SHELL%%[0-9]*}")" >/dev/null 2>&1 &&
      test "${FPATH-}" != '' &&
      case ':'"${FPATH-}"':' in
      *:/usr/local/share/"$(basename -- "${SHELL%%[0-9]*}")"/site-functions:*)
        op completion "$(basename -- "${SHELL%%[0-9]*}")" >/usr/local/share/"$(basename -- "${SHELL%%[0-9]*}")"/site-functions/_op
        ;;
      *) ;;
      esac
  }
}

# batman
man() {
  test "${#}" -gt 0 ||
    # EX_USAGE
    return 64
  if command -v -- batman >/dev/null 2>&1; then
    batman "${@}"
  elif command -v -- gman >/dev/null 2>&1; then
    gman "${@}"
  else
    command -p -- man "${@}"
  fi
}
command -v -- _man >/dev/null 2>&1 &&
  compdef -- batman='man' >/dev/null 2>&1

man_pdf() {
  command -v -- /System/Applications/Preview.app/Contents/MacOS/Preview >/dev/null 2>&1 ||
    command -v -- /Applications/Preview.app/Contents/MacOS/Preview >/dev/null 2>&1 ||
    # EX_UNAVAILABLE
    return 69
  command -v -- ps2pdf >/dev/null 2>&1 ||
    command -v -- mandoc >/dev/null 2>&1 ||
    # EX_UNAVAILABLE
    return 69
  test "${#}" -gt 0 ||
    # EX_USAGE
    return 64
  set \
    -o noclobber \
    -o noglob \
    -o verbose \
    -o xtrace
  if command -v -- ps2pdf >/dev/null 2>&1; then
    while test "${#}" -gt 0; do
      command man -t -- "${1-}" 2>/dev/null |
        ps2pdf - - | open -a Preview -f
      shift 1
    done
  elif command -v -- mandoc >/dev/null 2>&1 && {
    command -v -- /System/Applications/Preview.app/Contents/MacOS/Preview >/dev/null 2>&1 ||
      command -v -- /Applications/Preview.app/Contents/MacOS/Preview >/dev/null 2>&1
  }; then
    while test "${#}" -gt 0; do
      mandoc -T pdf "$(command man -w "${1-}" 2>/dev/null)" |
        open -a Preview -f
    done
  fi
  {
    set \
      +o noclobber \
      +o noglob \
      +o verbose \
      +o xtrace
  } 2>/dev/null
}
command -v -- _man >/dev/null 2>&1 &&
  compdef -- man_pdf='man' >/dev/null 2>&1

markdownlint_r() {
  command -v -- markdownlint >/dev/null 2>&1 ||
    # EX_UNAVAILABLE
    return 69
  set \
    -o verbose \
    -o xtrace
  # Markdown filename extensions
  # https://github.com/github/linguist/blob/7503f7588c/lib/linguist/languages.yml#L3707-L3718
  find -- . \
    -path '*/.git' -prune -o \
    -path '*/.well-known' -prune -o \
    -path '*/Library' -prune -o \
    -path '*/node_modules' -prune -o \
    -path '*/t' -prune -o \
    -path '*/Test*' -prune -o \
    -path '*/test*' -prune -o \
    -path '*/tst*' -prune -o \
    -path '*copilot*' -prune -o \
    -path '*dummy*' -prune -o \
    -path '*vscode*' -prune -o \
    '(' \
    -name '*.md' -o \
    -name '*.livemd' -o \
    -name '*.markdn' -o \
    -name '*.markdown' -o \
    -name '*.mdown' -o \
    -name '*.mdwn' -o \
    -name '*.mdx' -o \
    -name '*.mkd' -o \
    -name '*.mkdn' -o \
    -name '*.mkdown' -o \
    -name '*.ronn' -o \
    -name '*.scd' -o \
    -name '*.workbook' -o \
    -name 'contents.lr' \
    ')' \
    ! -name 'changelog.md' \
    ! -name '[Cc][Hh][Aa][Nn][Gg][Ee]*[Ll][Oo][Gg]*.[Mm]*[Dd]*' \
    -type f \
    -exec sh -x -c -- 'configuration="$(find -- "${XDG_CONFIG_HOME:-${HOME%/}/.config}"'\''/markdownlint/config.json'\'' "${HOME%/}"'\''/.markdownlint.json'\'' "${HOME%/}"'\''/.markdownlint.yml'\'' /dev/null -exec ls -S -- {} + 2>/dev/null | sed -e '\''1 q'\'')" && for file in "${@}"; do git ls-files --error-unmatch -- "${file-}" >/dev/null 2>&1 || ! git rev-parse --is-inside-work-tree >/dev/null 2>&1 && markdownlint --config="${configuration-}" --disable MD013 MD033 --dot --fix -- "${file-}"; done' _ {} +
  {
    set \
      +o verbose \
      +o xtrace
  } 2>/dev/null
}

## mindepth and maxdepth
# not defined by POSIX, but these are equivalent
maxdepth() {
  # instead of `find . -maxdepth 2 -print`, use `find . -path './*/*/*' -prune -o -print`
  set -- "${1:-0}" './*'
  while test "${1-}" -gt 0; do
    set -- "$((${1-} - 1))" "${2-}"'/*'
  done
  printf -- '#!/usr/bin/env sh\nfind -- . -path \047%s\047 -prune -o -print\n' "${2-}" | {
    bat \
      --decorations=never \
      --language=sh \
      --paging=never \
      -- \
      - 2>/dev/null ||
      cat \
        -- \
        -
  }
}
mindepth() {
  # instead of `find . -mindepth 2 -print`, use `find . -path './*/*' -print`
  set -- "${1:-0}" '.'
  while test "${1-}" -gt 0; do
    set -- "$((${1-} - 1))" "${2-}"'/*'
  done
  printf -- '#!/usr/bin/env sh\nfind -- . -path \047%s\047 -print\n' "${2-}" | {
    bat \
      --decorations=never \
      --language=sh \
      --paging=never \
      -- \
      - 2>/dev/null ||
      cat \
        -- \
        -
  }
}
m1m1() {
  printf -- '#!/usr/bin/env sh\nfind -- . -path \047./*/*\047 -prune -o -path \047./*\047 -print\n' | {
    bat \
      --decorations=never \
      --language=sh \
      --paging=never \
      -- \
      - 2>/dev/null ||
      cat \
        -- \
        -
  }
}

# https://unix.stackexchange.com/a/30950
alias mv='mv -v -i'

# find files with non-ASCII characters
non_ascii() {
  # file names
  # https://unix.stackexchange.com/a/109753

  if test "$(
    LC_ALL='C' find -- "${@:-.}" \
      -path '*/.git' -prune -o \
      -path '*/node_modules' -prune -o \
      '(' \
      ! -name '*[[:alnum:]]*' -o \
      -name '*[[:space:]]*' \
      -name '*[! -~]*' \
      ')' \
      -print
  )" != ''; then

    printf -- 'non-ASCII file names:\n'
    LC_ALL='C' find -- "${@:-.}" \
      -path '*/.git' -prune -o \
      -path '*/node_modules' -prune -o \
      '(' \
      ! -name '*[[:alnum:]]*' -o \
      -name '*[[:space:]]*' \
      -name '*[! -~]*' \
      ')' \
      -print
  fi

  # horizontal rule
  printf -- '\055\055\055\n'

  # file content
  # https://stackoverflow.com/a/9395552
  # `-I`: exclude binary files
  # `-e`: search expression
  if LC_ALL='C' git --no-pager grep -I --no-index --max-depth=0 --exclude-standard --perl-regexp --quiet --recursive -e '[\200-\377]|[^\t -~]'; then
    printf -- 'file content i.\n'
    LC_ALL='C' git --no-pager grep -I --no-index --max-depth=0 --exclude-standard --perl-regexp --line-number --recursive -e '[\200-\377]|[^\t -~]'
  fi
}
non_ascii_filenames() {
  LC_ALL='C' find -- "${@:-.}" \
    -path '*/.git' -prune -o \
    -path '*/node_modules' -prune -o \
    '(' \
    ! -name '*[[:alnum:]]*' -o \
    -name '*[[:space:]]*' \
    -name '*[! -~]*' \
    ')' \
    -print
  # not sure why this prints WITHOUT using the C locale, but that happens to be what I want
}

nslookup_r() {
  # repeated nameserver lookup like itools.com/internet of olden times
  command -v -- nslookup >/dev/null 2>&1 ||
    # EX_UNAVAILABLE
    return 69
  while test "${#}" -gt 0; do
    output="$(nslookup "${1-}" 2>&1)"
    printf -- '%s\n' "${output-}" | grep -A 1 -e 'Name' | tail -n 1 | awk -- '{print $2}'
    printf -- '%s\n' "${output-}" | grep -e 'name' | awk -- '{print $4}'
    shift 1
  done
}
command -v -- _nslookup >/dev/null 2>&1 &&
  compdef -- nslookup_r='nslookup' >/dev/null 2>&1

odb() {
  # odb: convert hexadecimal escapes to octal escapes
  # usage: `odb <string>` or `echo <string> | odb`
  # test for standard input or if not, then use arguments
  { {
    test "${#}" -eq 0 && cat -- -
    # while this is ultra clever and succinct, this could be made cleverer yet perhaps by
    # checking if `$1` = `-` which is standard input
    # https://git.sr.ht/~q3cpma/scripts/tree/64fee0c02b9/item/util.sh#L39-49
  } || printf -- '%s' "${@}"; } |
    # `-A n` hide the address base
    # `-t o1` convert to octal
    od \
      -A n \
      -t o1 |
    sed \
      -n \
      -e '# move the results onto one line' \
      -e 'H' \
      -e '$ {' \
      -e '  x' \
      -e '  # remove trailing final spaces, tabs, and newlines' \
      -e '  s/[[:space:]]*$//' \
      -e '  # replace all remaining strings of spaces, tabs, or newlines with a single backslash "\"' \
      -e '  s/[[:space:]][[:space:]]*/\\/gp' \
      -e '}'
}

ocr() {
  command -v -- ocrmypdf >/dev/null 2>&1 ||
    # EX_UNAVAILABLE
    return 69
  test "${#}" -gt 0 ||
    # EX_USAGE
    return 64
  #
  # TODO! make this work on all PDFs in folder if no argument is provided
  #
  for file in "${@}"; do
    test -s "${file-}" &&
      test ! -L "${file-}" &&
      case "${file-}" in
      *.[Pp][Dd][Ff])
        # useful when processing multiple files
        printf -- '\n%s\n' "${file-}" >&2 &&
          ocrmypdf \
            --deskew \
            --language eng \
            --optimize 0 \
            --output-type pdfa \
            --pdfa-image-compression lossless \
            --rotate-pages \
            --skip-text \
            -- \
            "${file-}" "${file-}"
        ;;
      *)
        shift 1
        ;;
      esac
  done
}
ocr_eo() {
  command -v -- ocrmypdf >/dev/null 2>&1 ||
    # EX_UNAVAILABLE
    return 69
  test "${#}" -gt 0 ||
    # EX_USAGE
    return 64
  for file in "${@}"; do
    test -s "${file-}" &&
      test ! -L "${file-}" &&
      case "${file-}" in
      *.[Pp][Dd][Ff])
        printf -- '\n%s\n' "${file-}" >&2 &&
          ocrmypdf \
            --deskew \
            --language eng+epo \
            --optimize 0 \
            --output-type pdfa \
            --pdfa-image-compression lossless \
            --rotate-pages \
            --skip-text \
            -- \
            "${file-}" "${file-}"
        ;;
      *)
        shift 1
        ;;
      esac
  done
}

office_update() {
  # https://github.com/PAPAMICA/terminal/commit/a07e1d8477
  find -- '/Library/Application Support/Microsoft' \
    -path '/Library/Application Support/Microsoft/*.git' -prune -o \
    -path '/Library/Application Support/Microsoft/*/node_modules' -prune -o \
    -path '/Library/Application Support/Microsoft/*' \
    -name 'msupdate' \
    -type f \
    -perm -700 \
    -exec {} --list ';' 2>/dev/null
}

# open current directory if no argument is given
open() {
  if test "${#}" -eq 0; then
    open -- "${PWD:-.}"
  else
    case "${1-}" in
    P)
      { test "${2-}" != '' &&
        open -- 'https://pubs.opengroup.org/onlinepubs/9799919799/utilities/'"${2-}"'.html#top'; } ||
        open -- 'https://pubs.opengroup.org/onlinepubs/9799919799/idx/utilities.html'
      ;;
    p)
      { test "${2-}" != '' &&
        open -- 'https://pubs.opengroup.org/onlinepubs/9699919799/utilities/'"${2-}"'.html#top'; } ||
        open -- 'https://pubs.opengroup.org/onlinepubs/9699919799/idx/utilities.html'
      ;;
    B)
      { test "${2-}" != '' &&
        open -- 'https://pubs.opengroup.org/onlinepubs/9799919799/utilities/V3_chap02.html#'"${2-}"; } ||
        open -- 'https://pubs.opengroup.org/onlinepubs/9799919799/idx/sbi.html'
      ;;
    b)
      { test "${2-}" != '' &&
        open -- 'https://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#'"${2-}"; } ||
        open -- 'https://pubs.opengroup.org/onlinepubs/9699919799/idx/sbi.html'
      ;;
    g)
      shift 1 &&
        gopen "${@}"
      ;;
    sc*)
      open -- 'https://github.com/koalaman/shellcheck/wiki/SC'"${1#sc}"
      ;;
    SC*)
      open -- 'https://github.com/koalaman/shellcheck/wiki/'"${1-}"
      ;;
    *)
      open "${@}"
      ;;
    esac
  fi
}
# if there is no `xdg-open`, then alias it to `open`
command -v -- xdg-open >/dev/null 2>&1 ||
  alias xdg-open='open'

## pax
unpax() {
  while test "${#}" -gt 0; do
    uncompress -f -v -- "${1-}" &&
      set -- "${1%.Z}"
    pax -r -v -f "${1-}"
    shift 1
  done
}

## pasteboard
pbc() {
  # gather content, but also print it
  pbcopy &&
    pbpaste
}
# https://github.com/ferrarimarco/dotfiles/commit/dc9e378f37
command -v -- pbcopy >/dev/null 2>&1 ||
  alias pbcopy='xclip -selection clipboard'
command -v -- pbpaste >/dev/null 2>&1 ||
  alias pbpaste='xclip -selection clipboard -o'

pdf_images() {
  ## extract images from a PDF
  # requires `pdfimages` from `poppler`
  command -v -- pdfimages >/dev/null 2>&1 ||
    # EX_UNAVAILABLE
    return 69
  test "${#}" -gt 0 ||
    # EX_USAGE
    return 64
  set \
    -o noclobber \
    -o noglob \
    -o verbose \
    -o xtrace
  for file in "${@}"; do
    test -s "${file-}" &&
      test ! -L "${file-}" &&
      case "${file-}" in
      *.[Pp][Dd][Ff])
        # -p: add page numbers to filenames
        # -print-filenames: to standard output
        pdfimages \
          -all \
          -p \
          -print-filenames \
          "${file-}" \
          "${file%.*}"-
        ;;
      *) ;;
      esac
  done
  {
    set \
      +o noclobber \
      +o noglob \
      +o verbose \
      +o xtrace
  } 2>/dev/null
}

perltidy_r() {
  set \
    -o noclobber \
    -o noglob \
    -o nounset \
    -o verbose \
    -o xtrace
  command -v -- find_perl_files >/dev/null 2>&1 &&
    command -v -- perltidy >/dev/null 2>&1 ||
    # EX_UNAVAILABLE
    return 69
  find_perl_files | while IFS='' read -r -- file; do
    git ls-files --error-unmatch -- "${file-}" >/dev/null 2>&1 ||
      ! git rev-parse --is-inside-work-tree >/dev/null 2>&1 &&
      test -s "${file-}" &&
      test ! -L "${file-}" &&
      mkdir -p -- "${TMPDIR:-${TEMP:-${TMP:-/tmp}}}"'/perltidy' &&
      cp -f -p -- "${file-}" "${TMPDIR:-${TEMP:-${TMP:-/tmp}}}"'/perltidy/'"${file##*/}" &&
      perltidy --outfile "${file-}" "${TMPDIR:-${TEMP:-${TMP:-/tmp}}}"'/perltidy/'"${file##*/}"
  done
  {
    set \
      +o noclobber \
      +o noglob \
      +o nounset \
      +o verbose \
      +o xtrace
  } 2>/dev/null
}

permissions() {
  # restore default file and directory permissions and
  # set owner and group to current user
  set -o xtrace
  git rev-parse --is-inside-work-tree >/dev/null 2>&1 ||
    return "${?:-1}"
  chown -R "$(id -u)":"$(id -g)" .
  # make all directories traversable
  find -- . -type d -exec chmod -- 755 {} +
  # set non-dotfiles to read-only
  find -- . -path '*/.*' -prune -o -type f -exec chmod -- 644 {} +
  # make git hooks executable
  find -- . -path '*/.git/hooks/*' -type f -exec chmod -- 755 {} +
  find -- . -path '*/.git/objects' -prune -o -path '*/.git/hooks' -prune -o -type f -exec chmod -- 644 {} +
  find -- . -path '*/.git/objects/*' -type f -exec chmod -- 444 {} +
  {
    set +o xtrace
  } 2>/dev/null
}

posix_character_classes() {
  set -- 'https://pubs.opengroup.org/onlinepubs/9699919799/utilities/tr.html'
  {
    wget \
      --hsts-file=/dev/null \
      --output-document=- \
      --quiet \
      -- \
      "${1-}" ||
      curl \
        --fail \
        --location \
        --show-error \
        --silent \
        --url "${1-}"
  } 2>/dev/null |
    sed \
      -n \
      -e '/"tent"/ {' \
      -e '  s/.*>\([[:alpha:]]\{1,\}\).*/[:\1:]/p' \
      -e '}' |
    LANG='C' LC_ALL='C' sort -u
}

posix_special_utilities_list() {
  # break colon continue dot eval exec exit export readonly return set
  # shift times trap unset
  printf -- 'break colon continue dot eval exec exit export readonly return set shift times trap unset\n'
}
alias posix_builtins_list='posix_special_utilities_list'
posix_utilities_list() {
  # admin alias ar asa at awk basename batch bc bg c̸9̸9̸ [c17] cal cat cd cflow
  # chgrp chmod chown cksum cmp comm command compress cp crontab csplit
  # ctags cut cxref date dd delta df diff dirname du echo ed env ex expand
  # expr false fc fg file find fold f̸o̸r̸t̸7̸7̸ fuser gencat get getconf getopts [gettext]
  # grep hash head iconv id ipcrm ipcs jobs join kill lex link ln locale
  # localedef logger logname lp ls m4 mailx make man mesg mkdir mkfifo more [msgfmt]
  # mv newgrp [ngettext] nice nl nm nohup od paste patch pathchk pax pr printf prs ps
  # pwd q̸a̸l̸t̸e̸r̸ q̸d̸e̸l̸ q̸h̸o̸l̸d̸ q̸m̸o̸v̸e̸ q̸m̸s̸g̸ q̸r̸e̸r̸u̸n̸ q̸r̸l̸s̸ q̸s̸e̸l̸e̸c̸t̸ q̸s̸i̸g̸ q̸s̸t̸a̸t̸ q̸s̸u̸b̸
  # read [readlink] [realpath] renice rm rmdel rmdir sact sccs sed sh sleep sort split strings
  # strip stty tabs tail talk tee test time [timeout] touch tput tr true tsort tty
  # type ulimit umask unalias uname uncompress unexpand unget uniq unlink
  # uucp uudecode uuencode uustat uux val vi wait wc what who write xargs [xgettext]
  # yacc zcat
  curl \
    --show-error \
    --silent \
    --url 'https://pubs.opengroup.org/onlinepubs/9699919799/idx/utilities.html' |
    # https://archive.today/2022.10.19-184853/https://cyberciti.biz/faq/?p=12818
    sed \
      -e ':a' \
      -e 'N' \
      -e '$! b a' \
      -e 's/\n/ /g' \
      -e '# remove Utilities headers' \
      -e 's/.*<ul>//' \
      -e '# remove elements, even if successive' \
      -e 's/\( *<[^>]*>\)*\([[:alnum:]]*\)/\2 /g' \
      -e '# remove the last trailing spaces' \
      -e 's/[[:space:]]*$//' \
      -e 's/c99 /c17 /' \
      -e 's/fort77 //' \
      -e 's/getopts /getopts gettext /' \
      -e 's/more /more msgfmt /' \
      -e 's/newgrp /newgrp ngettext /' \
      -e 's/qalter //' \
      -e 's/qdel //' \
      -e 's/qhold //' \
      -e 's/qmove //' \
      -e 's/qmsg //' \
      -e 's/qrerun //' \
      -e 's/qrls //' \
      -e 's/qselect //' \
      -e 's/qsig //' \
      -e 's/qstat //' \
      -e 's/qsub //' \
      -e 's/read /read readlink realpath /' \
      -e 's/time /time timeout /' \
      -e 's/xargs /xargs xgettext /'
}

posix_variables_list() {
  # 77 “frequently exported” variables in “wide[] use[]”
  # https://gitlab.opengroup.org/the-austin-group/sus_html/blob/2af5dfdd37/html/basedefs/V1_chap08.html#L98-389
  # ARFLAGS CC CDPATH CFLAGS CHARSET COLUMNS DATEMSK DEAD EDITOR ENV EXINIT \
  # FC FCEDIT FFLAGS GET GFLAGS HISTFILE HISTORY HISTSIZE HOME IFS LANG \
  # LC_ALL LC_COLLATE LC_CTYPE LC_MESSAGES LC_MONETARY LC_NUMERIC LC_TIME \
  # LDFLAGS LEX LFLAGS LINENO LINES LISTER LOGNAME LPDEST MAIL MAILCHECK \
  # MAILER MAILPATH MAILRC MAKEFLAGS MAKESHELL MANPATH MBOX MORE MSGVERB \
  # NLSPATH NPROC OLDPWD OPTARG OPTERR OPTIND PAGER PATH PPID PRINTER \
  # PROCLANG PROJECTDIR PS1 PS2 PS3 PS4 PWD RANDOM SECONDS SHELL TERM \
  # TERMCAP TERMINFO TMPDIR TZ USER VISUAL YACC YFLAGS
  set -- 'https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap08.html'
  {
    wget --hsts-file=/dev/null --output-document=- --quiet -- "${1-}" ||
      curl --fail --show-error --silent --url "${1-}"
  } 2>/dev/null |
    sed \
      -n \
      -e '/"tent"/ {' \
      -e '  s/.*>\([[:upper:]]\{1,\}[[:upper:]_]*\).*/\1/p' \
      -e '}' |
    LANG='C' LC_ALL='C' sort -u |
    LANG='C' LC_ALL='C' sort -f |
    while IFS='' read -r -- variable; do
      test "$(eval " printf -- '%s\n' \$${variable-}" 2>/dev/null)" = '' ||
        printf -- '%s:\t%s\n' "${variable-}" "$(eval " printf -- '%s\n' \$${variable-}")"
    done
  shift 1
  #   @TODO:
  #   printf -- 'ADMIN:%-12s%s\n' "${ADMIN-}"
  #   because the longest variable names are 11 characters long
  for variable in ARFLAGS IFS MAILPATH PS1 CC LANG MAILRC PS2 CDPATH LC_ALL MAKEFLAGS PS3 CFLAGS LC_COLLATE MAKESHELL PS4 CHARSET LC_CTYPE MANPATH PWD COLUMNS LC_MESSAGES MBOX RANDOM DATEMSK LC_MONETARY MORE SECONDS DEAD LC_NUMERIC MSGVERB SHELL EDITOR LC_TIME NLSPATH TERM ENV LDFLAGS NPROC TERMCAP EXINIT LEX OLDPWD TERMINFO FC LFLAGS OPTARG TMPDIR FCEDIT LINENO OPTERR TZ FFLAGS LINES OPTIND USER GET LISTER PAGER VISUAL GFLAGS LOGNAME PATH YACC HISTFILE LPDEST PPID YFLAGS HISTORY MAIL PRINTER HISTSIZE MAILCHECK PROCLANG HOME MAILER PROJECTDIR; do
    eval " echo ${variable-}:		\$${variable-}" 2>/dev/null
  done
}

## iCloud
priority() {
  # increase priority of running process
  # default iCloud/`bird`
  sudo -- renice -n -20 -p "$(
    ps -a -u "$(
      id -u
    )" |
      awk -vquery="${1:-bird}" -- '$0 ~ query {print $2; exit}'
  )" ||
    return "${?:-1}"
}

pledit() {
  # based on Joe Block’s `pledit`
  # Convert a binary plist file to XML and open with `$EDITOR`
  # Copyright 2017, Joe Block <jpb@unixorn.net>
  # https://github.com/unixorn/tumult.plugin.zsh/blob/2f83fb8287/bin/pledit
  command -v -- plutil >/dev/null 2>&1 ||
    # EX_UNAVAILABLE
    return 69
  test "${#}" -gt 0 ||
    # EX_USAGE
    return 64
  for file in "${@}"; do
    test -s "${file-}" &&
      test ! -L "${file-}" &&
      # convert the binary file to XML
      plutil -convert xml1 -- "${file-}" &&
      # open with the default editor
      "${EDITOR:-vi}" -- "${file-}"
  done
}

# .plist
plist_r() {
  command -v -- plutil >/dev/null 2>&1 ||
    # EX_UNAVAILABLE
    return 69
  set \
    -o verbose \
    -o xtrace
  case "$(pwd -P)" in
  "${HOME%/}" | */trash)
    printf -- 'permission error\n' >&2
    printf -- 'do not run command \140plist_r\140 ' >&2
    printf -- 'from directory \140%s/\140\n' "${PWD##*/}" >&2
    # EX_NOPERM
    return 77
    ;;
  *)
    if test "${#}" -eq 0; then
      # https://bit.ly/apple_property_list_filename_extensions
      find -- . \
        -path '*/Library' -prune -o \
        -path "${DOTFILES-}"'/*' -prune -o \
        -path '*/Trash' -prune -o \
        -path '*/trash' -prune -o \
        '(' \
        -name '*.plist' -o \
        -name '*.aae' -o \
        -name '*.appex' -o \
        -name '*.bbColorScheme' -o \
        -name '*.caar' -o \
        -name '*.codesnippet' -o \
        -name '*.entitlements' -o \
        -name '*.fileloc' -o \
        -name '*.glyphs' -o \
        -name '*.idekeybindings' -o \
        -name '*.inetloc' -o \
        -name '*.intentdefinition' -o \
        -name '*.itermcolors' -o \
        -name '*.loctable' -o \
        -name '*.mobileconfig' -o \
        -name '*.mom' -o \
        -name '*.plist.in' -o \
        -name '*.scriptSuite' -o \
        -name '*.strings' -o \
        -name '*.stringsdict' -o \
        -name '*.stTheme' -o \
        -name '*.tagpool' -o \
        -name '*.tagset' -o \
        -name '*.textClipping' -o \
        -name '*.tmCommand' -o \
        -name '*.tmLanguage' -o \
        -name '*.tmMacro' -o \
        -name '*.tmPreferences' -o \
        -name '*.tmSnippet' -o \
        -name '*.tmTheme' -o \
        -name '*.ttps' -o \
        -name '*.waveform' -o \
        -name '*.webarchive' -o \
        -name '*.webloc' -o \
        -name '*.wflow' -o \
        -name '*.xccheckout' -o \
        -name '*.xccolortheme' -o \
        -name '*.xccurrentversion' -o \
        -name '*.xcprivacy' -o \
        -name '*.xcsettings' -o \
        -name '*.xcuserstate' \
        ')' \
        -type f \
        -exec sh -x -c -- 'git ls-files --error-unmatch -- "${1-}" >/dev/null 2>&1 || ! git rev-parse --is-inside-work-tree >/dev/null 2>&1 && plutil -convert xml1 -o /tmp/"${1##*/}" -- "${1-}" && sed -e '\''# replace tabs with two spaces each'\'' -e '\''s/\t/  /g'\'' -e '\''# insert each indented line by two more spaces'\'' -e '\''s/^  /    /'\'' -e '\''# indent top-level <dict> elements by two spaces'\'' -e '\''s/^\(<\/\{0,1\}dict>\)/  \1/'\'' /tmp/"${1##*/}" >"${1-}"' _ {} ';'
    else
      while test "${#}" -gt 0; do
        plutil -convert xml1 -o "${TMPDIR:-/tmp}"'/'"${1##*/}" -- "${1-}" &&
          sed \
            -e '# replace tabs with two spaces each' \
            -e 's/\t/  /g' \
            -e '# insert each indented line by two more spaces' \
            -e 's/^  /    /' \
            -e '# indent top-level <dict> elements by two spaces' \
            -e 's/^\(<\/\{0,1\}dict>\)/  \1/' \
            "${TMPDIR:-/tmp}"'/'"${1##*/}" >"${1-}"
        shift 1
      done
    fi
    ;;
  esac
  {
    set \
      +o verbose \
      +o xtrace
  } 2>/dev/null
}

# PlistBuddy
command -v -- /usr/libexec/PlistBuddy >/dev/null 2>&1 &&
  # https://apple.stackexchange.com/a/414774
  alias plistbuddy='/usr/libexec/PlistBuddy'

## PNG
to_png() {
  command -v -- magick >/dev/null 2>&1 ||
    # EX_UNAVAILABLE
    return 69
  test "${#}" -gt 0 ||
    # EX_USAGE
    return 64
  set \
    -o noclobber \
    -o noglob \
    -o xtrace
  for file in "${@}"; do
    magick \
      -background none \
      -density "${d:-2048}" \
      -quality 100 \
      -verbose \
      -- \
      "${file-}" \
      "${file%.*}"'.transparent.png' &&
      magick \
        -background white \
        -density "${d:-2048}" \
        -quality 100 \
        -verbose \
        -- \
        "${file-}" \
        "${file%.*}"'.white.png'
  done
  {
    set \
      +o noclobber \
      +o noglob \
      +o xtrace
  } 2>/dev/null
}

# AdvPNG (AdvanceCOMP)
advpng_r() {
  command -v -- advpng >/dev/null 2>&1 ||
    # EX_UNAVAILABLE
    return 69
  test "${#}" -gt 0 ||
    # EX_USAGE
    return 64
  set \
    -o noclobber \
    -o verbose \
    -o xtrace
  for file in "${@}"; do
    test -s "${file-}" &&
      test ! -L "${file-}" &&
      case "${file-}" in
      *.[Pp][Nn][Gg])
        advpng \
          --recompress \
          --shrink-insane \
          --iter 1024 \
          -- \
          "${file-}"
        ;;
      *) ;;
      esac
  done
  {
    set \
      +o noclobber \
      +o verbose \
      +o xtrace
  } 2>/dev/null
}

# OptiPNG
optipng_r() {
  command -v -- optipng >/dev/null 2>&1 ||
    # EX_UNAVAILABLE
    return 69
  test "${#}" -gt 0 ||
    # EX_USAGE
    return 64
  set \
    -o noclobber \
    -o verbose \
    -o xtrace
  for file in "${@}"; do
    test -s "${file-}" &&
      test ! -L "${file-}" &&
      case "${file-}" in
      *.[Pp][Nn][Gg])
        optipng \
          -fix \
          -force \
          -nb \
          -nc \
          -np \
          -nx \
          -o 7 \
          -out "${file%.*}"'-optipng.png' \
          -strip all \
          -verbose \
          -zm 1-9 \
          -- \
          "${file-}"
        ;;
      *) ;;
      esac
  done
  {
    set \
      +o noclobber \
      +o verbose \
      +o xtrace
  } 2>/dev/null
}

# OxiPNG
oxipng_r() {
  command -v -- oxipng >/dev/null 2>&1 ||
    # EX_UNAVAILABLE
    return 69
  test "${#}" -gt 0 ||
    # EX_USAGE
    return 64
  set \
    -o noclobber \
    -o verbose \
    -o xtrace
  for file in "${@}"; do
    test -s "${file-}" &&
      test ! -L "${file-}" &&
      case "${file-}" in
      *.[Pp][Nn][Gg])
        oxipng \
          --filters=0,9 \
          --opt=max \
          --out="${file%.*}"'-oxipng.png' \
          --strip=all \
          --verbose \
          --zopfli \
          -- \
          "${file-}"
        ;;
      *) ;;
      esac
  done
  {
    set \
      +o noclobber \
      +o verbose \
      +o xtrace
  } 2>/dev/null
}

# pngcrush
pngcrush_r() {
  command -v -- pngcrush >/dev/null 2>&1 ||
    # EX_UNAVAILABLE
    return 69
  test "${#}" -gt 0 ||
    # EX_USAGE
    return 64
  set \
    -o noclobber \
    -o verbose \
    -o xtrace
  for file in "${@}"; do
    test -s "${file-}" &&
      test ! -L "${file-}" &&
      case "${file-}" in
      *-pngcrush.png)
        shift 1
        ;;
      *.[Pp][Nn][Gg])
        pngcrush \
          -brute \
          -fix \
          -force \
          -reduce \
          -v \
          -- \
          "${file-}" \
          "${file%.*}"'-pngcrush.png'
        ;;
      *) ;;
      esac
  done
  {
    set \
      +o noclobber \
      +o verbose \
      +o xtrace
  } 2>/dev/null
}

pngout_r() {
  command -v -- pngout >/dev/null 2>&1 ||
    # EX_UNAVAILABLE
    return 69
  test "${#}" -gt 0 ||
    # EX_USAGE
    return 64
  set \
    -o noclobber \
    -o verbose \
    -o xtrace
  for file in "${@}"; do
    test -s "${file-}" &&
      test ! -L "${file-}" &&
      pngout \
        -b0 \
        -d0 \
        -f4 \
        -k0 \
        -s0 \
        -v \
        -y \
        "${file-}" \
        "${file%.*}"'-pngout.png'
  done
  {
    set \
      +o noclobber \
      +o verbose \
      +o xtrace
  } 2>/dev/null
}

# $?
question_mark() {
  # `??`: return a specific error in the very unlikely event that `$?` is not set
  printf -- '%d\n' "${??}"
}
alias '?'='question_mark'

# QuickLook
ql() {
  command -v -- qlmanage >/dev/null 2>&1 ||
    # EX_UNAVAILABLE
    return 69
  test "${#}" -gt 0 ||
    # EX_USAGE
    return 64
  case "${1-}" in
  -r)
    find -- . \
      -path './*/*' -prune -o \
      -path './*.*.*' -prune -o \
      -path './* *' -prune -o \
      '(' \
      -path './[Rr][Ee][Aa][Dd]*[Mm][Ee]*' -o \
      -path './[Cc][Ll][Ii][Cc][Kk]*[Mm][Ee]*' -o \
      -path './[Kk][Ee][Ee][Pp]*[Mm][Ee]*' \
      ')' \
      -type f \
      -exec sh -c -- 'case "${1-}" in
*.asciidoc | *.adoc | *.asc)
  bat \
    --decorations=never \
    --language=asciidoc \
    --paging=never \
    -- \
    "${1-}" 2>/dev/null ||
    cat \
    -- \
    "${1-}"
  ;;
*)
  qlmanage -p -- "${1-}" >/dev/null 2>&1 ||
    bat \
      --decorations=never \
      --paging=never \
      -- \
      "${1-}" 2>/dev/null ||
    cat \
    -- \
    "${1-}"
  ;;
esac' _ {} +
    ;;
  *)
    while test "${#}" -ne 0; do
      qlmanage -p -- "${1-}" >/dev/null 2>&1 &&
        shift 1
    done
    ;;
  esac
}
alias qlr='ql -r'

quote() {
  # shell-quoting arbitrary strings
  # https://web.archive.org/web/0id_/etalabs.net/sh_tricks.html
  for string in "${@}"; do
    printf -- '%s\n' "${string-}" |
      sed \
        -e "$(
          printf -- 's/\047/\047\\\\\047\047/g'
        )" \
        -e '1 s/^/'\''/' \
        -e '$ s/$/'\''/'
  done
}
alias printf_q='quote'

RANDOM() {
  # https://shellcheck.net/wiki/SC3028/1f83d59#correct-code
  awk -vmax="$(getconf -- SHRT_MAX)" -- 'BEGIN {
  srand()
  printf "%d\n", int(rand() * max)
}'
}

random_r() {
  set \
    -o noclobber \
    -o noglob \
    -o nounset \
    -o verbose \
    -o xtrace
  printf -- '%s:powershell:pwsh\n' "${SHELLS-}" |
    sed \
      -e '# posh lacks support' \
      -e 's/^posh://' \
      -e 's/:posh$//' \
      -e 's/:posh://' |
    sed -e 's/:/\n/g' | while IFS='' read -r -- shell; do
    { eval " $(printf -- '%s -c \047\042%s\140t\044(Get-Random)\042\047\n' "${shell-}" "${shell-}")" ||
      eval " $(printf -- '%s -c \047printf -- \047\134\047\047%s\134t\045s\134n\047\134\047\047 "\044{RANDOM}"\047\n' "${shell-}" "${shell-}")"; } |
      sed \
        -n \
        -e '/[[:space:]][[:digit:]]/p' \
        -e 'q' |
      LANG='C' LC_ALL='C' sort
  done 2>/dev/null
  awk -vmax="$(getconf -- SHRT_MAX)" -- 'BEGIN {
  srand()
  printf "awk\t%d\n", int(rand() * max)
}'
  {
    set \
      +o noclobber \
      +o noglob \
      +o nounset \
      +o verbose \
      +o xtrace
  } 2>/dev/null
}

random_string() {
  # ensure `/dev/urandom` or `/dev/random` is a character special
  if test -c /dev/urandom; then
    set -- "${1:-10}" /dev/urandom
  elif test -c /dev/random; then
    set -- "${1:-10}" /dev/random
  else
    # EX_OSFILE
    return 72
  fi
  # print all non-space ASCII characters
  LANG='C' LC_ALL='C' tr -c -d -- '\41-\176' <"${2-}" |
    # default to 10 characters
    dd bs=1 count="${1:-10}" 2>/dev/null &&
    printf -- '\n' >&2
}

rbenv_update_r() {
  command -v -- rbenv >/dev/null 2>&1 ||
    # EX_UNAVAILABLE
    return 69
  test -d "$(rbenv prefix 2>/dev/null)" ||
    # EX_NOINPUT
    return 66
  set \
    -o verbose \
    -o xtrace
  find -- "$(rbenv prefix)"'/bin' \
    -path "$(rbenv prefix)"'/bin/*/*' -prune -o \
    -type f \
    -perm -700 \
    -exec sh -x -c -- 'for file in "${@}"; do
  gem install --verbose "${file##*/}"
done' _ {} +
  {
    set \
      +o verbose \
      +o xtrace
  } 2>/dev/null
}
alias gem_update_r='rbenv_update_r'

## Rectangle
# set ⌘⌥F to maximize the focused window
alias rectangle_shortcut='defaults write com.knollsoft.Rectangle maximize -dict-add keyCode -float 3 modifierFlags -float 1572864 2>/dev/null'

## rename
rename_install() {
  command -v -- rename 2>/dev/null || {
    set -- "${DOTFILES-}"'/bin/rename' 'https://github.com/ap/rename/raw/HEAD/rename' &&
      command -v -- brew >/dev/null 2>&1 && {
      brew install --HEAD -- "${1##*/}" ||
        brew install -- "${1##*/}"
    } ||
      printf -- ':%s:\n' "${PATH-}" | grep -e ':'"${1%/*}"':' >/dev/null 2>&1 && {
      wget --hsts-file=/dev/null --quiet --output-document="${1-}" -- "${2-}" ||
        curl --fail --location --show-error --silent --output "${1-}" --url "${2-}"
    } 2>/dev/null &&
      chmod -- 755 "${1-}"
  }
}
rename_sanitize() {
  # usage rename_sanitize [ -l ] [ -n ]
  # -l: rename using lowercase
  # -n: dry run
  command -v -- rename >/dev/null 2>&1 ||
    # EX_UNAVAILABLE
    return 69
  while getopts 'ln' opt; do
    case "${opt-}" in
    l)
      l='--lower-case'
      ;;
    n)
      n='--dry-run'
      ;;
    *) ;;
    esac
  done
  shift "$((OPTIND - 1))"

  find -- . \
    -depth \
    ! -path '*/.git/*' \
    ! -path '*/.well-known/*' \
    ! -path '*/Library/*' \
    ! -path '*/node_modules/*' \
    ! -path '*/t/*' \
    ! -path '*/Test*' \
    ! -path '*/test*' \
    ! -path '*/tst*' \
    ! -path '*copilot*' \
    ! -path '*dummy*' \
    ! -path '*vscode*' \
    ! -name '*.icloud' \
    ! -name '.DS_Store' \
    -exec rename \
    --make-dirs \
    --sanitize \
    --subst '_at_' '_' \
    --subst 'libgen.li' '' \
    --subst-all '+' '_' \
    --subst-all '__' '_' \
    --subst-all '_.' '.' \
    --subst-all '-.' '.' \
    --transcode=ascii \
    --urlesc \
    --verbose \
    "${l-}" \
    "${n-}" \
    -- \
    {} +
  unset l >/dev/null 2>&1 || l=''
  unset n >/dev/null 2>&1 || n=''
}
rename_r() {
  command -v -- rename >/dev/null 2>&1 ||
    # EX_UNAVAILABLE
    return 69
  case "${#}" in
  2)
    find -- . \
      -depth \
      ! -path '*/.git/*' \
      ! -path '*/.well-known/*' \
      ! -path '*/Library/*' \
      ! -path '*/node_modules/*' \
      ! -path '*/t/*' \
      ! -path '*/Test*' \
      ! -path '*/test*' \
      ! -path '*/tst*' \
      ! -path '*copilot*' \
      ! -path '*dummy*' \
      ! -path '*vscode*' \
      -exec rename \
      --verbose \
      --make-dirs \
      --subst "${1-}" "${2-}" \
      -- \
      {} +
    ;;
  0)
    find -- . \
      -depth \
      ! -path '*/.git/*' \
      ! -path '*/.well-known/*' \
      ! -path '*/Library/*' \
      ! -path '*/node_modules/*' \
      ! -path '*/t/*' \
      ! -path '*/Test*' \
      ! -path '*/test*' \
      ! -path '*/tst*' \
      ! -path '*copilot*' \
      ! -path '*dummy*' \
      ! -path '*vscode*' \
      -type f \
      -exec rename \
      --force \
      --make-dirs \
      --sanitize \
      --subst '_at_' '_' \
      --subst-all '+' '_' \
      --subst-all '__' '_' \
      --transcode=ascii \
      --urlesc \
      --verbose \
      -- \
      {} +
    ;;
  *)
    return 1
    ;;
  esac
}

rename_with_dimensions() {
  command -v -- exiftool >/dev/null 2>&1 ||
    # EX_UNAVAILABLE
    return 69
  test "${#}" -gt 0 ||
    # EX_USAGE
    return 64
  set \
    -o noclobber \
    -o noglob \
    -o verbose \
    -o xtrace
  for file in "${@}"; do
    git rev-parse --is-inside-work-tree >/dev/null 2>&1 &&
      test -s "${file-}" &&
      test ! -L "${file-}" &&

      # if extracting the image dimensions works...
      exiftool -ImageSize -short3 -- "${file-}" >/dev/null 2>&1 &&

      # then rename the file
      mv -i -- \
        "${file-}" \
        "${file%.*}"'.'"$(exiftool -ImageSize -short3 -- "${file-}")"'.'"${file##*.}"
  done
  {
    set \
      +o noclobber \
      +o noglob \
      +o verbose \
      +o xtrace
  } 2>/dev/null
}

rpm_extract() {
  command -v -- rpm2cpio >/dev/null 2>&1 &&
    command -v -- cpio >/dev/null 2>&1 ||
    # EX_UNAVAILABLE
    return 69
  find -- . \
    -path '*/.git' -prune -o \
    -path '*/node_modules' -prune -o \
    '(' \
    -name '*.rpm' -o \
    -name '*.[Rr][Pp][Mm]' \
    ')' \
    -type f \
    -exec sh -x -c -- 'for file in "${@}"; do mkdir -p -- "$(basename -- "${file%.*}")" && rpm2cpio -- "${file-}" >"$(basename -- "${file%.*}")"'\''/'\''"$(basename -- "${file%.*}"'\''.cpio'\'')" && CDPATH='\''.'\'' cd "$(basename -- "${file%.*}")" >/dev/null 2>&1 && test -s "$(basename -- "${file%.*}"'\''.cpio'\'')" && cpio --extract --make-directories --verbose <"$(basename -- "${file%.*}"'\''.cpio'\'')" && rm -- "$(basename -- "${file%.*}"'\''.cpio'\'')" && CDPATH='\''.'\'' cd "${OLDPWD:--}" >/dev/null 2>&1 && rm -- "${file-}"; done' _ {} +
}

rsync_r() {
  command -v -- rsync >/dev/null 2>&1 ||
    # EX_UNAVAILABLE
    return 69
  case "${1-}" in
  c | k | o)
    target='kevoc7@oconnor.nyc:/home/kevoc7/.local/share/Trash/'"${2##*/}"
    ;;
  f)
    target='llarson@freeshell.de:/home/l/llarson/.local/share/Trash/'"${2##*/}"
    ;;
  l)
    target='lucaslarson@lucaslarson.net:/home/lucaslarson/.local/share/Trash/'"${2##*/}"
    ;;
  s)
    target='ll@tty.sdf.org:/sdf/arpa/gm/l/ll/.local/share/Trash/'"${2##*/}"
    ;;
  *)
    # EX_USAGE
    return 64
    ;;
  esac
  shift 1
  while test "${#}" -gt 0; do
    rsync --archive --compress --partial --progress --verbose -- "${1-}" "${target-}"
    shift 1
  done
  unset target >/dev/null 2>&1 || target=''
}

## rubocop
rubocop_r() {
  command -v -- find_ruby_files >/dev/null 2>&1 &&
    command -v -- rubocop >/dev/null 2>&1 ||
    # EX_UNAVAILABLE
    return 69
  find_ruby_files | while IFS='' read -r -- file; do
    git ls-files --error-unmatch -- "${file-}" >/dev/null 2>&1 ||
      ! git rev-parse --is-inside-work-tree >/dev/null 2>&1 &&
      rubocop \
        --autocorrect-all \
        --extra-details \
        --format github \
        --format progress \
        -- \
        "${file-}"
  done
}

## rustfmt
rustfmt_r() {
  command -v -- rustfmt >/dev/null 2>&1 ||
    # EX_UNAVAILABLE
    return 69
  set \
    -o verbose \
    -o xtrace
  find -- . \
    -name '*.rs' \
    -type f \
    -exec sh -x -c -- 'git ls-files --error-unmatch -- "${1-}" >/dev/null 2>&1 ||
  ! git rev-parse --is-inside-work-tree >/dev/null 2>&1 &&
  rustfmt --emit files --verbose -- "${1-}"
' _ {} ';'
  {
    set \
      +o verbose \
      +o xtrace
  } 2>/dev/null
}

sc() {
  for file in "${@:-${DOTFILES-}/custom/aliases.sh}"; do
    case "${file-}" in
    --) shift 1 && continue ;;
    -h* | --help)
      printf -- 'Usage: sc [--] [file ...]\n' >&2
      # EX_OK
      return 0
      ;;
    *)
      test -f "${file-}" ||
        # EX_NOINPUT
        return 66
      printf -- '%s\n' "${SHELLS-}" |
        sed \
          -e 's/:/\n/g' |
        while IFS='' read -r -- shell; do
          command -v -- "${shell-}" >/dev/null 2>&1 &&
            {
              PS4=' '
              set -o xtrace
              "${shell-}" -C -e -n -u -x -o noglob -- "${file-}"
              { set +o xtrace; } 2>/dev/null
            } 2>&1 |
            sed \
              -e 's/^/  /' \
              -e 's/-- .*\//-- /'
        done
      sca "${file-}"
      ;;
    esac
  done
}

sca() {
  while getopts -- 's:' opt; do
    case "${opt-}" in
    s)
      shell="${OPTARG:-sh}"
      ;;
    *)
      printf -- 'Usage: sca [-s [bash|dash|ksh|sh]] [--] [file]\n' >&2
      ;;
    esac
  done
  shift "$((OPTIND - 1))"
  for file in "${@:-${DOTFILES-}/custom/aliases.sh}"; do
    case "${file-}" in
    --)
      shift 1
      ;;
    *)
      printf -- '%s...\n' "${file##*/}"
      for test in \
        'shellcheck --color=always --enable=all --exclude=SC1071,SC1091,SC2123,SC2312,SC3040 --external-sources --format=gcc --source-path=/dev/null --shell='"${shell:-sh}" \
        'zsh            -C -e    -n -u    -o pipefail -o noglob' \
        'ash            -C -e -f -n -u -x -o pipefail' \
        'bash           -C -e -f -n -u -x -o pipefail -o functrace' \
        'dash           -C -e -f -n -u -x' \
        'dtksh       -b -C -e -f -n -u -x -o pipefail -o posix -o functrace' \
        'fizsh          -C -e    -n -u    -o pipefail -o noglob -o posix_aliases -o posix_arg_zero -o posix_builtins -o posix_cd -o posix_identifiers -o posix_jobs -o posix_strings -o posix_traps' \
        'ksh         -b -C -e -f -n -u -x -o pipefail' \
        'ksh88       -b -C -e -f -n -u -x -o pipefail -o posix -o functrace' \
        'ksh93       -b -C -e -f -n -u -x -o pipefail' \
        'ksh2020     -b -C -e -f -n -u -x -o pipefail' \
        'lksh        -b -C -e -f -n -u -x             -o posix -o sh' \
        'mksh        -b -C -e -f -n -u -x -o pipefail -o posix' \
        'mksh-static -b -C -e -f -n -u -x -o pipefail -o posix' \
        'nksh93      -b -C -e -f -n -u -x -o pipefail -o posix -o functrace' \
        'oksh        -b -C -e -f -n -u -x -o pipefail -o posix' \
        'osh            -C -e -f -n -u -x -o pipefail -o posix --ast-format none' \
        'pdksh       -b -C -e -f -n -u -x -o pipefail -o posix' \
        'pfksh       -b -C -e -f -n -u -x -o pipefail -o posix' \
        'posh           -C -e -f -n -u -x' \
        'psh            -C -e -f -n -u -x -o pipefail' \
        'rbash          -C -e -f -n -u -x -o pipefail -o functrace' \
        'rksh        -b -C -e -f -n -u -x -o pipefail' \
        'rksh93      -b -C -e -f -n -u -x -o pipefail' \
        'rksh2020    -b -C -e -f -n -u -x -o pipefail' \
        'scsh           -C -e -f -n -u -x -o pipefail' \
        'yash           -C -e -f -n -u -x -o pipefail -o posixly-correct' \
        'sh          -C    -e -f -n -u -x' \
        'zsh         -C    -e    -n -u    -o pipefail -o noglob -o posix_aliases -o posix_arg_zero -o posix_builtins -o posix_cd -o posix_identifiers -o posix_jobs -o posix_strings -o posix_traps'; do
        if command -v -- "${test%% *}" >/dev/null 2>&1; then
          { {
            eval " ${test-} -- \"${file-}\"" 2>&1 &&
              printf -- '  passed %s\n' "${test%% *}"
          } ||
            printf -- '    %s failed %s\n' "${file##*/}" "${test%% *}"; } |
            # paths in descending specificity:
            sed \
              -e '/^AST not printed\./ d' \
              -e 's|'"${custom-}"'|$\custom|' \
              -e 's|'"${DOTFILES-}"'|$\DOTFILES|' \
              -e 's|'"${XDG_CONFIG_HOME-}"'|$\XDG_CONFIG_HOME|' \
              -e 's|'"${HOME%/}"'|~|'
        fi
      done
      ;;
    esac
  done
  unset opt >/dev/null 2>&1 || opt=''
}

scour_r() {
  command -v -- scour >/dev/null 2>&1 ||
    # EX_UNAVAILABLE
    return 69
  test "${#}" -gt 0 ||
    # EX_USAGE
    return 64
  set \
    -o noclobber \
    -o verbose \
    -o xtrace
  for file in "${@}"; do
    test -s "${file-}" &&
      test ! -L "${file-}" &&
      git ls-files --error-unmatch -- "${file-}" >/dev/null 2>&1 &&
      case "${file-}" in
      *.[Ss][Vv][Gg])
        scour \
          --create-groups \
          --disable-embed-rasters \
          --enable-comment-stripping \
          --enable-id-stripping \
          --enable-viewboxing \
          --indent=none \
          --nindent=0 \
          --no-line-breaks \
          --protect-ids-noninkscape \
          --remove-descriptions \
          --remove-descriptive-elements \
          --remove-metadata \
          --remove-titles \
          --set-precision="$(getconf -- CHAR_MAX)" \
          --strip-xml-prolog \
          --strip-xml-space \
          --verbose \
          -i "${file-}" \
          -o "${file%.*}"'-scour.svg'
        ;;
      *)
        shift 1
        ;;
      esac
  done
  {
    set \
      +o noclobber \
      +o verbose \
      +o xtrace
  } 2>/dev/null
}

## SDKPATH
# if this from zshrc_commented doesn’t work, then try: https://stackoverflow.com/a/60002595
# DEFER? This is me attempting to defer `SDKPATH` until after the first load of `~/.zshrc`. ¯\_(ツ)_/¯
# I feel like I’ve done this accidentally before (was it Python) and it worked, but I can’t remember
if command -v -- xcrun >/dev/null 2>&1; then
  SDKPATH="$(xcrun --show-sdk-path)" &&
    export SDKPATH &&
    test -d "${SDKPATH%/}"'/usr/share/man' &&
    MANPATH="${MANPATH:+${MANPATH-}:}${SDKPATH%/}"'/usr/share/man'
fi

sed_help() {
  test "${#}" -gt 0 ||
    # EX_USAGE
    return 64
  # @mislav and @arp242
  # https://github.com/arp242/dotfiles/blob/9ade674954/local/script/tz
  sed \
    -e '1,2 d' \
    -e '/^[^#]/ q' \
    -e 's/^# //' \
    -e 's/^#//' \
    "${@}"
}

sed_pretty() {
  command -v -- gsed >/dev/null 2>&1 ||
    # EX_UNAVAILABLE
    return 69
  printf -- '\n' |
    gsed \
      --debug \
      --posix \
      --sandbox "$(
        printf -- '%s\n' "${@}" |
          sed \
            -e '# duplicate incoming backslashes for specially escaped characters' \
            -e '# https://web.archive.org/web/0id_/gnu.org/s/bash/manual/html_node/ANSI_002dC-Quoting' \
            -e 's/\\\([abfnrtv]\)/\\\\\1/g' 2>&1
      )" |
    sed \
      -e '# replace double backslashes with singles' \
      -e 's/\\\\/\\/g' \
      -e '# replace single quotes with escaped single quotes' \
      -e "$(printf -- 's/\047/\047\\\\\047\047/g')" \
      -e '# remove INPUT: and everything after it' \
      -e "$(printf -- '/INPUT:/,\044 {\nd\n}\n')" \
      -e '# surround each line with single quotes and prepend -e' \
      -e 's/\([^[:space:]].*\)$/-e '\''\1'\'' \\/' \
      -e '# add shebang and call sed' \
      -e '1 s/.*/#!\/usr\/bin\/env sh\nsed \\/' |
    shfmt \
      --indent 2 \
      --language-dialect bash \
      --simplify \
      -- \
      - | {
    bat \
      --decorations=never \
      --language=sh \
      --paging=never \
      -- \
      - 2>/dev/null ||
      cat \
        -- \
        -
  }
  printf -- '%s\n' "${@}" |
    gsed \
      --debug \
      --posix \
      --sandbox \
      -e '# duplicate incoming backslashes for specially escaped characters' \
      -e '# https://web.archive.org/web/0id_/gnu.org/s/bash/manual/html_node/ANSI_002dC-Quoting' \
      -e 's/\\\([abfnrtv]\)/\\\\\1/g' \
      2>&1 |
    sed \
      -e '# replace double backslashes with singles' \
      -e 's/\\\\/\\/g' \
      -e '# replace single quotes with escaped single quotes' \
      -e "$(printf -- 's/\047/\047\\\\\047\047/g')" \
      -e '# remove INPUT: and everything after it' \
      -e "$(printf -- '/INPUT:/,\044 {\nd\n}\n')" \
      -e '# surround each line with single quotes and prepend -e' \
      -e 's/\([^[:space:]].*\)$/-e '\''\1'\'' \\/' \
      -e '# add shebang and call sed' \
      -e '1 s/.*/#!\/usr\/bin\/env sh\nsed \\/' |
    shfmt \
      --indent 2 \
      --language-dialect bash \
      --simplify \
      -- \
      - | {
    bat \
      --decorations=never \
      --language=sh \
      --paging=never \
      -- \
      - 2>/dev/null ||
      cat \
        -- \
        -
  }
}
alias sed_debug='sed_pretty'

seq() {
  case "${#}" in
  1)
    set -- 1 1 "${1-}"
    ;;
  2)
    set -- "${1-}" 1 "${2-}"
    ;;
  3)
    set -- "${1-}" "${2-}" "${3-}"
    ;;
  *)
    return 1
    ;;
  esac
  while test "${1-}" -le "${3-}"; do
    printf -- '%d\n' "${1-}"
    set -- "$((${1-} + ${2-}))" "${2-}" "${3-}"
  done
}

shellcheck_d() {
  set \
    -o noglob \
    -o verbose \
    -o xtrace
  while test "${#}" -gt 0; do
    test -s "${1-}" &&
      test ! -L "${1-}" &&
      rm -f -- "${TMPDIR:-${TEMP:-${TMP:-/tmp}}}"'/'"${1##*/}" &&
      cp -f -p -- "${1-}" "${TMPDIR:-${TEMP:-${TMP:-/tmp}}}"'/'"${1##*/}" &&
      sed \
        -e '/\#[[:blank:]]*shellcheck[[:blank:]][[:blank:]]*disable/ d' \
        -e '# replace shellcheck shell=𝑥sh, if on line 1, with #!/usr/bin/env 𝑥sh' \
        -e '1 s/[[:blank:]]*\#[[:blank:]]*shellcheck[[:blank:]][[:blank:]]*shell=\(.*\)sh/#!\/usr\/bin\/env \1sh/' \
        "${TMPDIR:-${TEMP:-${TMP:-/tmp}}}"'/'"${1##*/}" \
        >"${1-}"
    shift 1
  done
  {
    set \
      +o noglob \
      +o verbose \
      +o xtrace
  } 2>/dev/null
}

shellcheck_markdown() {
  # test shell syntax of Markdown code snippets
  # https://github.com/dylanaraps/pure-sh-bible/commit/9d54e96011

  # Markdown filename extensions
  # https://github.com/github/linguist/blob/7503f7588c/lib/linguist/languages.yml#L3707-L3718

  # run shellcheck on the extracted code blocks
  # SC1071: allow conforming shells besides sh, bash, ksh, dash
  # SC1090: allow linking to a dynamic location
  # SC1091: allow linking to, but not following, linked scripts
  # SC2123: allow `$PATH` modification
  # SC2312: allow masking return values
  command -v -- shellcheck >/dev/null 2>&1 ||
    # EX_UNAVAILABLE
    return 69
  find -- . \
    -path '*/.git' -prune -o \
    -path '*/.well-known' -prune -o \
    -path '*/Library' -prune -o \
    -path '*/node_modules' -prune -o \
    -path '*/t' -prune -o \
    -path '*/Test*' -prune -o \
    -path '*/test*' -prune -o \
    -path '*/tst*' -prune -o \
    -path '*copilot*' -prune -o \
    -path '*dummy*' -prune -o \
    -path '*vscode*' -prune -o \
    '(' \
    -name '*.md' -o \
    -name '*.livemd' -o \
    -name '*.markdn' -o \
    -name '*.markdown' -o \
    -name '*.mdown' -o \
    -name '*.mdwn' -o \
    -name '*.mdx' -o \
    -name '*.mkd' -o \
    -name '*.mkdn' -o \
    -name '*.mkdown' -o \
    -name '*.ronn' -o \
    -name '*.scd' -o \
    -name '*.workbook' -o \
    -name 'contents.lr' \
    ')' \
    -type f \
    -exec sh -c -- 'git ls-files --error-unmatch -- "${1-}" >/dev/null 2>&1 || ! git rev-parse --is-inside-work-tree >/dev/null 2>&1 && while IFS='\'''\'' read -r -- line; do test "${code-}" = '\''1'\'' && test "${line-}" != '\''```'\'' && printf -- '\''%s\n'\'' "${line-}"; case "${line-}" in '\''```sh'\'' | '\''```bash'\'' | '\''```shell'\'' | '\''```zsh'\'' ) code=1 ;; '\''```'\'') code='\'''\'' ;; *) ;; esac; done <"${1-}"' _ {} ';' |
    shellcheck \
      --check-sourced \
      --enable=all \
      --exclude='SC1071,SC1090,SC1091,SC2123,SC2312' \
      --norc \
      --severity=style \
      --shell=sh \
      --source-path=/dev/null \
      -- \
      - ||
    return "${?:-1}"
}

shellharden_r() {
  command -v -- shellharden >/dev/null 2>&1 ||
    # EX_UNAVAILABLE
    return 69
  test "${#}" -gt 0 ||
    # EX_USAGE
    return 64
  set \
    -o noglob \
    -o verbose \
    -o xtrace
  for file in "${@}"; do
    test -s "${file-}" &&
      test ! -L "${file-}" &&
      git ls-files --error-unmatch -- "${file-}" >/dev/null 2>&1 &&
      shellharden --transform -- "${file-}" >"${TMPDIR:-/tmp}"'/'"${file##*/}" &&
      sed \
        -e 's/\([[:space:]]*\)\((*\)"\(\\\)"/\1\2'\''\3'\''/g' \
        -e '# replace two double quotes with two single quotes' \
        -e "$(printf -- 's/ \042\042/ \047\047/g')" \
        "${TMPDIR:-/tmp}"'/'"${file##*/}" >"${file-}"
  done
  {
    set \
      +o noglob \
      +o verbose \
      +o xtrace
  } 2>/dev/null
}

# create the function that will restore options
restore_shell_options() {

  # save options
  {
    set_o="$(set +o)" &&
      export set_o &&
      export set_options_long="${set_o-}" &&
      set_hyphen="${--}" &&
      export set_hyphen &&
      export set_options_short="${set_hyphen-}"
  } ||
    return "${?:-1}"

  # restore options
  test "${set_o-}" != '' &&
    printf -- '%s\n' "${set_o-}" | "${SHELL-}" -C -e -n -u -x -o noglob - 2>/dev/null &&
    { eval " ${set_o-}" >/dev/null 2>&1 || true; }
  unset set_o >/dev/null 2>&1 || set_o=''

  test "${set_hyphen-}" != '' &&
    printf -- '%s\n' "${set_hyphen-}" |
    sed -e 's/\(.\)/\1\n/g' | while IFS='' read -r -- option; do
      { eval " set -${option-}" >/dev/null 2>&1 || true; }
    done

  unset set_hyphen >/dev/null 2>&1 || set_hyphen=''
  unset option >/dev/null 2>&1 || option=''
}
alias shell_options_restore='restore_shell_options'

shf() {
  command -v -- shfmt >/dev/null 2>&1 ||
    # EX_UNAVAILABLE
    return 69
  test "${#}" -gt 0 ||
    # EX_USAGE
    return 64
  set \
    -o noclobber \
    -o noglob \
    -o verbose \
    -o xtrace
  for file in "${@}"; do
    test -s "${file-}" &&
      test ! -L "${file-}" &&
      shfmt --indent 2 --language-dialect bash --simplify --write -- "${file-}"
  done
  {
    set \
      +o noclobber \
      +o noglob \
      +o verbose \
      +o xtrace
  } 2>/dev/null
}

shfmt_r() {
  command -v -- find_shell_scripts >/dev/null 2>&1 &&
    command -v -- shfmt >/dev/null 2>&1 ||
    # EX_UNAVAILABLE
    return 69
  set -o xtrace
  find_shell_scripts |
    while IFS='' read -r -- file; do
      git ls-files --error-unmatch -- "${file-}" >/dev/null 2>&1 &&
        shfmt --indent 2 --language-dialect bash --simplify --write -- "${file-}" &&
        test -s "${file-}" &&
        test ! -L "${file-}" &&
        mkdir -p -- "${TMPDIR:-${TEMP:-${TMP:-/tmp}}}"'/tmp' &&
        cp -f -p -- "${file-}" "${TMPDIR:-${TEMP:-${TMP:-/tmp}}}"'/tmp/'"${file##*/}" &&
        # prevent `shfmt` from breaking Zsh (($+foo)) constructions
        sed \
          -e '# undo shfmt damage to Zshism' \
          -e '# TO DELETE superseded by next line s/(([[:space:]]*\$[[:space:]]*+[[:space:]]*\([^)]*\)))/(($+\1))/g' \
          -e 's/((\$ + \([^)]*\)/(( $+\1 /g' \
          -e '# replace uncommented eval "foo with eval " foo' \
          -e 's/\(^[^#]*eval "\)\([^[:space:]]\)/\1 \2/g' \
          -e '# replace uncommented, non-awk "printf foo" with "printf -- foo"' \
          -e '# TODO: skip fucking with gfind -printf' \
          -e '/awk/! s/\(^[^#]*printf \)\('\''\)/\1-- \2/g' \
          -e '# replace uncommented [ foo ] and [[ foo ]] with test foo' \
          -e 's/^\([^#\[]*\)\[\{1,2\}\( [^]]*\) \]\{1,2\}/\1test\2/g' \
          -e '# silence ksh family ((math+1)) warnings, but hide dollar-sign-then-open-parenthesis from shellcheck' \
          -e 's/^\([^#]*=\)\($[(](.*))\)$/\1"\2"/g' \
          -e '# replace 1>＆2 with >＆2' \
          -e 's/ 1\(>&2\)/ \1/g' \
          -e '# replace uncommented test -n "" with test != ""; \3 is null to hide the ＄{ from shellcheck' \
          -e 's/^\([^#]*\)\(test \)-n \("\$\(\){[^}]*-*}"\)/\1\2\3 != '\''\4'\''/g' \
          -e '# replace uncommented test -z "" with test = ""; \3 is null but hides the ＄{ from shellcheck' \
          -e 's/^\([^#]*\)\(test \)-z \("\$\(\){[^}]*-*}"\)/\1\2\3 = '\''\4'\''/g' \
          -e '# replace all strings like ＄＄ with "＄{＄:--1}"' \
          -e 's/ "\{0,1\}\(\$\){\{0,1\}\(\$\):\{0,1\}-\{0,2\}[[:digit:]]*}\{0,1\}"\{0,1\}/ "\1{\2:--1}"/g' \
          -e '# replace all strings like ＄? with "＄{＄:-1}" ' \
          -e 's/ "\{0,1\}\(\$\){\{0,1\}\(?\):\{0,1\}-\{0,1\}[[:digit:]]\{0,3\}}\{0,1\}"\{0,1\}/ "\1{\2:-1}"/g' \
          -e '# add two single quotes to uncommented trailing equals signs at EOL' \
          -e 's/^\([^#]*=\)$/\1'\'''\''/' \
          -e '# add two single quotes to uncommented variable-assigning equals signs followed by non-EOL' \
          -e 's/^\([^#]* \{0,1\}\)\([[:alpha:]_]\{1,\}[[:alnum:]_]*=\) /\1\2'\'''\'' /g' \
          -e '# replace non-awk, uncommented, double equals signs for test or for [[ or for [, with singles' \
          -e '# DELETE ME /awk/! s/^\([^#]* =\)=/\1/' \
          -e '/awk/! s/^\([^#] *\)\{0,1\}\(test [^=[:space:]]* =\)\{0,1\}\(\[\[ [^=[:space:]]* =\)\{0,1\}\(\[ [^=[:space:]]* =\)\{0,1\}= /\1\2\3\4 /g' \
          -e '# add end-of-options parameter to read' \
          -e 's/\(read -r\)\([[:space:]]\{1,\}[^-][^-][^[:space:]].*\)/\1 --\2/g' \
          -e '#' \
          -e '##' \
          -e '# TODO consider allowing for Zsh "＄{＄{..."' \
          -e '##' \
          -e '# TODO consider basename and dirname replacements using parameter expansion' \
          -e '##' \
          "${TMPDIR:-${TEMP:-${TMP:-/tmp}}}"'/tmp/'"${file##*/}" >"${file-}"
    done
  {
    set +o xtrace
  } 2>/dev/null
}
shfmt_r_() {
  command -v -- shfmt >/dev/null 2>&1 ||
    # EX_UNAVAILABLE
    return 69
  test "${#}" -gt 0 ||
    # EX_USAGE
    return 64
  set -o xtrace
  for file in "${@}"; do
    shfmt --indent 2 --language-dialect bash --simplify --write -- "${file-}" &&
      test -s "${file-}" &&
      # prevent overwriting symlinks and turning them into regular files
      test ! -L "${file-}" &&
      mkdir -p -- "${TMPDIR:-${TEMP:-${TMP:-/tmp}}}"'/tmp' &&
      cp -f -p -- "${file-}" "${TMPDIR:-${TEMP:-${TMP:-/tmp}}}"'/tmp/'"${file##*/}" &&
      awk -- 'match($0,/((\$ \+ .*]))/) { tgt=substr($0,RSTART,RLENGTH); gsub(/ /,"",tgt); $0=substr($0,1,RSTART-1) tgt substr($0,RSTART+RLENGTH) } 1; {gsub(/\(\($\+commands\[(.+)\]\)\)/, "\\1")}' "${file-}" >"${TMPDIR:-${TEMP:-${TMP:-/tmp}}}"'/tmp/'"${file##*/}" &&
      sed \
        -e 's/\$\([a-zA-Z1-9_][a-zA-Z0-9_]*\(\[[^]]\{1,\}\]\)\{0,1\}\)/\${\1}/g' \
        -e 's/(([[:space:]]*\$[[:space:]]*+[[:space:]]*\([^)]*\)))/(($+\1))/g' \
        -e 's/\[\([^[:space:]]*\)[[:space:]]*\([^[:space:]]*\)[[:space:]]*\([^[:space:]]*\)\]/\[\1\2\3\]/g' \
        "${TMPDIR:-${TEMP:-${TMP:-/tmp}}}"'/tmp/'"${file##*/}" >"${file-}"
  done
  {
    set +o xtrace
  } 2>/dev/null
}
shfmt_r_r_() {
  command -v -- shfmt >/dev/null 2>&1 ||
    # EX_UNAVAILABLE
    return 69
  test "${#}" -gt 0 ||
    # EX_USAGE
    return 64
  set -o xtrace
  for file in "${@}"; do
    shfmt --indent 2 --language-dialect bash --simplify --write -- "${file-}" &&
      test -s "${file-}" &&
      # prevent overwriting symlinks and turning them into regular files
      test ! -L "${file-}" &&
      mkdir -p -- "${TMPDIR:-${TEMP:-${TMP:-/tmp}}}"'/tmp' &&
      cp -f -p -- "${file-}" "${TMPDIR:-${TEMP:-${TMP:-/tmp}}}"'/tmp/'"${file##*/}" &&
      sed \
        -e 's/^\([^#]*\)\$\([a-zA-Z1-9_][a-zA-Z0-9_]*\(\[[^]]\{1,\}\]\)\{0,1\}\)/\1\${\2}/g' \
        -e 's/^\([^#]*\)\(([[:space:]]*\$[[:space:]]*+[[:space:]]*\([^)]*\))\)/\1(($+\3))/g' \
        -e 's/^\([^#]*\)\[\([^[:space:]]*\)[[:space:]]*\([^[:space:]]*\)[[:space:]]*\([^[:space:]]*\)\]/\1\[\2\3\4\]/g' \
        "${TMPDIR:-${TEMP:-${TMP:-/tmp}}}"'/tmp/'"${file##*/}" >"${file-}"
  done
  {
    set +o xtrace
  } 2>/dev/null
}
shfmt_r_r_r() {
  command -v -- shfmt >/dev/null 2>&1 ||
    # EX_UNAVAILABLE
    return 69
  test "${#}" -gt 0 ||
    # EX_USAGE
    return 64
  set -o xtrace
  for file in "${@}"; do
    shfmt --indent 2 --language-dialect bash --simplify --write -- "${file-}" &&
      test -s "${file-}" &&
      # prevent overwriting symlinks and turning them into regular files
      test ! -L "${file-}" &&
      mkdir -p -- "${TMPDIR:-${TEMP:-${TMP:-/tmp}}}"'/tmp' &&
      cp -f -p -- "${file-}" "${TMPDIR:-${TEMP:-${TMP:-/tmp}}}"'/tmp/'"${file##*/}" &&
      sed \
        -e 's/^\([^#]*\)\$\([a-zA-Z1-9_][a-zA-Z0-9_]*\(\[[^]]\{1,\}\]\)\{0,1\}\)/\1\${\2}/g' \
        -e 's/^\([^#]*\)\(([[:space:]]*\$[[:space:]]*+[[:space:]]*\([^)]*\))\)/\1(($+\3))/g' \
        -e 's/^\([^#]*\)\[\([^[:space:]]*\)[[:space:]]*\([^[:space:]]*\)[[:space:]]*\([^[:space:]]*\)\]/\1\[\2\3\4\]/g' \
        "${TMPDIR:-${TEMP:-${TMP:-/tmp}}}"'/tmp/'"${file##*/}" >"${file-}"
  done
  {
    set +o xtrace
  } 2>/dev/null
}

shlvl() {
  # shellcheck disable=SC3028
  printf -- '%d\n' "${SHLVL?}"
}

# shred
shred_r() {
  command -v -- shred >/dev/null 2>&1 ||
    # EX_UNAVAILABLE
    return 69
  test "${#}" -gt 0 || {
    # let `shred` provide the error message
    shred >&2
    # EX_USAGE
    return 64
  }
  for file in "${@}"; do
    test -s "${file-}" &&
      test ! -L "${file-}" &&
      shred \
        --force \
        --iterations="$(getconf -- CHAR_MAX)" \
        --remove='wipesync' \
        --size="$(LANG='C' LC_ALL='C' find -- "${file-}" -exec ls -d -l -- {} + | awk -- '$5 >= 0 {printf "%d\n", $5}')" \
        --verbose \
        --zero \
        -- \
        "${file-}"
  done
}

signals() {
  # https://docs.google.com/spreadsheets/d/1Pr6IiXP3vv71SMx-PD_DQf6eucwlfJq3WDPnXRwmBgc
  # https://web.archive.org/web/20240704012105id_/dsa.cs.tsinghua.edu.cn/oj/static/unix_signal.html
  # https://web.archive.org/web/20240725101237id_/man7.org/linux/man-pages/man7/signal.7.html
  printf -- ' signal    | portable name | value\n'
  printf -- ' ----------+---------------+------\n'
  printf -- ' 0         | 0             |     0\n'
  printf -- ' SIGHUP    | HUP           |     1\n'
  printf -- ' SIGINT    | INT           |     2\n'
  printf -- ' SIGQUIT   | QUIT          |     3\n'
  printf -- ' SIGILL    | ILL           |     4\n'
  printf -- ' SIGTRAP   | TRAP          |     5\n'
  printf -- ' SIGABRT   | ABRT          |     6\n'
  printf -- ' SIGIOT    | IOT           |     6\n'
  printf -- ' SIGBUS    | BUS           |     7\n'
  printf -- ' SIGEMT    | EMT           |     7\n'
  printf -- ' SIGSTKFLT | STKFLT        |     7\n'
  printf -- ' SIGFPE    | FPE           |     8\n'
  printf -- ' SIGKILL   | KILL          |     9\n'
  printf -- ' SIGBUS    | BUS           |    10\n'
  printf -- ' SIGUSR1   | USR1          |    10\n'
  printf -- ' SIGSEGV   | SEGV          |    11\n'
  printf -- ' SIGSYS    | SYS           |    12\n'
  printf -- ' SIGUSR2   | USR2          |    12\n'
  printf -- ' SIGXCPU   | XCPU          |    12\n'
  printf -- ' SIG       | SIG           |    13\n'
  printf -- ' SIGPIPE   | PIPE          |    13\n'
  printf -- ' SIGALRM   | ALRM          |    14\n'
  printf -- ' SIGTERM   | TERM          |    15\n'
  printf -- ' SIGSTKFLT | STKFLT        |    16\n'
  printf -- ' SIGURG    | URG           |    16\n'
  printf -- ' SIGUSR1   | USR1          |    16\n'
  printf -- ' SIGCHLD   | CHLD          |    17\n'
  printf -- ' SIGSTOP   | STOP          |    17\n'
  printf -- ' SIGUSR2   | USR2          |    17\n'
  printf -- ' SIGCHLD   | CHLD          |    18\n'
  printf -- ' SIGCLD    | CLD           |    18\n'
  printf -- ' SIGCONT   | CONT          |    18\n'
  printf -- ' SIGTSTP   | TSTP          |    18\n'
  printf -- ' SIGCONT   | CONT          |    19\n'
  printf -- ' SIGPWR    | PWR           |    19\n'
  printf -- ' SIGSTOP   | STOP          |    19\n'
  printf -- ' SIGCHLD   | CHLD          |    20\n'
  printf -- ' SIGTSTP   | TSTP          |    20\n'
  printf -- ' SIGVTALRM | VTALRM        |    20\n'
  printf -- ' SIGWINCH  | WINCH         |    20\n'
  printf -- ' SIGPROF   | PROF          |    21\n'
  printf -- ' SIGTTIN   | TTIN          |    21\n'
  printf -- ' SIGURG    | URG           |    21\n'
  printf -- ' SIGIO     | IO            |    22\n'
  printf -- ' SIGPOLL   | POLL          |    22\n'
  printf -- ' SIGTTOU   | TTOU          |    22\n'
  printf -- ' SIGIO     | IO            |    23\n'
  printf -- ' SIGPOLL   | POLL          |    23\n'
  printf -- ' SIGSTOP   | STOP          |    23\n'
  printf -- ' SIGURG    | URG           |    23\n'
  printf -- ' SIGWINCH  | WINCH         |    23\n'
  printf -- ' SIGSTOP   | STOP          |    24\n'
  printf -- ' SIGTSTP   | TSTP          |    24\n'
  printf -- ' SIGXCPU   | XCPU          |    24\n'
  printf -- ' SIGCONT   | CONT          |    25\n'
  printf -- ' SIGTSTP   | TSTP          |    25\n'
  printf -- ' SIGXFSZ   | XFSZ          |    25\n'
  printf -- ' SIGCONT   | CONT          |    26\n'
  printf -- ' SIGTTIN   | TTIN          |    26\n'
  printf -- ' SIGVTALRM | VTALRM        |    26\n'
  printf -- ' SIGPROF   | PROF          |    27\n'
  printf -- ' SIGTTIN   | TTIN          |    27\n'
  printf -- ' SIGTTOU   | TTOU          |    27\n'
  printf -- ' SIGTTOU   | TTOU          |    28\n'
  printf -- ' SIGVTALRM | VTALRM        |    28\n'
  printf -- ' SIGWINCH  | WINCH         |    28\n'
  printf -- ' SIGINFO   | INFO          |    29\n'
  printf -- ' SIGIO     | IO            |    29\n'
  printf -- ' SIGLOST   | LOST          |    29\n'
  printf -- ' SIGPOLL   | POLL          |    29\n'
  printf -- ' SIGPROF   | PROF          |    29\n'
  printf -- ' SIGPWR    | PWR           |    29\n'
  printf -- ' SIGURG    | URG           |    29\n'
  printf -- ' SIGPWR    | PWR           |    30\n'
  printf -- ' SIGUSR1   | USR1          |    30\n'
  printf -- ' SIGXCPU   | XCPU          |    30\n'
  printf -- ' SIGXFSZ   | XFSZ          |    30\n'
  printf -- ' SIGSYS    | SYS           |    31\n'
  printf -- ' SIGUNUSED | UNUSED        |    31\n'
  printf -- ' SIGUSR2   | USR2          |    31\n'
  printf -- ' SIGXFSZ   | XFSZ          |    31\n'
}

sk() {
  set \
    -o noclobber \
    -o noglob \
    -o verbose \
    -o xtrace
  sudo \
    -- \
    killall -z \
    -- \
    'bird' \
    'corespotlightd' \
    'DropboxFileProvider' \
    'DropboxFileProviderCH' \
    'fileproviderd' \
    'Finder' \
    'Google Drive' \
    'Google Drive Helper' \
    'Maestral' \
    'Spotlight'
  {
    set \
      +o noclobber \
      +o noglob \
      +o verbose \
      +o xtrace
  } 2>/dev/null
}

subdomains() {
  command -v -- curl >/dev/null 2>&1 ||
    # EX_UNAVAILABLE
    return 69
  test "${#}" -eq 1 ||
    # EX_USAGE
    return 64
  curl \
    --fail \
    --location \
    --show-error \
    --silent \
    --url 'https://api.subdomain.center/?domain='"${1-}" |
    sed \
      -e '# replace capital letters' \
      -e 'y/ABCDEFGHIJKLMNOPQRSTUVWXYZ/abcdefghijklmnopqrstuvwxyz/' \
      -e '# remove all string values that begin with "www."' \
      -e 's/"www\.[^"]*"//g' \
      -e '# remove all double quotation marks' \
      -e 's/"//g' \
      -e '# remove all opening square brackets' \
      -e 's/\[//g' \
      -e '# replace all strings of commas with a single newline' \
      -e 's/,\{1,\}/\n/g' \
      -e '# replace all closing square brackets with a newline' \
      -e 's/\]/\n/g' |
    LANG='C' LC_ALL='C' sort -u |
    LANG='C' LC_ALL='C' sort -f
}

substring_contains() {
  # does string/$1 contain substring/$2?
  test "${#}" -eq 2 &&
    # https://stackoverflow.com/a/8811800
    test "${1-}" != "${1#"${2-}"}"
}
alias \
  string_contains='substring_contains' \
  string_contains_alternative='substring_contains'

alias sudo='sudo '

string_length() {
  # https://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_06_02
  test "${#}" -gt 0 ||
    # EX_USAGE
    return 64
  for string in "${@}"; do
    printf -- '%d\n' "${#string}"
  done
}

string_starts_with() {
  test "${#}" -eq 2 ||
    return 1
  # https://stackoverflow.com/a/48913862
  case "${1-}" in
  "${2-}"*)
    return 0
    ;;
  *)
    return 1
    ;;
  esac
}

string_ends_with() {
  # string=$1
  # ends_with=$2
  case "${1-}" in
  *"${2-}")
    return 0
    ;;
  *)
    return 1
    ;;
  esac
}
alias substring_ends_with='string_ends_with'

stylelint_r() {
  command -v -- stylelint >/dev/null 2>&1 &&
    command -v -- npm >/dev/null 2>&1 &&
    npm config --location=global -- get prefix >/dev/null 2>&1 &&
    test -d "$(npm config --location=global -- get prefix)" &&
    test -d "$(npm config --location=global -- get prefix)"'/lib/node_modules/stylelint-config-standard' &&
    test -d "$(npm config --location=global -- get prefix)"'/lib/node_modules/stylelint-config-recommended' ||
    # EX_UNAVAILABLE
    return 69
  set -- "$(
    find -L -- \
      './stylelint.config.mjs' \
      "${XDG_CONFIG_HOME:-${HOME%/}/.config}"'/stylelint/.stylelintrc' \
      "${XDG_CONFIG_HOME:-${HOME%/}/.config}"'/stylelint/.stylelintrc.cjs' \
      "${XDG_CONFIG_HOME:-${HOME%/}/.config}"'/stylelint/.stylelintrc.js' \
      "${XDG_CONFIG_HOME:-${HOME%/}/.config}"'/stylelint/.stylelintrc.json' \
      "${XDG_CONFIG_HOME:-${HOME%/}/.config}"'/stylelint/.stylelintrc.yaml' \
      "${XDG_CONFIG_HOME:-${HOME%/}/.config}"'/stylelint/.stylelintrc.yml' \
      -type f \
      -exec ls -1 -S -- {} + 2>/dev/null |
      sed -e '1 q'
  )" &&
    test -s "${1-}" ||
    # EX_CONFIG
    return 78
  set \
    -o verbose \
    -o xtrace
  configuration="${1-}" find -- . \
    -path '*/.git' -prune -o \
    -path '*/.well-known' -prune -o \
    -path '*/Empty' -prune -o \
    -path '*/Library' -prune -o \
    -path '*/node_modules' -prune -o \
    -path '*/t' -prune -o \
    -path '*/Test*' -prune -o \
    -path '*/test*' -prune -o \
    -path '*/tst*' -prune -o \
    -path '*copilot*' -prune -o \
    -path '*dummy*' -prune -o \
    -path '*vscode*' -prune -o \
    '(' \
    -name '*.css' -o \
    -name '*.[Cc][Ss][Ss]' \
    ')' \
    -type f \
    -exec sh -x -c -- 'for file in "${@}"; do
  git ls-files --error-unmatch -- "${file-}" >/dev/null 2>&1 ||
    ! git rev-parse --is-inside-work-tree >/dev/null 2>&1 &&
    npm exec -- stylelint --allow-empty-input --color --config="${configuration-}" --fix --formatter=verbose --ignore-disables --report-descriptionless-disables --report-invalid-scope-disables --report-needless-disables -- "${file-}"
done' _ {} +
  {
    set \
      +o verbose \
      +o xtrace
  } 2>/dev/null
}

swiftlint_r() {
  command -v -- swiftlint >/dev/null 2>&1 ||
    # EX_UNAVAILABLE
    return 69
  find -- . \
    -path '*/.git' -prune -o \
    -path '*/node_modules' -prune -o \
    '(' \
    -name '*.swift' -o \
    -name '*.[Ss][Ww][Ii][Ff][Tt]' \
    ')' \
    -type f \
    -exec sh -x -c -- 'for file in "${@}"; do
  git ls-files --error-unmatch -- "${file-}" >/dev/null 2>&1 ||
    ! git rev-parse --is-inside-work-tree >/dev/null 2>&1 &&
    swiftlint lint --enable-all-rules --fix --format --progress -- "${file-}"
done' _ {} +
}

tabs_to_spaces() {
  test "${#}" -gt 0 ||
    # EX_USAGE
    return 64
  for file in "${@}"; do
    # apply to any file, except for
    # - zero-length files
    test -s "${file-}" &&
      # - symlinks
      test ! -L "${file-}" &&
      # - binary property lists using `grep` without `-q` support
      grep -v -e 'bplist' -- "${file-}" >/dev/null 2>&1 &&
      file -- "${file-}" |
      grep -v -e 'binary' >/dev/null 2>&1 &&
      mkdir -p -- "${TMPDIR:-${TEMP:-${TMP:-/tmp}}}"'/tmp' &&
      cp -f -p -- "${file-}" "${TMPDIR:-${TEMP:-${TMP:-/tmp}}}"'/tmp/'"${file##*/}" &&
      sed -e 's/\t/  /g' "${TMPDIR:-${TEMP:-${TMP:-/tmp}}}"'/tmp/'"${file##*/}" >"${file-}"
  done
}

tabs_to_spaces_ed() {
  command -v -- ed >/dev/null 2>&1 ||
    # EX_UNAVAILABLE
    return 69
  test "${#}" -gt 0 ||
    # EX_USAGE
    return 64
  set \
    -o noclobber \
    -o noglob \
    -o verbose \
    -o xtrace
  for file in "${@}"; do
    test -s "${file-}" &&
      test ! -L "${file-}" &&
      grep -v -e 'bplist' -- "${file-}" >/dev/null 2>&1 &&
      LC_ALL='C' file -- "${file-}" |
      grep -v -e 'binary' >/dev/null 2>&1 &&
      ed -s -- "${file-}" <<EOF
1,\$ s/	/  /g
w
q
EOF
  done |
    sed \
      -e '# suppress ed question mark-only lines' \
      -e '/^?$/ d'
  {
    set \
      +o noclobber \
      +o noglob \
      +o verbose \
      +o xtrace
  } 2>/dev/null
}

tail() {
  case "${1-}" in
  -*)
    command -p -- tail "${@}"
    ;;
  *)
    command -p -- tail -n "$((${LINES:-"$(
      tput -- lines 2>/dev/null ||
        printf -- '10 + 2'
    )"} - 3))" "${@}"
    ;;
  esac
}

# take: mkdir && cd
take() {
  while test "${#}" -gt 0; do
    if test -d "${1-}"; then
      printf -- 'directory \342\200\230%s\342\200\231 exists...\n' "${1-}" >&2
    elif printf -- 'creating directory \342\200\230%s\342\200\231... ' "${1##*"${PWD}"/}" >&2 &&
      mkdir -p -- "${1-}"; then
      printf -- 'done\n' >&2
    fi
    # POSIX-compliant `${@:$#}`-style string indexing (SC3057)
    # https://stackoverflow.com/q/1853946
    test "${#}" -eq 1 &&
      printf -- 'entering directory \342\200\230%s\342\200\231\n' "${1##*"${PWD}"/}" >&2 &&
      CDPATH='.' cd "${1-}" >/dev/null 2>&1 ||
      return "${?:-1}"
    shift 1
  done
}
alias md >/dev/null 2>&1 &&
  unalias -- md
alias md='mkdir -p'

tdt() {
  case "${1-}" in
  --evil)
    {
      target="${TMPDIR:-${TEMP:-${TMP:-/tmp}}}"'/tmp.trash/evil-'"$(LANG='C' LC_ALL='C' date -- '+%Y%m%d%H%M%S')"
      mkdir -p -- "${target-}" &&
        CDPATH='.' cd "${target-}" >/dev/null 2>&1
    } ||
      return 1
    ;;
  *)
    {
      mkdir -p -- "${TMPDIR:-${TEMP:-${TMP:-/tmp}}}"'/tmp.trash' &&
        CDPATH='.' cd "${TMPDIR:-${TEMP:-${TMP:-/tmp}}}"'/tmp.trash' >/dev/null 2>&1
    } ||
      return 1
    ;;
  esac
  git status 2>/dev/null ||
    true
  unset target >/dev/null 2>&1 || target=''
}
alias tet='tdt --evil'

# temperature: return the CPU temperature in degrees Fahrenheit
temperature() {
  command -v -- powermetrics >/dev/null 2>&1 ||
    # EX_UNAVAILABLE
    return 69
  {
    sudo -- powermetrics --samplers smc &
  } |
    # 𝑛 + narrow non-breaking space + degree sign + F
    awk -- '/CPU die temperature/ {printf "%.3f\342\200\257\302\260F\n", $4 * 9 / 5 + 32; exit}'
}

textlint_r() {
  {
    command -v -- npm >/dev/null 2>&1 &&
      npm config --location=global -- get prefix >/dev/null 2>&1 &&
      test -d "$(npm config --location=global -- get prefix)" &&
      test -d "$(npm config --location=global -- get prefix)"'/lib/node_modules/textlint-rule-terminology'
  } ||
    # EX_UNAVAILABLE
    return 69
  set -o xtrace
  # find all Markdown text files, then run `textlint` on them
  find -- . \
    -path '*/.git' -prune -o \
    -path '*/.well-known' -prune -o \
    -path '*/Empty' -prune -o \
    -path '*/Library' -prune -o \
    -path '*/node_modules' -prune -o \
    -path '*/t' -prune -o \
    -path '*/Test*' -prune -o \
    -path '*/test*' -prune -o \
    -path '*/tst*' -prune -o \
    -path '*copilot*' -prune -o \
    -path '*dummy*' -prune -o \
    -path '*vscode*' -prune -o \
    '(' \
    -name '*.md' -o \
    -name '*.livemd' -o \
    -name '*.markdn' -o \
    -name '*.markdown' -o \
    -name '*.mdown' -o \
    -name '*.mdwn' -o \
    -name '*.mdx' -o \
    -name '*.mkd' -o \
    -name '*.mkdn' -o \
    -name '*.mkdown' -o \
    -name '*.ronn' -o \
    -name '*.scd' -o \
    -name '*.workbook' -o \
    -name 'contents.lr' -o \
    -name '*.txt' -o \
    -name '*.fr' -o \
    -name '*.nb' -o \
    -name '*.ncl' -o \
    -name '*.no' -o \
    -name 'CITATION' -o \
    -name 'CITATIONS' -o \
    -name 'click.me' -o \
    -name 'COPYING' -o \
    -name 'COPYING.regex' -o \
    -name 'COPYRIGHT.regex' -o \
    -name 'delete.me' -o \
    -name 'FONTLOG' -o \
    -name 'INSTALL' -o \
    -name 'INSTALL.mysql' -o \
    -name 'keep.me' -o \
    -name 'LICENSE' -o \
    -name 'LICENSE.mysql' -o \
    -name 'NEWS' -o \
    -name 'package.mask' -o \
    -name 'package.use.mask' -o \
    -name 'package.use.stable.mask' -o \
    -name 'read.me' -o \
    -name 'readme.1st' -o \
    -name 'README.me' -o \
    -name 'README.mysql' -o \
    -name 'README.nss' -o \
    -name 'test.me' -o \
    -name 'use.mask' -o \
    -name 'use.stable.mask' \
    ')' \
    ! -name 'changelog*' \
    ! -name '[Cc][Hh][Aa][Nn][Gg][Ee]*[Ll][Oo][Gg]*' \
    ! -name 'LICENSE*' \
    ! -name '[Ll][Ii][Cc][Ee][Nn][CcSs][Ee]*' \
    -type f \
    -exec sh -x -c -- 'for file in "${@}"; do
  git ls-files --error-unmatch -- "${file-}" >/dev/null 2>&1 ||
    ! git rev-parse --is-inside-work-tree >/dev/null 2>&1 &&
    npm exec -- textlint --experimental --fix --rule terminology -- "${file-}"
done' _ {} +
  {
    set +o xtrace
  } 2>/dev/null
}

transfer() {
  test "${#}" -gt 0 ||
    # EX_USAGE
    return 64
  for file in "${@}"; do
    test -s "${file-}" &&
      {
        curl --fail --form 'expires=1' --form 'file=@'"${file-}" --form 'secret='\'''\''' --location --show-error --silent --url https://0x0.st 2>/dev/null ||
          { curl --fail --form 'file=@'"${file-}" --location --show-error --silent --url 'https://temp.sh/upload' && printf -- '\n' >&2; } ||
          wget --hsts-file=/dev/null --post-file="${file-}" --quiet 'https://temp.sh/upload' ||
          { curl --fail --location --silent --show-error --upload-file "${file-}" --url 'https://temp.sh' && printf -- '\n' >&2; } ||
          { curl --fail --location --silent --show-error --upload-file "${file-}" --url 'https://temp.sh/'"${file##*/}" && printf -- '\n' >&2; } ||
          wget --body-file="${file-}" --hsts-file=/dev/null --method=PUT --output-document=- --quiet 'https://temp.sh/'"${file##*/}" ||
          { curl --fail --location --show-error --silent --upload-file "${file-}" --url 'https://transfer.sh/'"${file##*/}" && printf -- '\n' >&2; } ||
          wget --body-file="${file-}" --hsts-file=/dev/null --method=PUT --output-document=- --quiet 'https://transfer.sh/'"${file##*/}"
      }
  done
}

trash_developer() {
  set \
    -o noclobber \
    -o noglob \
    -o verbose \
    -o xtrace
  if test -d "${HOME%/}"'/.Trash'; then
    set -- "${HOME%/}"'/.Trash'
  elif mkdir -p -- "${XDG_DATA_HOME:-${HOME%/}/.local/share}"'/Trash' 2>/dev/null; then
    set -- "${XDG_DATA_HOME:-${HOME%/}/.local/share}"'/Trash'
  elif mkdir -p -- "${TMPDIR:-${TEMP:-${TMP:-/tmp}}}"'/.Trash' 2>/dev/null; then
    set -- "${TMPDIR:-${TEMP:-${TMP:-/tmp}}}"'/.Trash'
  else
    # EX_CANTCREAT
    return 73
  fi
  set -- "${1-}" "$(LANG='C' LC_ALL='C' date -- '+%Y%m%d%H%M%S')"
  test -d "${HOME%/}"'/Library/Developer/Xcode/DerivedData' &&
    mv -f -- "${HOME%/}"'/Library/Developer/Xcode/DerivedData' "${1-}"'/Xcode-'"${2-}"
  test -d "${HOME%/}"'/Library/Developer/Xcode/UserData/IB Support' &&
    mv -f -- "${HOME%/}"'/Library/Developer/Xcode/UserData/IB Support' "${1-}"'/Xcode⁄UserData⁄IB Support-'"${2-}"
  test -d "${HOME%/}"'/Library/Caches/JetBrains' &&
    mv -f -- "${HOME%/}"'/Library/Caches/JetBrains' "${1-}"'/JetBrains-'"${2-}"
  test -d "${HOME%/}"'/Library/Caches/org.carthage.CarthageKit/DerivedData' &&
    mv -f -- "${HOME%/}"'/Library/Caches/org.carthage.CarthageKit/DerivedData' "${1-}"'/Carthage-'"${2-}"
  test -d "${HOME%/}"'/Library/Caches/Homebrew/downloads' &&
    mv -f -- "${HOME%/}"'/Library/Caches/Homebrew/downloads' "${1-}"'/Homebrew-'"${2-}"
  command -v -- brew >/dev/null 2>&1 && {
    brew autoremove --verbose
    brew cleanup --prune=all --verbose
  }
  command -v -- gem >/dev/null 2>&1 &&
    gem cleanup --verbose
  case "$(
    command -v -- xcrun >/dev/null 2>&1 &&
      xcrun --run -- simctl \
        list -j \
        devices unavailable |
      sed \
        -n \
        -e 'H' \
        -e '$ {' \
        -e '  x' \
        -e '  s/[[:space:]]//gp' \
        -e '}'
  )" in
  *{}*) ;;
  *)
    # this may require `sudo` and
    # this may be on a virtual but ejectable disk
    xcrun --run -- simctl delete unavailable
    ;;
  esac &&
    {
      set \
        +o noclobber \
        +o noglob \
        +o verbose \
        +o xtrace
    } 2>/dev/null
  printf -- '\n\360\237\232\256  data successfully trashed\n' >&2
}

update_changelog() {
  command -v -- gem >/dev/null 2>&1 &&
    command -v -- github_changelog_generator >/dev/null 2>&1 &&
    command -v -- markdownlint >/dev/null 2>&1 ||
    # EX_UNAVAILABLE
    return 69
  test "${CHANGELOG_GITHUB_TOKEN-}" != '' ||
    test "${GITHUB_API_TOKEN-}" != '' ||
    test "${GITHUB_OAUTH_TOKEN-}" != '' ||
    test "${GITHUB_TOKEN-}" != '' ||
    # EX_CONFIG
    return 78
  # find one existing changelog once
  file="$(
    CDPATH='.' cd "$(
      # attempt relative-path access
      git rev-parse \
        --path-format=relative \
        --show-toplevel |
        sed -e '1 q'
    )" >/dev/null 2>&1 ||
      CDPATH='.' cd "$(
        git rev-parse \
          --show-toplevel
      )" >/dev/null 2>&1 ||
      return "${?:-1}"
    # find the Markdown changelog with the latest commit
    find -- . \
      -path './[Cc][Hh][Aa][Nn][Gg][Ee]*[Ll][Oo][Gg]*.[Mm]*[Dd]*' \
      -type f \
      -exec sh -c -- 'git log --max-count=1 --format='\''%at '\''"${1-}"' _ {} ';' |
      LANG='C' LC_ALL='C' sort -n -r |
      sed \
        -e '# print only the second field of the first line' \
        -e '1 s/.*\///g' \
        -e '1 q'
  )"
  # define changelog location if none is found
  file="${file:=changelog.md}"
  # ensure the file exists
  touch -- "${file-}"
  # create local changes
  gem exec github_changelog_generator \
    --user "$(
      git ls-remote --get-url |
        sed \
          -e '# replace colons with forward slashes' \
          -e 's/:/\//g' \
          -e '# remove everything except the second-to-last' \
          -e '# forward slash-delimited field' \
          -e 's/.*\/\([^/]*\)\/[^/]*/\1/'
    )" \
    --project "$(
      git ls-remote --get-url |
        sed \
          -e 's/.*\///' \
          -e 's/\.git$//'
    )" \
    --token "${CHANGELOG_GITHUB_TOKEN:-${GITHUB_TOKEN:-${GITHUB_API_TOKEN:-${GITHUB_OAUTH_TOKEN-}}}}" \
    --exclude-labels 'duplicate,question,invalid,wontfix,nodoc' \
    --output "${file-}" ||
    return 1
  # repair changelog credit
  sed \
    -e 's/This Changelog/This changelog/' \
    -e 's/automatically generated/\[automatically generated\]()/' \
    -e 's/\]()/\](.\/.github\/workflows\/changelog.yml)/' \
    -e 's/generator)\*/generator).\*/' \
    ./"${file-}" >./"${file%.*}"_temporary."${file##*.}" &&
    mv -f -- \
      ./"${file%.*}"_temporary."${file##*.}" ./"${file-}"
  # get linting configuration
  {
    test -s "${HOME%/}"'/.markdownlint.json' &&
      configuration='--config='"${HOME%/}"'/.markdownlint.json'
  } || {
    test -s "${HOME%/}"'/.markdownlint.yml' &&
      configuration='--config='"${HOME%/}"'/.markdownlint.yml'
  } ||
    configuration='--disable MD013 MD033'
  export configuration
  # lint changelog
  test ! -e "${HOME%/}"'/.markdownlint.json' ||
    configuration='--config='"${HOME%/}"'/.markdownlint.json' ||
    configuration='--disable MD013'
  markdownlint "${configuration-}" --fix -- "${file-}"
  unset file >/dev/null 2>&1 || file=''
  unset configuration >/dev/null 2>&1 || configuration=''
  # ensure nothing else is staged
  git reset --quiet HEAD -- .
  # stage and commit files
  git add --verbose -- ./"${file-}"
  git commit \
    --author='GitHub <actions@github.com>' \
    --message='update changelog' \
    --verbose ||
    return 0
}

# Unix epoch seconds
alias unixtime='awk -- '\''BEGIN {srand(); print srand()}'\'''
unixtime_set() {
  # force weekday matching when only 1970 to 1999 are available using perpetual calendar
  # UNIX 5.0: `date [ mmddhhmm[yy] ]`
  # fail if called before 2000, after 2066
  # https://web.archive.org/web/0id_/i.pinimg.com/originals/8a/23/99/8a2399cf3774165dddc728641a6b0c06.jpg
  set -- "$(LANG='C' LC_ALL='C' date -- '+%Y')" &&
    test 2000 -le "${1-}" &&
    test "${1-}" -le 2066 &&
    if test "${1-}" -ge 2026; then
      # 2026’s calendar matches 1970's... 2066’s matches 1999’s
      set -- "$((${1-} + 44))" &&
        set -- "$((${1-} - 2000))"
    else
      # 2000’s calendar matches 1972’s... 2025’s matches 1997’s
      set -- "$((${1-} + 72))" &&
        set -- "$((${1-} - 2000))"
    fi &&
    printf -- 'UNIX date to force a matching weekday:\n\n' >&2 &&
    printf -- 'date \047%d%s\047\n' "${1-}" "$(LANG='C' LC_ALL='C' date -- '+%m%d%H%M.%S')" &&
    printf -- '# UNIX 5.0\n' >&2 &&
    printf -- 'date \047%s%d\047\n' "$(LANG='C' LC_ALL='C' date -- '+%m%d%H%M')" "${1-}"
}
alias unixdate_set='unixtime_set'

url_to_filename() {
  test "${#}" -gt 0 ||
    # EX_USAGE
    return 64
  printf -- '%s\n' "${*-}" |
    sed \
      -e '# remove https/http/chrome/brave protocol and www' \
      -e 's|.*://\(w*\.\)*||g' \
      -e '# remove leading github.com/ or gitlab.com/' \
      -e 's|git..b\.com/||g' \
      -e '# remove “/blob”, “/-/blob”, “/tree”, “/-/tree”, “/commit”, “/-/commit”' \
      -e 's|/*-*/blob/|/|' \
      -e 's|/*-*/tree/|/|' \
      -e 's|/*-*/commit/|/|' \
      -e '# replace slash plus up to 40 hexadecimal characters with “@” plus their first 7' \
      -e '# https://chat.com/share/67cdc568-5cec-8007-99a4-57fb960a96e3' \
      -e 's|/\([[:xdigit:]]\)\([[:xdigit:]]\)\([[:xdigit:]]\)\([[:xdigit:]]\)\([[:xdigit:]]\)\([[:xdigit:]]\)\([[:xdigit:]]\)[[:xdigit:]]\{33\}|@\1\2\3\4\5\6\7|g' \
      -e '# replace slashes with “∕”' \
      -e 's|/|'"$(LC_ALL='C' printf -- '\342\210\225')"'|g' \
      -e '# replace question marks with “︖”' \
      -e 's|?|'"$(LC_ALL='C' printf -- '\357\270\226')"'|g' \
      -e '# replace exclamation points with “！”' \
      -e 's|!|'"$(LC_ALL='C' printf -- '\357\274\201')"'|g' \
      -e '# replace ampersands with “＆”' \
      -e 's|&|'"$(LC_ALL='C' printf -- '\357\274\206')"'|g' \
      -e '# replace parentheses with fullwidth punctuation' \
      -e 's|(|'"$(LC_ALL='C' printf -- '\357\274\210')"'|g' \
      -e 's|)|'"$(LC_ALL='C' printf -- '\357\274\211')"'|g' \
      -e '# replace [especially Wikipedia] “File:” with “File：”' \
      -e 's|:|'"$(LC_ALL='C' printf -- '\357\274\232')"'|g' \
      -e '# replace asterisks with asterisk operator (“∗”)' \
      -e 's|*|'"$(LC_ALL='C' printf -- '\342\210\227')"'|g' \
      -e '# replace spaces with underscores' \
      -e 's| |_|g' \
      -e '# remove trailing hashmarks if any' \
      -e 's|#*$||g' \
      -e '# replace non-trailing hashmarks with fullwidth number signs' \
      -e 's|#|'"$(LC_ALL='C' printf -- '\357\274\203')"'|g' \
      -e '# remove trailing slashes if any' \
      -e 's|/*$||g'
}

variable_value() {
  test "${#}" -gt 0 ||
    # EX_USAGE
    return 64
  for possible_variable in "${@}"; do
    eval " test \"\${${possible_variable-}+x}\" != ''" &&
      printf -- '\044%s\t' "${possible_variable-}" >&2 &&
      eval " printf -- '%s\n' \"\${${possible_variable-}-}\""
  done
}
alias value_of_variable='variable_value'

# Visual Studio Code
code() {
  {
    "$(
      command -v -- code-insiders ||
        command -v -- "${HOMEBREW_PREFIX-}"'/bin/code-insiders' ||
        command -v -- '/Applications/Visual Studio Code - Insiders.app/Contents/Resources/app/bin/code' ||
        command -v -- code ||
        command -v -- "${HOMEBREW_PREFIX-}"'/bin/code' ||
        command -v -- '/Applications/Visual Studio Code.app/Contents/Resources/app/bin/code'
    )" "${@:-.}" ||
      open -a 'Visual Studio Code - Insiders' "${@:-.}" ||
      open -n -a 'Visual Studio Code - Insiders' "${@:-.}" ||
      open -a 'Visual Studio Code' "${@:-.}" ||
      open -n -a 'Visual Studio Code' "${@:-.}"
  } 2>/dev/null
}
command -v -- _code >/dev/null 2>&1 &&
  compdef -- code-insiders='code' >/dev/null 2>&1

wayback_r() {
  command -v -- gem >/dev/null 2>&1 ||
    # EX_UNAVAILABLE
    return 69
  command -v -- wayback_machine_downloader >/dev/null 2>&1 ||
    # EX_UNAVAILABLE
    return 69
  test "${#}" -eq 1 ||
    # EX_USAGE
    return 64
  set \
    -o verbose \
    -o xtrace
  wayback_machine_downloader --all-timestamps "${1-}"
  {
    set \
      +o verbose \
      +o xtrace
  } 2>/dev/null
}

webp_r() {
  command -v -- cwebp >/dev/null 2>&1 ||
    # EX_UNAVAILABLE
    return 69
  test "${#}" -gt 0 ||
    # EX_USAGE
    return 64
  set \
    -o noclobber \
    -o noglob \
    -o nounset \
    -o verbose \
    -o xtrace
  for file in "${@}"; do
    test -s "${file-}" &&
      test ! -L "${file-}" &&
      cwebp \
        -alpha_filter best \
        -lossless \
        -m 6 \
        -mt \
        -progress \
        -q 100 \
        -qrange 100 100 \
        -v \
        -z 9 \
        -o "${file%.*}"'.webp' \
        -- \
        "${file-}"
  done
  {
    set \
      +o noclobber \
      +o noglob \
      +o nounset \
      +o verbose \
      +o xtrace
  } 2>/dev/null
}

## website troubleshooting
troubleshoot_website() {
  {
    printf -- '# https://web.archive.org/web/20221203151931/help.dreamhost.com/hc/en-us/articles/215867298-Commands-to-troubleshoot-your-websites\n'
    printf -- 'uptime\n'
    printf -- 'lsof -u "\044{LOGNAME:-\044{USER-}}" | grep -e '\''php'\'' | grep -e '\''/home'\''\n'
    printf -- 'watch "lsof -u \044{LOGNAME:-\044{USER-}} | grep -e '\''php'\'' | grep -e '\''/home'\'' | tee -a -- ./results.txt"\n'
    printf -- 'cat -- ./results.txt\n'
    printf -- '# https://web.archive.org/web/20221005032620/help.dreamhost.com/hc/en-us/articles/115000683852-Using-the-top-command-to-troubleshoot-your-website\n'
    printf -- 'top\n'
    printf -- '# https://web.archive.org/web/20221004111114/help.dreamhost.com/hc/en-us/articles/214880098-Using-the-ps-command-to-troubleshoot-your-website\n'
    printf -- '# cpu\n'
    printf -- 'ps -A -o pcpu,pid,user,args | LANG='\''C'\'' LC_ALL='\''C'\'' sort -k 1 -r | head -n 10\n'
    printf -- '# memory\n'
    printf -- 'ps -A -o pmem,pid,user,args | LANG='\''C'\'' LC_ALL='\''C'\'' sort -k 1 -r | head -n 10\n'
    printf -- '# https://web.archive.org/web/20221203051014/help.dreamhost.com/hc/en-us/articles/216105097-Viewing-and-examining-your-access-log-via-SSH\n'
    printf -- 'CDPATH='\''.'\'' cd "\044{HOME\045/}"'\''/logs/'\''"\044{LOGNAME:-\044{USER-}}"'\''.net'\'' >/dev/null 2>&1 &&\n'
    printf -- '  # list the last 10,000 site hits\n'
    printf -- '  find -L -- . -name '\''access.log'\'' -type f -exec tail -n 10000 -- {} + | awk -- '\''{print \0441}'\'' | LANG='\''C'\'' LC_ALL='\''C'\'' sort | uniq -c | LANG='\''C'\'' LC_ALL='\''C'\'' sort -n\n'
    printf -- '# watch the server log in real time\n'
    printf -- 'tail -f -- ./**/*access.log\n'
    printf -- '# list files being called the most\n'
    printf -- 'awk '\''{print \0447}'\'' ./access.log | cut -d'\''?'\'' -f 1 | LANG='\''C'\'' LC_ALL='\''C'\'' sort | uniq -c | LANG='\''C'\'' LC_ALL='\''C'\'' sort -k -n 1 | tail -n 10\n'
    printf -- '# list traffic for all user domains on server\n'
    printf -- 'CDPATH='\''.'\'' cd "\044{HOME\045/}"'\''/logs'\'' >/dev/null 2>&1 &&\n'
    printf -- '  for k in \044(ls -S -- ./**/*/https/access.log); do wc -l -- "\044{k-}" | LANG='\''C'\'' LC_ALL='\''C'\'' sort -n -r; done\n'
  } | {
    bat \
      --decorations=never \
      --language=sh \
      --paging=never \
      -- \
      - 2>/dev/null ||
      cat \
        -- \
        -
  }
}
alias website_troubleshoot='troubleshoot_website'

# wget
wget_download() {
  command -v -- wget >/dev/null 2>&1 ||
    # EX_UNAVAILABLE
    return 69
  test "${#}" -eq 1 ||
    # EX_USAGE
    return 64
  set -- "$(
    printf -- '%s\n' "${1-}" |
      sed \
        -e 's/.*@//' \
        -e 's/https\{0,1\}:\/\///' \
        -e 's/www\.//' \
        -e 's/[:/].*//'
  )"
  # check both targets exist
  test -d "${HOME%/}"'/Code/'"${1-}"'/.https' &&
    test -d "${HOME%/}"'/Sites/'"${1-}" &&
    # check that there is just
    # 1 unique file serial number amongst the
    # 2 targets
    test "$(
      find -- \
        "${HOME%/}"'/Code/'"${1-}"'/.https' \
        "${HOME%/}"'/Sites/'"${1-}" \
        -prune \
        -exec ls -1 -d -i -L -- {} + |
        awk -- '! seen[$1]++ {print $1}' |
        grep -c -e '.'
    )" -eq 1 ||
    {
      {
        set +o xtrace
      } 2>/dev/null
      # EX_CONFIG
      return 78
    }

  CDPATH='.' cd "${HOME%/}"'/Sites' >/dev/null 2>&1 ||
    return "${?:-1}"

  # user agent
  # https://web.archive.org/web/0id_/developers.google.com/search/blog/2019/10/updating-user-agent-of-googlebot#the-new-evergreen-googlebot-and-its-user-agent
  wget \
    --adjust-extension \
    --append-output="${1-}"'.log' \
    --continue \
    --convert-links \
    --debug \
    --directory-prefix="${HOME%/}"'/Sites/'"${1-}" \
    --domains="${1-}" \
    --execute robots=off \
    --force-directories \
    --hsts-file=/dev/null \
    --keep-session-cookies \
    --level=0 \
    --mirror \
    --no-check-certificate \
    --no-host-directories \
    --no-parent \
    --no-robots \
    --page-requisites \
    --progress=bar \
    --random-wait \
    --recursive \
    --referer='https://www.google.com/search' \
    --restrict-file-names=nocontrol \
    --server-response \
    --timestamping \
    --user-agent='Mozilla/5.0 (compatible; Googlebot/2.1; +https://www.google.com/bot.html)' \
    'https://'"${1-}" ||
    return "${?:-1}"
}

which() {
  if builtin which -a -s -x 2 "${@}" >/dev/null 2>&1; then
    builtin which -a -s -x 2 "${@}"
  elif command "${HOMEBREW_PREFIX-}"'/bin/gwhich' "${@}" >/dev/null 2>&1; then
    command "${HOMEBREW_PREFIX-}"'/bin/gwhich' "${@}"
  elif command "${HOMEBREW_PREFIX-}"'/bin/which' "${@}" >/dev/null 2>&1; then
    command "${HOMEBREW_PREFIX-}"'/bin/which' "${@}"
  elif command '/usr/bin/which' "${@}" >/dev/null 2>&1; then
    command '/usr/bin/which' "${@}"
  elif command '/bin/which' "${@}" >/dev/null 2>&1; then
    command '/bin/which' "${@}"
  else
    return "${??}"
  fi
}
alias all='which -a'

whois() {
  # whois a domain or a URL
  # https://github.com/paulirish/dotfiles/blob/86ab0fa/.functions#L57-L69

  # get domain from URL
  domain="$(
    printf -- '%s\n' "${1-}" |
      sed \
        -e 's/.*@//' \
        -e 's/https\{0,1\}:\/\///' \
        -e 's/www\.//' \
        -e 's/[:/].*//'
  )"

  test "${domain-}" = '' &&
    domain="${1-}"

  # this is the best whois server
  command -p -- whois --host whois.internic.net "${domain-}" |

    # strip boilerplate footer
    grep -e '^   '

  unset domain >/dev/null 2>&1 || domain=''
}

wikipedia() {
  set -- 'https://lucaslarson.net/wiki/'"${*-}"
  xdg-open -- "${1-}" 2>/dev/null ||
    open -- "${1-}"
}

yamllint_r() {
  find -- . \
    -path '*/.git' -prune -o \
    -path '*/.well-known' -prune -o \
    -path '*/Empty' -prune -o \
    -path '*/Library' -prune -o \
    -path '*/node_modules' -prune -o \
    -path '*/t' -prune -o \
    -path '*/Test*' -prune -o \
    -path '*/test*' -prune -o \
    -path '*/tst*' -prune -o \
    -path '*copilot*' -prune -o \
    -path '*dummy*' -prune -o \
    -path '*vscode*' -prune -o \
    '(' \
    -path "${HOME%/}"'/.config/yamllint/config' -o \
    -path "${XDG_CONFIG_HOME-}"'/yamllint/config' -o \
    -name '*.yml' -o \
    -name '*.CFF' -o \
    -name '*.cff' -o \
    -name '*.mir' -o \
    -name '*.reek' -o \
    -name '*.rviz' -o \
    -name '*.sublime-syntax' -o \
    -name '*.syntax' -o \
    -name '*.YAML' -o \
    -name '*.yaml' -o \
    -name '*.yaml-tmlanguage' -o \
    -name '*.yaml.sed' -o \
    -name '*.YML' -o \
    -name '*.yml.mysql' -o \
    -name '.clang-format' -o \
    -name '.clang-tidy' -o \
    -name '.clangd' -o \
    -name '.gemrc' -o \
    -name '.yamllint' -o \
    -name 'docker_fish_history' -o \
    -name 'fish_history' -o \
    -name 'glide.lock' -o \
    -name 'pixi.lock' -o \
    -name 'yarn.lock' \
    ')' \
    -type f \
    -exec sh -c -- 'for file in "${@}"; do
  git ls-files --error-unmatch -- "${file-}" >/dev/null 2>&1 ||
    ! git rev-parse --is-inside-work-tree >/dev/null 2>&1 &&
    yamllint --format colored --strict -- "${file-}"
done' _ {} +
}

yaml_prettier_r() {
  command -v -- prettier >/dev/null 2>&1 ||
    # EX_UNAVAILABLE
    return 69
  find -- . \
    -path '*/.git' -prune -o \
    -path '*/.well-known' -prune -o \
    -path '*/Empty' -prune -o \
    -path '*/Library' -prune -o \
    -path '*/node_modules' -prune -o \
    -path '*/t' -prune -o \
    -path '*/Test*' -prune -o \
    -path '*/test*' -prune -o \
    -path '*/tst*' -prune -o \
    -path '*copilot*' -prune -o \
    -path '*dummy*' -prune -o \
    -path '*vscode*' -prune -o \
    '(' \
    -name '*.yml' -o \
    -name '*.CFF' -o \
    -name '*.cff' -o \
    -name '*.mir' -o \
    -name '*.reek' -o \
    -name '*.rviz' -o \
    -name '*.sublime-syntax' -o \
    -name '*.syntax' -o \
    -name '*.YAML' -o \
    -name '*.yaml' -o \
    -name '*.yaml-tmlanguage' -o \
    -name '*.yaml.sed' -o \
    -name '*.YML' -o \
    -name '*.yml.mysql' -o \
    -name '.clang-format' -o \
    -name '.clang-tidy' -o \
    -name '.clangd' -o \
    -name '.gemrc' -o \
    -name '.yamllint' -o \
    -name 'docker_fish_history' -o \
    -name 'fish_history' -o \
    -name 'glide.lock' -o \
    -name 'pixi.lock' -o \
    -name 'yarn.lock' \
    ')' \
    -type f \
    -exec sh -c -- 'for file in "${@}"; do
  git ls-files --error-unmatch -- "${file-}" >/dev/null 2>&1 ||
    ! git rev-parse --is-inside-work-tree >/dev/null 2>&1 &&
    prettier --log-level log --write -- "${file-}"
done' _ {} +
}

# YouTube downloader
yt() {
  command -v -- yt-dlp >/dev/null 2>&1 ||
    # EX_UNAVAILABLE
    return 69
  test "${#}" -gt 0 ||
    # EX_USAGE
    return 64
  case "${1-}" in
  --video)
    shift 1 &&
      for video in "${@}"; do
        # removing `--format`/`-f` ensures the best quality video
        yt-dlp --verbose --console-title --abort-on-error --break-on-existing --restrict-filenames --windows-filenames --no-overwrites --write-thumbnail --audio-quality=0 --keep-video --embed-thumbnail --add-metadata --xattrs --fixup=detect_or_warn -- "${video-}"
      done
    ;;
  *)
    for video in "${@}"; do
      # try for m4a first
      yt-dlp --verbose --console-title --abort-on-error --break-on-existing --restrict-filenames --windows-filenames --no-overwrites --write-thumbnail --audio-quality=0 --keep-video --embed-thumbnail --add-metadata --xattrs --fixup=detect_or_warn --format=m4a -- "${video-}" ||
        # if not then try mp3
        yt-dlp --verbose --console-title --abort-on-error --break-on-existing --restrict-filenames --windows-filenames --no-overwrites --write-thumbnail --audio-quality=0 --keep-video --embed-thumbnail --add-metadata --xattrs --fixup=detect_or_warn --format=mp3 -- "${video-}" ||
        # if not then this mess which changes `--format` into `--list-formats`
        yt-dlp --verbose --console-title --abort-on-error --break-on-existing --restrict-filenames --windows-filenames --no-overwrites --write-thumbnail --audio-quality=0 --keep-video --embed-thumbnail --add-metadata --xattrs --fixup=detect_or_warn --list-formats -- "${video-}"
    done
    ;;
  esac
}

zshabbr() {
  command -v -- shfmt >/dev/null 2>&1 &&
    command -v -- abbr >/dev/null 2>&1 ||
    # EX_UNAVAILABLE
    return 69
  set \
    -o noglob \
    -o verbose \
    -o xtrace
  if test -s "${ABBR_USER_ABBREVIATIONS_FILE-}"; then
    set -- "${ABBR_USER_ABBREVIATIONS_FILE-}"
  elif test -s "${XDG_CONFIG_HOME-}"'/zsh-abbr/user-abbreviations'; then
    set -- "${XDG_CONFIG_HOME-}"'/zsh-abbr/user-abbreviations'
  elif test -s "${XDG_CONFIG_HOME-}"'/zsh/abbreviations'; then
    set -- "${XDG_CONFIG_HOME-}"'/zsh/abbreviations'
  else
    # EX_NOINPUT
    return 66
  fi
  "${EDITOR:-vi}" -- "${1-}" &&
    shfmt --indent 2 --language-dialect bash --simplify --write -- "${1-}" &&
    abbr load
  {
    set \
      +o noglob \
      +o verbose \
      +o xtrace
  } 2>/dev/null
}
alias \
  zshenv='"${EDITOR:-vi}" -- "${ZDOTDIR:-${HOME%/}}"/."$(basename -- "${SHELL%%[0-9-]*}")"env && exec - "${SHELL##*/}"' \
  zlogin='"${EDITOR:-vi}" -- "${ZDOTDIR:-${HOME%/}}"'\''/.'\''"$(printf -- '\''%.1slogin'\'' "${SHELL##*/}")" && exec - "${SHELL##*/}"' \
  zlogout='"${EDITOR:-vi}" -- "${ZDOTDIR:-${HOME%/}}"'\''/.'\''"$(printf -- '\''%.1slogout'\'' "${SHELL##*/}")" && exec - "${SHELL##*/}"' \
  zprofile='"${EDITOR:-vi}" -- "${ZDOTDIR:-${HOME%/}}"'\''/.'\''"$(printf -- '\''%.1sprofile'\'' "${SHELL##*/}")" && exec - "${SHELL##*/}"' \
  zshrc='"${EDITOR:-vi}" -- "${ZDOTDIR:-${HOME%/}}"'\''/.'\''"$(basename -- "${SHELL%%[0-9-]*}")"'\''rc'\'' && exec - "${SHELL##*/}"' \
  z='. "${ZDOTDIR:-${HOME%/}}"'\''/.'\''"$(basename -- "${SHELL%%[0-9-]*}")"'\''rc'\''' \
  zshdebug='( builtin emulate -R zsh -C -v -x -c -- '\''. "${ZDOTDIR:-${HOME%/}}"'\''/.'\''"$(basename -- "${SHELL%%[0-9-]*}")"'\''rc'\'';'\''; );' \
  zshdebug_rc='( builtin emulate -R zsh -C -v -x -c -- '\''zmodload zsh/zprof; . "${ZDOTDIR:-${HOME%/}}"'\''/.'\''"$(basename -- "${SHELL%%[0-9-]*}")"rc; zprof;'\''; );' \
  zshdebug_env='( builtin emulate -R zsh -C -v -x -c -- '\''zmodload zsh/zprof; . "${ZDOTDIR:-${HOME%/}}"'\''/.'\''"$(basename -- "${SHELL%%[0-9-]*}")"env; zprof;'\''; );'

# history recovery
# https://unix.stackexchange.com/a/551083
zsh_history_recovery() {
  builtin fc -W -- ./zsh_history_recovery_"$(LANG='C' LC_ALL='C' date -- '+%Y%m%d')"
}
alias \
  history_restore='zsh_history_recovery' \
  restore_history='zsh_history_recovery'

zshoptions_search() {
  # prepare a string to use in a zsh manpage grep, where
  # • underscores are meaningless
  # • searching by case is not helpful
  # • a prefix of `no` or `no_` must be ignored
  test "${#}" -eq 1 ||
    # EX_USAGE
    return 64
  printf -- '%s\n' "${1-}" |
    sed \
      -e 's/_//g' \
      -e 's/^[[:space:]]*//' \
      -e 's/^[Nn][Oo]//' \
      -e 's/[[:space:]]*$//' |
    awk -- '{
  for (i = 1; i <= length($0); i++) {
    printf "[%s%s]", toupper(substr($0, i, 1)), tolower(substr($0, i, 1))
    # skip printing `_*` after the last character
    if (i < length($0)) {
      printf "_*"
    }
  }
  printf "\n"
}' |
    tee -- /dev/tty | {
    xclip -selection clipboard ||
      xsel --clipboard --input ||
      pbcopy -pboard general ||
      cat -- -
  } >/dev/null 2>&1
}

## zero-width space, shrug, and sparkle
# copy to macOS clipboard
alias \
  zwsp='printf -- '\''​'\'' | pbcopy' \
  shrug='printf -- '\''\302\257\134_(\343\203\204)_/\302\257'\'' | pbcopy && printf -- '\''\302\257\134_(\343\203\204)_/\302\257\n'\''' \
  sparkle='printf -- '\''\342\234\250'\'' | pbcopy && printf -- '\''\342\234\250\n'\'''
