dotfiles

Contents

zsh

.zprofile

emulate sh -c 'source /etc/profile'
PATH=$PATH:$HOME/.scripts

export FLOATING_TERM=xterm
export TERM=alacritty
export BROWSER=firefix-nightly
export EDITOR=nvim
export VISUAL=nvim
export LC_ALL=en_US.UTF-8
export OPENER=rifle
export PAGER=less
export MANPAGER="sh -c 'col -bx | bat -l man -p --paging always'"

export XDG_CONFIG_HOME=$HOME/.config
export XDG_CACHE_HOME=$HOME/.cache
export XDG_DATA_HOME=$HOME/.local/share
export IPYTHONDIR="$XDG_CONFIG_HOME"/jupyter
export JUPYTER_CONFIG_DIR="$XDG_CONFIG_HOME"/jupyter
export LESSHISTFILE=-
export NPM_CONFIG_USERCONFIG=$XDG_CONFIG_HOME/npm/npmrc
export GNUPGHOME="$XDG_DATA_HOME"/gnupg
export GOPATH=$XDG_DATA_HOME/go
export PISTOL_CHROMA_FORMATTER=terminal16m
export PISTOL_CHROMA_STYLE=monokai
export SCOPE_PATH="$HOME/.config/ranger/scope.sh"
export CACHE_PATH="$HOME/.cache/ranger"

export __GL_SHADER_DISK_CACHE_PATH=$XDG_CACHE_HOME/nvidia/
export MESA_LOADER_DRIVER_OVERRIDE=iris
export QT_QPA_PLATFORMTHEME=qt5ct
export MOZ_X11_EGL=1
export LIBVA_DRIVER_NAME=i965

export LESS_TERMCAP_mb=$'\e[1;32m'
export LESS_TERMCAP_md=$'\e[1;32m'
export LESS_TERMCAP_me=$'\e[0m'
export LESS_TERMCAP_se=$'\e[0m'
export LESS_TERMCAP_so=$'\e[01;33m'
export LESS_TERMCAP_ue=$'\e[0m'
export LESS_TERMCAP_us=$'\e[1;4;31m'

sudo tee /sys/devices/system/cpu/intel_pstate/no_turbo <<<1 >/dev/null

.zshrc

if [[ -r "${XDG_CACHE_HOME:-$HOME/.cache}/p10k-instant-prompt-${(%):-%n}.zsh" ]]; then
  source "${XDG_CACHE_HOME:-$HOME/.cache}/p10k-instant-prompt-${(%):-%n}.zsh"
fi


export GPG_TTY=$TTY
source $HOME/.macrorc
source $HOME/.functionrc
source $HOME/.aliasrc
source /usr/share/z/z.sh

setopt auto_cd

bindkey -e
bindkey "^[[3~" delete-char
autoload -U edit-command-line
zle -N edit-command-line
bindkey '\C-x\C-e' edit-command-line
bindkey '\C-e' end-of-line
bindkey '\C-a' beginning-of-line
bindkey '\C-f' delete-word
bindkey '\C-w' backward-delete-word
bindkey '\C-l' forward-word
bindkey '\C-h' backward-word
bindkey '\C-j' down-line-or-history
bindkey '\C-k' up-line-or-history

### ZSH autosuggestions config
ZSH_AUTOSUGGEST_STRATEGY=(match_prev_cmd completion history)
ZSH_AUTOSUGGEST_USE_ASYNC=1
ZSH_AUTOSUGGEST_BUFFER_MAX_SIZE=20
ZSH_AUTOSUGGEST_MANUAL_REBIND=1
alias zrebind="_zsh_autosuggest_bind_widgets"

### fzf tab completion
local extract="
local in=\${\${\"\$(<{f})\"%\$'\0'*}#*\$'\0'}
local -A ctxt=(\"\${(@ps:\2:)CTXT}\")
local realpath=\${ctxt[IPREFIX]}\${ctxt[hpre]}\$in
realpath=\${(Qe)~realpath}
"
zstyle ':completion:*' list-colors "${(s.:.)LS_COLORS}"
zstyle ':completion:*' matcher-list '' 'm:{a-zA-Z}={A-Za-z}'
zstyle ':completion:*:descriptions' format '[%d]'
zstyle ':fzf-tab:complete:kill:argument-rest' extra-opts --preview=$extract'ps --pid=$in[(w)1] -o cmd --no-headers -w -w' --preview-window=down:5:wrap
zstyle ':fzf-tab:complete:cd:*' extra-opts --preview=$extract'ls -sh --color=always $realpath'

# init zinit
source "$HOME/.zinit/bin/zinit.zsh"
autoload -Uz _zinit
(( ${+_comps} )) && _comps[zinit]=_zinit

zinit light-mode for \
    zinit-zsh/z-a-patch-dl \
    zinit-zsh/z-a-as-monitor \
    zinit-zsh/z-a-bin-gem-node

zinit light romkatv/powerlevel10k
zinit ice lucid wait='0'
zinit snippet OMZ::lib/termsupport.zsh
zinit snippet OMZ::lib/history.zsh
zinit ice lucid wait='0'
zinit snippet OMZ::plugins/fzf/fzf.plugin.zsh

zpcompinit; zpcdreplay

zinit ice lucid wait='0'
zinit light Aloxaf/fzf-tab
zinit ice lucid wait='0'
zinit light zsh-users/zsh-completions
zinit ice lucid wait='0'
zinit light zdharma/fast-syntax-highlighting
zinit ice lucid wait atload='_zsh_autosuggest_start'
zinit light zsh-users/zsh-autosuggestions

# To customize prompt, run `p10k configure` or edit ~/.p10k.zsh.
[[ ! -f ~/.p10k.zsh ]] || source ~/.p10k.zsh

.aliasrc

#!/usr/bin/zsh

alias pacup='yay -Syu --ignore linux,linux-headers'
alias cp='cp -v '
alias dud='du -sh --'
alias cpr='rsync -arvhP'
alias sudo='sudo '
alias vim="nvim"
alias v="nvim"
alias -s txt='less -r'
alias -s zip='unzip -l'
alias dragon="dragon -a -x"
alias dosbox="dosbox -conf $HOME/.config/dosbox/dosbox.conf"
alias c="clear"
alias pwdc="pwd | xclip -selection clipboard"
alias diff="diff --color=always"
alias se="sudoedit"
alias fyay="yay -Slq | fzf -m --preview 'yay -Si {1}' | yay -S -"
alias dg='/usr/bin/git --git-dir=$HOME/Git/dotfiles/ --work-tree=$HOME'
alias clip=" xclip -selection clipboard"
alias pw="password "
alias mime="file --mime-type "

alias hl='highlight -O html --base16=twilight -I '
alias kjv='kjv-fzf'

alias ls='exa'
alias l='exa -al'

# change cursor style on the fly
alias cu_l="printf '\033[6 q'"
alias cu_u="printf '\033[4 q'"
alias cu_b="printf '\033[1 q'"

# custom functions alias
alias cpt='zsh -c "$(declare -f cpt);cpt"'
alias cpf='zsh -c "$(declare -f cpf);cpf"'
alias hcpt='zsh -c "$(declare -f hcpt);hcpt"'
alias hcpf='zsh -c "$(declare -f hcpf);hcpf"'
alias fcp='zsh -c "$(declare -f fcp);fcp"'
alias hfcp='zsh -c "$(declare -f hfcp);hfcp"'

alias lc='print -z $(fc -e -)'
alias lcc='$(echo "Executed command :">&2);echo `fc -e -` | tee $TTY | xclip -selection clipboard ; echo -e "\nOutput copied"'

.functionrc

### copy & paste
cpf() { fd -L . '/home/' '/usr/local/' '/run/media/'  -t f -t d  | fzf-tmux -m   --height=50% --preview='pistol {}' | xargs -I {} rsync -asvrhP {} .  || echo "Nothing done"; }
cpt() { local from=$( fd -L . -t f -t d | fzf-tmux  --height=50% -m --preview='pistol {}' --header='Source') ; [ -n "$from" ] && local to="$( fd -L . '/home/' '/usr/local/'  '/run/media/' -t d | fzf-tmux +m --header='Destination' --preview='ls -sh --color=always {}')" ; [ -n "$to" ] && echo $from | xargs -I {} rsync -asvrhP {} $to && pushd $to || echo "Nothing done" ; }

hcpf() { fd -L -H  . '/home/' '/usr/local/' '/run/media' -t f -t d  | fzf-tmux -m --height=50% --preview='pistol {}' | xargs -I {} rsync -asvrhP {} .  || echo "Nothing done"; }
hcpt() { local from=$( fd -L -H . -t f -t d | fzf-tmux -m --preview='pistol {}' --header='Source') ; [ -n "$from" ] && local to="$( fd -L -H . '/home/' '/usr/local/'  '/run/media/' -t d | fzf-tmux +m   --height=50% --header='Destination' --preview='ls -sh --color=always {}')" ; [ -n "$to" ] && echo $from | xargs -I {} rsync -asvrhP {} $to && pushd $to || echo "Nothing done" ; }

fcp() { local from=$(fd -L . '/home/' '/usr/local' '/run/media' -t f -t d  | fzf-tmux -m --header='Source' --preview='pistol {}') ; [ -n "$from" ] && local to="$( fd -L . '/home/' '/usr/local/'  '/run/media/' -t d | fzf-tmux +m   --height=50%  --header='Destination' --preview='ls -sh --color=always {}')" ; [ -n "$to" ]  && echo $from | xargs -I {} rsync -asvrhP {} $to && pushd $to || echo "Nothing done" ; }
hfcp() { local from=$(fd -L -H . '/home/' '/usr/local' '/run/media' -t f -t d  | fzf-tmux -m --header='Source' --preview='pistol {}') ; [ -n "$from" ] && local to="$( fd -L -H . '/home/' '/usr/local/' -t d | fzf-tmux +m   --height=50% --header='Destination' --preview='ls -sh --color=always {}')" ; [ -n "$to" ]  && echo $from | xargs -I {} rsync -asvrhP {} $to && pushd $to || echo "Nothing done" ; }

# open files, manual, z-jump, cdir
m() { man -k . | fzf-tmux --preview='man {1}{2}' --preview-window=right:70%:wrap --bind 'enter:execute(man {1}{2})' }

o() { target=$(fd -H -L -t f -t d | fzf-tmux  --preview='pistol {}' --preview-window right:70%:wrap --bind 'ctrl-o:execute(rifle {}),ctrl-v:execute(rifle -f t {}),enter:accept' --header='enter:accept | ctrl-v:open with new terminal | ctrl-o:open') ; [ -n "$target" ] && rifle "$target"; }
so() { target=$(fd -L -t f | sk -c 'fd {}' --preview='pistol {}' --preview-window right:70%:wrap --bind 'ctrl-o:execute(rifle {}),ctrl-v:execute(rifle -f t {}),enter:accept' --header='enter:accept | ctrl-v:open with new terminal | ctrl-o:open') ; [ -n "$target" ] && rifle "$target"; }

. /usr/share/z/z.sh
z() {
  [ $# -gt 0 ] && _z "$*" && return
  target=$(_z -l 2>&1 | fzf-tmux +m --height 70% --nth 2.. --reverse --inline-info +s --tac --query "${*##-* }" --preview "dirname=\$(echo {} | sed 's/^[0-9..]* *//;s/\ /\\ /g') ; ls -sh --color=always \$dirname" | sed 's/^[0-9,.]* *//')
  cd "$target"
}

g() { local dest="$( fd -L -H . '/home' '/usr/local/' '/usr/share/' '/run/media' -t d | fzf-tmux +m  --height=50% --preview='ls -sh --color=always {}')"; [ -n "$dest" ] && cd $dest ; }


# rga
rgaf() { sk -i -c 'rga "{}" --ignore-case --files-with-matches --no-messages --rga-cache-max-blob-len=100000000' --preview "rga --ignore-case --pretty --context 10 {cq} {}" --preview-window right:50%:wrap --bind 'ctrl-o:execute(rifle {}),ctrl-v:execute(rifle -f t {}),enter:accept' --header='enter:accept | ctrl-v:open with new terminal | ctrl-o:open'| xargs -I this rifle this }

rgf() { sk -i -c 'rg -n "{}"' -d ':' --nth 1 --preview "pistol {}" --preview-window right:70%:wrap | awk -F':' '{print $1}' | xargs -I this rifle this }

### misc
aurgen() { makepkg --printsrcinfo > .SRCINFO && echo "SRCINFO generated"; updpkgsums; echo "Checksum updated" ; git add --force PKGBUILD .SRCINFO && echo "PKGBUILD and .SRCINFO added" ; }
getcolor() { grim -g "$(slurp -p)" -t ppm - | convert - -format '%[pixel:p{0,0}]' txt:- ; }
pacmir() { sudo reflector --country Germany --latest 5 --sort rate --verbose --save /etc/pacman.d/mirrorlist ; }

## print palette
palette() { local -a colors ; for i in {000..255}; do colors+=("%F{$i}$i%f"); done ; print -cP $colors ; }
printc() { local color="%F{$1}" ; echo -E ${(qqqq)${(%)color}} ; }

r() {
	local temp_file="$(mktemp -t "ranger_cd.XXXXXXXXXX")"
	ranger --choosedir="$temp_file" -- "${@:-$PWD}"
	if local chosen_dir="$(cat -- "$temp_file")" && [ -n "$chosen_dir" ] && [ "$chosen_dir" != "$PWD" ]; then
        	cd -- "$chosen_dir"
	fi
	rm -f -- "$temp_file"
}

### conda
startconda() {
__conda_setup="$('/opt/miniconda3/bin/conda' 'shell.zsh' 'hook' 2> /dev/null)"
if [ $? -eq 0 ]; then
    eval "$__conda_setup"
else
    if [ -f "/opt/miniconda3/etc/profile.d/conda.sh" ]; then
        . "/opt/miniconda3/etc/profile.d/conda.sh"
    else
        export PATH="/opt/miniconda3/bin:$PATH"
    fi
fi
unset __conda_setup
}

.macrorc

export SSLKEYLOGFILE=$HOME/.cache/sslkeylog.log

export FZF_DEFAULT_COMMAND='fd -L -H -t d -t f --exclude .git'
export FZF_DEFAULT_OPTS=" --hscroll-off=100 --reverse -m --cycle --bind up:preview-up,down:preview-down,ctrl-/:toggle-preview,ctrl-j:toggle+down,ctrl-k:toggle+up,tab:down,shift-tab:up,ctrl-l:toggle,home:top,ctrl-x:clear-screen"
export FZF_ALT_C_COMMAND='fd -H -L -t d'
export FZF_CTRL_T_COMMAND="$FZF_DEFAULT_COMMAND"

export SKIM_DEFAULT_OPTIONS=" -c '{}' --multi --reverse --bind up:preview-up,down:preview-down,?:toggle-preview,ctrl-j:toggle+down,ctrl-k:toggle+up,tab:down,shift-tab:up,ctrl-space:toggle --preview-window=wrap"

export CACA_DRIVER=ncurses
export MAKEFLAGS="-j12"

export NVIM_LISTEN_ADDRESS="/tmp/nvimsocket nvim"

export BAT_THEME="base16"

export _Z_CMD="j"

bspwm & sxhkd

bspwmrc

#!/bin/sh

# start programs
sxhkd &
#xcompmgr -c &
#picom --config "$HOME/.config/picom/picom.conf" --experimental-backends -b
libinput-gestures-setup start
dunst &
fcitx5 -d &
feh --bg-fill $HOME/Pictures/Wallpapers/dark.jpg
searx-run &


bspc monitor -d I II III IV V VI VII VIII IX X
bspc config border_width         3
bspc config window_gap          15
bspc config focus_follows_pointer true
bspc config split_ratio          0.6
bspc config borderless_monocle   true
bspc config gapless_monocle      true
bspc config normal_border_color   \#000000
bspc config focused_border_color  \#a2a0a3
bspc config presel_feedback_color \#5c564c
bspc config automatic_scheme  	  alternate
bspc config removal_adjustment
bspc config honor_size_hints
bspc config ignore_ewmh_struts

bspc rule -a Gimp desktop='^8' state=floating follow=on
bspc rule -a mpv state=floating layer=above
bspc rule -a Screenkey manage=off
bspc rule -a \* center=true rectangle=1920x1080+0+0
bspc rule -a *:float state=floating center=true rectangle=1920x1080+0+0 layer=above
bspc rule -a Zathura state=tiled center=true rectangle=1440x1920+0+0
bspc rule -a XTerm state=floating center=true rectangle=1920x1080+0+0 layer=above

pkill polybar
polybar example 1>&2 &

sxhkd

# wm independent hotkeys

# terminal emulator
super + Return
	$TERM

# program launcher
super + d
	$FLOATING_TERM -e fzflaunch

alt + Tab
	bspwm_switch

# mpv launcher
super + o
	fzfo

# make sxhkd reload its configuration files:
super + Escape
	pkill -USR1 -x sxhkd

#
# bspwm hotkeys
#

# quit/restart bspwm
super + alt + {q,r}
	bspc {quit,wm -r}

# close and kill
super + {_,shift + }q
	bspc node -{c,k}

# alternate between the tiled and monocle layout
super + m
	bspc desktop -l next

# send the newest marked node to the newest preselected node
super + y
	bspc node newest.marked.local -n newest.!automatic.local

# swap the current node and the newest marked node
super + g
	bspc node -s newest.marked.local --follow

# state/flags
# set the node flags
super + ctrl + m
	bspc node -g locked ; \
	notify-send "Window locked toggle"

super + ctrl + s
	bspc node -g sticky ; \
	notify-send "Window sticky toggle"

super + ctrl + p
	bspc node -g private ; \
	notify-send "Window private toggle"

super + ctrl + a
	bspc node -g marked ; \
	notify-send "Window marked"
# focus/swap
#

# focus the node in the given direction
super + {_,shift + }{h,j,k,l}
	bspc node -{f,s} {west,south,north,east}

# focus the node for the given path jump
super + {p,b,comma,period}
	bspc node -f @{parent,brother,first,second}

# focus the next/previous node in the current desktop
super + {_,shift + }c
	bspc node -f {next,prev}.local

# focus the next/previous desktop in the current monitor
super + bracket{left,right}
	bspc desktop -f {prev,next}.local

# focus the last node/desktop
super + {grave,Tab}
	bspc {node,desktop} -f last


# focus or send to the given desktop
super + {_,shift + }{1-9,0}
	bspc {desktop -f,node -d} '^{1-9,10}'

#
# preselect
#

# preselect the direction
super + ctrl + {h,j,k,l}
	bspc node -p {west,south,north,east}

# preselect the ratio
super + ctrl + {1-9}
	bspc node -o 0.{1-9}

# cancel the preselection for the focused node
super + ctrl + c
	bspc node -p cancel

# move to the preselection
super + ctrl +  space
	bspc node -n 'last.!automatic.local'

#
# move/resize
#

# expand a window by moving one of its side outward
super + alt + {h,j,k,l}
	bspc node -z {left -40 0,bottom 0 40,top 0 -40,right 40 0}

# contract a window by moving one of its side inward
super + alt + shift + {h,j,k,l}
	bspc node -z {right -40 0,top 0 40,bottom 0 -40,left 40 0}

# move a floating window
super + {Left,Down,Up,Right}
	bspc node -v {-40 0,0 40,0 -40,40 0}

#
# state related
#
super + {t,shift + t}
	bspc node -t {tiled,pseudo_tiled}

super + f
	bspc node -t \~fullscreen

super + space
	bspc node focused -t \~floating


#
# volume control
#
XF86AudioLowerVolume
	pamixer -d 3
XF86AudioRaiseVolume
	pamixer -i 3
XF86AudioMute
	pamixer -t

#
# playerctl
#
XF86AudioPlay
	playerctl play-pause
XF86AudioNext
	playerctl next
XF86AudioPrev
	playerctl previous

#
# screenshot
#
ctrl + shift + 3
	maim $HOME/Pictures/shots/$(date +%s).png -s
ctrl + shift + 4
	maim -s | xclip -selection clipboard -t image/png
ctrl + semicolon
	shot


#
# rotate
#
super + e
	bspc node -R 90
super + r
	bspc node @/ -R 90

#
# status
#

# toggle polybar
super + x
	polybar-msg cmd toggle ; bspc config bottom_padding 0

Scripts

bspwm_switch

#!/usr/bin/env sh

bspc query -N -n .window | tr '[\n]' '[\0]' | xargs -r0 dash -c 'for i in "$@"; do printf "$i\t" ; xdotool getwindowname "$i"; done;' ' ' | fzfmenu | xargs bspc node -f

fzfo

#!/usr/bin/env sh

cddir=$(fd . '/home' '/run/media' -L -t f -t d | fzfmenu  "--preview='pistol {}' --preview-window right:50%:wrap --bind 'ctrl-o:execute(rifle {}),ctrl-v:execute(rifle -f t {}),enter:accept'")
[ -n "$cddir" ] && $TERM -e sh -c "rifle \"$cddir\""
exit

fzfs

__fzffs_fzf ()
{
    declare \
        prompt=${1:->}
 #       FZF_DEFAULT_COMMAND= \
 #       FZF_DEFAULT_OPTS= ;

    fzf --prompt="${prompt} " --preview="pistol {10}" --layout=default
}

__fzffs_find ()
{
    find -H "${1}/." ! -name . -prune -inum "$2" -exec basename '{}' \; 2>/dev/null
}

__fzffs_ls ()
{
    printf '[%s] %s\n[%s] %s\n[%s] %s\n[%s] %s\n[%s] %s\n' \
        "." "pwd" \
        ".." "up" \
        "/" "root" \
        "q" "quit" \
        "~" "cd" ;

    # Do not use tac/tail -r and tail -n +2 or ls -A (POSIX)
    ls -laHi | sed -n '2!G;h;$p'
}

__fzffs_quit ()
{
    unset -f \
        __fzffs_browse \
        __fzffs_find \
        __fzffs_fzf \
        __fzffs_ls \
        __fzffs_main \
        __fzffs_quit ;

    #trap - EXIT TERM
    #eval "$_fzffs_traps_old"

    declare -xg LC_COLLATE=$_fzffs_LC_COLLATE_old

    unset -v \
        _fzffs_LC_COLLATE_old \
        _fzffs_traps_old ;
}

__fzffs_browse ()
while [[ $pwd ]]
do
    builtin cd -- "$pwd"
    child_ls=$(__fzffs_ls "$pwd" | __fzffs_fzf "[${pwd}]")
    case $child_ls in
        \[..\]*|*..)
            pwd=${pwd%/*}
            pwd=${pwd:-$root}
            ;;
        \[.\]*|*.)
            :
            ;;
        \[~\]*)
            pwd=$HOME
            ;;
        \[/\]*)
            pwd=$root
            ;;
        \[q\]*)
            pwd=
            ;;
        *)
            child_basename=$(__fzffs_find "$pwd" "${child_ls%% *}")
            if [[ -d ${pwd}/${child_basename} ]]
            then
                pwd=${pwd}/${child_basename}
                pwd=${pwd//\/\//\/}
            elif [[ -f ${pwd}/${child_basename} || \
                -p ${pwd}/${child_basename} ]]
            then
		rifle "${pwd}/${child_basename}"
#                case $(file --mime-type -bL "${pwd}/${child_basename}")
#                in
#                    image*)
#                        w3m -o 'ext_image_viewer=off' \
#                            -o 'imgdisplay=w3mimgdisplay' \
#                            "${pwd}/${child_basename}" ;
#                        ;;
#                    *)
#                        bat "${pwd}/${child_basename}"
#                esac
            else
                pwd=
            fi
    esac
done

__fzffs_main ()
{
    declare \
        child_ls= \
        child_basename= \
        pwd=$1 \
        root=/ ;

    declare -gx \
        _fzffs_LC_COLLATE_old=$LC_COLLATE \
        LC_COLLATE=C ;
        #_fzffs_traps_old=$(trap) ;

    #trap -- 'echo quit ; __fzffs_quit' EXIT TERM

    if [[ $pwd == .. ]]
    then
        pwd=${PWD%/*}
        pwd=${pwd:-$root}
    elif [[ -z $pwd || $pwd == . ]]
    then
        pwd=$PWD
    elif [[ -d $pwd ]]
    then
        if [[ ${pwd:${#pwd}-1} == / ]]
        then
            pwd=${pwd%/*}
            pwd=${pwd:-$root}
        else
            pwd=$pwd
        fi
    else
        __fzffs_quit
        {
            printf '%s\n' \
            "${BASH_SOURCE:-$0}:Error:79: Not a directory: '${pwd}'" 1>&2
            return 79
        }
    fi

    { tput smcup || tput ti ; } 2>/dev/null

    __fzffs_browse

    __fzffs_quit
}

# -- MAIN.

__fzffs_main "$1"

fzfmenu

#!/usr/bin/env sh
# fzfmenu - fzf as dmenu replacement

arg=$1
input=$(mktemp -u --suffix .fzfmenu.input)
output=$(mktemp -u --suffix .fzfmenu.output)
mkfifo $input
mkfifo $output
chmod 600 $input $output


# it's better to use st here (starts a lot faster than pretty much everything else)
# kitty --single-instance --class=float -e sh -c "cat $input | fzf $* $arg | tee $output"
# specific to alacritty
$FLOATING_TERM  -e dash -c "cat $input | fzf $* $arg | tee $output"  & disown

# handle ctrl+c outside child terminal window
trap "kill $! 2>/dev/null; rm -f $input $output" EXIT

cat > $input
cat $output

fzflaunch

# terminal application launcher for sway, using fzf
# Based on: https://gitlab.com/FlyingWombat/my-scripts/blob/master/sway-launcher
# https://gist.github.com/Biont/40ef59652acf3673520c7a03c9f22d2a

shopt -s nullglob
if [[ "$1" == 'describe' ]]; then
  shift
  if [[ $2 == 'command' ]]; then
    title=$1
    readarray arr < <(whatis -l "$1" 2>/dev/null)
    description="${arr[0]}"
    description="${description%*-}"
  else
    title=$(sed -ne '/^Name=/{s/^Name=//;p;q}' "$1")
    description=$(sed -ne '/^Comment=/{s/^Comment=//;p;q}' "$1")
  fi
  echo -e "\033[36m$title\033[0m"
  echo "${description:-No description}"
  exit
fi

DIRS=(
  /usr/share/applications
  "$XDG_DATA_HOME/applications"
  /usr/local/share/applications
)

GLYPH_COMMAND="TER "
GLYPH_DESKTOP="DSK "

FZFPIPE=$(mktemp)
PIDFILE=$(mktemp)
trap 'rm "$FZFPIPE" "$PIDFILE"' EXIT INT


# Load and append Desktop entries
(
  for dir in "${DIRS[@]}"; do
    [[ -d "$dir" ]] || continue
    awk -v pre="$GLYPH_DESKTOP" -F= '
                BEGINFILE{application=0;block="";a=0}
                /^\[Desktop Entry\]/{block="entry"}
                /^Type=Application/{application=1}
                /^\[Desktop Action/{
                  sub("^\\[Desktop Action ", "");
                  sub("\\]$", "");
                  block="action";
                  a++;
                  actions[a,"key"]=$0
                }
                /^Name=/{
                if(block=="action") {
                    actions[a,"name"]=$2;
                } else {
                    name=$2
                }
                }
                ENDFILE{
                  if (application){
                      print FILENAME "\034desktop\034\033[35m" pre name "\033[0m";
                      if (a>0)
                          for (i=1; i<=a; i++)
                              print FILENAME "\034desktop\034\033[31m" pre name "\033[0m (" actions[i, "name"] ")\034" actions[i, "key"]
                  }
                }' \
      "$dir/"*.desktop </dev/null >>"$FZFPIPE"
    # the empty stdin is needed in case no *.desktop files
  done
) &

# Load and append command list
(
  IFS=:
  read -ra path <<<"$PATH"
  for dir in "${path[@]}"; do
    printf '%s\n' "$dir/"* |
      awk -F / -v pre="$GLYPH_COMMAND" '{print $NF "\034command\034\033[31m" pre "\033[0m" $NF;}'
  done | sort -u >>"$FZFPIPE"
) &

COMMAND_STR=$(
  (
    tail -n +0 -f "$FZFPIPE" &
    echo $! >"$PIDFILE"
  ) |
    fzf -x -d '\034' --nth ..3 --with-nth 3 \
      --preview "$0 describe {1} {2}" \
      --preview-window=up:3:wrap --ansi
  kill -9 "$(<"$PIDFILE")" | tail -n1
) || exit 1

[ -z "$COMMAND_STR" ] && exit 1


command='echo "nope"'
# shellcheck disable=SC2086
readarray -d $'\034' -t PARAMS <<<${COMMAND_STR}
# COMMAND_STR is "<string>\034<type>"
case ${PARAMS[1]} in
desktop)
  # Define the search pattern that specifies the block to search for within the .desktop file
  PATTERN="^\\\\[Desktop Entry\\\\]"
  if [[ -n ${PARAMS[3]} ]]; then
    PATTERN="^\\\\[Desktop Action ${PARAMS[3]%?}\\\\]"
  fi
  # 1. We see a line starting [Desktop, but we're already searching: deactivate search again
  # 2. We see the specified pattern: start search
  # 3. We see an Exec= line during search: remove field codes and set variable
  # 3. We see a Path= line during search: set variable
  # 4. Finally, build command line
  command=$(awk -v pattern="${PATTERN}" -F= '
                BEGIN{a=0;exec=0;path=0}
                   /^\[Desktop/{
                    if(a){
                      a=0
                    }
                   }
                  $0 ~ pattern{
                   a=1
                  }
                  /^Terminal=/{
                    sub("^Terminal=", "");
                    if ($0 == "true") {
                      terminal=1
                    }
                  }
                  /^Exec=/{
                    if(a && !exec){
                      sub("^Exec=", "");
                      gsub(" ?%[cDdFfikmNnUuv]", "");
                      exec=$0;
                    }
                  }
                  /^Path=/{
                    if(a && !path){
                      path=$2
                    }
                   }

                END{
                  if(path){
                    printf "cd " path " &&"
                  }
                  if (terminal){
                    printf "xterm -e "
                  }
                  print exec
                }' "${PARAMS[0]}")
  setsid $command &
  ;;
command)
  setsid xterm -e ${PARAMS[0]} &
  ;;
esac

diskmount & diskumount

diskmount

#!/usr/bin/env sh

# check wayland or not
NOT=$([ -n "WAYLAND_DISPLAY" ] && echo "mako" || echo "dunst")

mountable=$(lsblk -lp | awk '/part $/&&/sd/{print $1, "(" $4 ")"}')
[ -z "$mountable" ] && pidof $NOT  && notify-send "No mountable device" && exit 1
echo $MENU1
chosen=$(echo "$mountable" | fzf --header='Mountable Devices' | awk '{print $1}')
[ -z "$chosen" ] &&  exit 0
dirs=$(find /mnt -maxdepth 1 -type d -empty 2>/dev/null)
( output=$(udisksctl mount -b $chosen) && notify-send "$output" ) || ( notify-send "Something Wrong" && exit 1)
openornot=$(echo -e "Yes\nNo" | fzf --header='Launch Ranger?' )
[ "$openornot" = "Yes" ] && setsid $FLOATING_TERM -e ranger /run/media/$USER &

diskumount

#!/usr/bin/env sh

# check wayland or not
NOT=$([ -n "WAYLAND_DISPLAY" ] && echo "mako" || echo "dunst")

umountable=$(lsblk -lp | awk '/part/&&/run/{print $0}')
[ -z "$umountable" ] && pidof $NOT && notify-send "No mounted device" && exit 1
chosen=$(echo "$umountable" | fzf --header='Unmountable Devices > ' | awk '{print $1}')
[ -z "$chosen" ] &&  exit 0
( udisksctl unmount -b $chosen && notify-send "$chosen unmounted." ) || ( notify-send "Something wrong happened." && exit 1 )
poweroff=$(echo -e "Yes\nNo" | fzf --header='Power-off? > ' )
( [ "$poweroff" = "Yes" ] && udisksctl power-off -b $chosen && notify-send "$chosen power turned off." ) || notify-send "Turning off power failed."