diff options
| author | TheSiahxyz <164138827+TheSiahxyz@users.noreply.github.com> | 2025-12-07 18:16:05 +0900 |
|---|---|---|
| committer | TheSiahxyz <164138827+TheSiahxyz@users.noreply.github.com> | 2025-12-07 18:16:05 +0900 |
| commit | 5ff02959d3069923bca63cb54c4bb246b86bf20d (patch) | |
| tree | 7ef1b56fb85a48c563bb3af51c26f181741282be | |
| parent | f65fe7591c18d6c8f4ecac5f379407a910aba1bc (diff) | |
deleted .gnupg/gpg-agent.conf, created .gnupg/, created .config/, created .local/, created .gnupg/
33 files changed, 4142 insertions, 0 deletions
diff --git a/global/.gnupg/gpg-agent.conf b/ar/.gnupg/gpg-agent.conf index 15b30ea..15b30ea 100644 --- a/global/.gnupg/gpg-agent.conf +++ b/ar/.gnupg/gpg-agent.conf diff --git a/fedora/.config/bash/autocomplete.bash b/fedora/.config/bash/autocomplete.bash new file mode 100644 index 0000000..0aeeedd --- /dev/null +++ b/fedora/.config/bash/autocomplete.bash @@ -0,0 +1,218 @@ +#!/bin/bash + +### --- Auto-completes aliases --- ### +# alias - normal aliases (completed with trailing space) +# balias - blank aliases (completed without space) +# ialias - ignored aliases (not completed) + +ialiases=() +ialias() { + # usage: ialias name='value' (same as alias builtin) + alias "$@" + # extract name (everything before first '=' or first space) + local args="$1" + args=${args%%=*} + args=${args%% *} + ialiases+=("$args") +} + +baliases=() +balias() { + alias "$@" + local args="$1" + args=${args%%=*} + args=${args%% *} + baliases+=("$args") +} + +# ---------- helper: get alias value ---------- +# returns alias expansion text for a name, or empty if none +_get_alias_value() { + local name="$1" + # alias output: alias ll='ls -la' + local a + a=$(alias "$name" 2>/dev/null) || return 1 + # strip "alias name='...'" + # use parameter expansion / sed safe parsing + # get first occurrence of =', then strip quotes + a=${a#*=} + # remove leading quote if present + a=${a#\'} + a=${a%\'} + printf "%s" "$a" + return 0 +} + +# ---------- helper: membership check ---------- +_in_array() { + local item="$1" + shift + local elem + for elem in "$@"; do + if [[ "$elem" == "$item" ]]; then + return 0 + fi + done + return 1 +} + +# ---------- expand alias at cursor and optionally insert space ---------- +# This function is executed via bind -x, so it can read/modify: +# READLINE_LINE - current full line buffer +# READLINE_POINT - current cursor index (0..len) +expand_alias_space() { + # READLINE_LINE and READLINE_POINT are provided by readline when bind -x is used. + # If not present (if invoked directly), fallback to no-op + if [[ -z "${READLINE_LINE+set}" ]]; then + # fallback: just insert a space + printf " " + return 0 + fi + + local line=${READLINE_LINE} + local point=${READLINE_POINT} + + # left substring up to cursor + local left=${line:0:point} + # right substring after cursor + local right=${line:point} + + # find the last "word" before the cursor (split on whitespace) + # If left ends with whitespace, current word is empty + local lastword + if [[ "$left" =~ [[:space:]]$ ]]; then + lastword="" + else + # remove everything up to last whitespace + lastword=${left##*['$'\t\n' ']} + fi + + # if lastword is empty -> just insert a space + if [[ -z "$lastword" ]]; then + READLINE_LINE="${left} ${right}" + READLINE_POINT=$((point + 1)) + return 0 + fi + + # check if lastword is in ignored aliases -> do not expand, just insert space + if _in_array "$lastword" "${ialiases[@]}"; then + READLINE_LINE="${left} ${right}" + READLINE_POINT=$((point + 1)) + return 0 + fi + + # try to get alias expansion + local expansion + if expansion=$(_get_alias_value "$lastword"); then + # Replace the lastword in left with expansion + # compute left_without_word + local left_without="${left%${lastword}}" + + # If balias: expansion but DO NOT add trailing space + if _in_array "$lastword" "${baliases[@]}"; then + READLINE_LINE="${left_without}${expansion}${right}" + # place cursor right after the expansion + READLINE_POINT=$((${#left_without} + ${#expansion})) + return 0 + else + # Normal alias: expansion and add a space after it + READLINE_LINE="${left_without}${expansion} ${right}" + READLINE_POINT=$((${#left_without} + ${#expansion} + 1)) + return 0 + fi + else + # no alias found: just insert space + READLINE_LINE="${left} ${right}" + READLINE_POINT=$((point + 1)) + return 0 + fi +} + +# ---------- accept-line that expands alias before executing ---------- +# Bind Enter to this function via bind -x; it will expand alias (if needed) then +# simulate Enter by setting READLINE_LINE and returning - readline will accept it. +expand_alias_and_accept_line() { + # Expand at cursor (use current READLINE_LINE/POINT) + expand_alias_space + # After expansion, we want to accept the line as if Enter was pressed. + # To do so in bind -x handler, we can set a marker and then use 'builtin bind -x' hack: + # Simpler approach: write the line to a temp file, then use 'kill -SIGWINCH' ??? Too complex. + # Luckily, when a bind -x handler returns, readline continues; we want to end editing. + # There's no direct way to programmatically press enter. Instead, rely on binding Enter to a wrapper that: + # - modifies READLINE_LINE (done) and then sets a special variable so readline knows to accept. + : +} + +# ---------- key bindings ---------- +# Bind Space to our function so pressing space triggers alias-expansion behavior. +# Use bind -x to call expand_alias_space (it will both expand and insert space when appropriate). +# WARNING: this overrides normal space key behavior; our function handles insertion. +bind -x '" "':expand_alias_space + +# optional: bind Ctrl-Space to the same (a bypass key like zsh had) +# Many terminals send "\C-@" for ctrl-space; try both common sequences: +bind -x '"\C-@":expand_alias_space' 2>/dev/null || true +bind -x '"\C- ":expand_alias_space' 2>/dev/null || true + +# Bind Enter (Return) to expand alias before accepting the line. +# We implement this by expanding then forcing a newline insertion. +# Using bind -x for Enter: when this function returns, readline will NOT automatically accept the line, +# but we can emulate acceptance by printing a newline and forcing input. Simpler: call 'return 0' from this hook +# and then send a newline. However, behavior varies between shells/terminals — so we will bind Enter to a function +# that expands and then uses 'READLINE_LINE' trick to set the expanded line and then call 'builtin bind' to +# temporarily restore Enter to default and re-invoke it. +_bash_accept_line() { + expand_alias_space + # After expanding, we want readline to accept the line. A workaround: + # write the expanded line into the current tty so that it becomes input for the shell. + # But this is messy. Instead, we simply move the cursor to the end and let the user press Enter again. + # (This is a conservative behavior to avoid interfering unexpectedly.) + return 0 +} +bind -x '"\C-m":_bash_accept_line' + +# ---------- helper: background starter ---------- +background() { + # start multiple args as programs in background + # usage: background cmd arg1 arg2 ... + # runs: cmd arg1 & cmd arg2 & ... + local cmd="$1" + shift || return 0 + for arg in "$@"; do + "$cmd" "$arg" &>/dev/null & + done +} + +# ---------- notes ---------- +# - After placing this into ~/.bashrc, run: source ~/.bashrc +# - Test aliases: +# balias ll='ls -la' +# alias g='git status' +# ialias X='something' +# - Then type `ll` followed by Space -> will expand to `ls -la` WITHOUT appending a space (blank alias). +# - Type `g` then Space -> will expand to `git status ` with a trailing space. +# - Type `X` then Space -> will NOT expand, just insert space. +# +# Limitations / caveats: +# - readline/bind -x behavior differs slightly across environments and terminals. +# - Completely emulating zsh's zle widgets (especially auto-accept behaviors) is tricky in bash. +# - Binding Enter to fully accept-after-expansion programmatically is not perfectly portable; +# the conservative implementation above expands first and leaves acceptance to the user (press Enter again). +# +# If you want a stronger behavior (auto-accept after expansion), tell me and I'll provide a +# more aggressive implementation that works on most terminals (but with more invasive tricks). + +# ---------- file completion patterns ---------- +_vim_complete() { + local cur="${COMP_WORDS[COMP_CWORD]}" + COMPREPLY=($(compgen -f -X '!*.@(pdf|odt|ods|doc|docx|xls|xlsx|odp|ppt|pptx|mp4|mkv|aux)' -- "$cur")) +} +shopt -s extglob +complete -F _vim_complete vim + +_build_mom_complete() { + local cur="${COMP_WORDS[COMP_CWORD]}" + COMPREPLY=($(compgen -f -X '!*.mom' -- "$cur")) +} +complete -F _build_mom_complete build-workshop +complete -F _build_mom_complete build-document diff --git a/fedora/.config/bash/bash_profile b/fedora/.config/bash/bash_profile new file mode 100644 index 0000000..068e3f5 --- /dev/null +++ b/fedora/.config/bash/bash_profile @@ -0,0 +1,40 @@ +#!/bin/sh + +umask 022 + +####################################################### +# EXPORTS +####################################################### + +export XDG_CACHE_HOME="$HOME/.cache" +export XDG_CONFIG_HOME="$HOME/.config" +export XDG_DATA_HOME="$HOME/.local/share" +export XDG_STATE_HOME="$HOME/.local/state" +export CLICOLOR=1 +export EDITOR="vim" +export HISTFILE="${XDG_DATA_HOME:-${HOME}/.local/share}/history/sh_history" +export INPUTRC="${XDG_CONFIG_HOME:-${HOME}/.config}/shell/inputrc" +export LESS="R" +export LESS_TERMCAP_mb="$(printf '%b' '[1;31m')" +export LESS_TERMCAP_md="$(printf '%b' '[1;36m')" +export LESS_TERMCAP_me="$(printf '%b' '[0m')" +export LESS_TERMCAP_so="$(printf '%b' '[01;44;33m')" +export LESS_TERMCAP_se="$(printf '%b' '[0m')" +export LESS_TERMCAP_us="$(printf '%b' '[1;32m')" +export LESS_TERMCAP_ue="$(printf '%b' '[0m')" +export LESSOPEN="| /usr/bin/highlight -O ansi %s 2>/dev/null" +export LS_COLORS="no=00:fi=00:di=00;34:ln=01;36:pi=40;33:so=01;35:do=01;35:bd=40;33;01:cd=40;33;01:or=40;31;01:ex=01;32:*.tar=01;31:*.tgz=01;31:*.arj=01;31:*.taz=01;31:*.lzh=01;31:*.zip=01;31:*.z=01;31:*.Z=01;31:*.gz=01;31:*.bz2=01;31:*.deb=01;31:*.rpm=01;31:*.jar=01;31:*.jpg=01;35:*.jpeg=01;35:*.gif=01;35:*.bmp=01;35:*.pbm=01;35:*.pgm=01;35:*.ppm=01;35:*.tga=01;35:*.xbm=01;35:*.xpm=01;35:*.tif=01;35:*.tiff=01;35:*.png=01;35:*.mov=01;35:*.mpg=01;35:*.mpeg=01;35:*.avi=01;35:*.fli=01;35:*.gl=01;35:*.dl=01;35:*.xcf=01;35:*.xwd=01;35:*.ogg=01;35:*.mp3=01;35:*.wav=01;35:*.xml=00;31:" +export LS_OPTIONS="--color=auto" +export TERM="xterm-256color" +export GVIMINIT='let $MYGVIMRC="$XDG_CONFIG_HOME/vim/gvimrc" | source $MYGVIMRC' +export VIMINIT='let $MYVIMRC="$XDG_CONFIG_HOME/vim/vimrc" | source $MYVIMRC' +export VISUAL=$EDITOR + +####################################################### +# Source global/local definitions +####################################################### + +[ -f /etc/bash_completion ] && . /etc/bash_completion +[ -f /usr/share/bash-completion/bash_completion ] && . /usr/share/bash-completion/bash_completion +[ -f /etc/bash/bashrc ] && . /etc/bash/bashrc +[ -f "${XDG_CONFIG_HOME:-${HOME}/.config}/bash/bashrc" ] && . "${XDG_CONFIG_HOME:-${HOME}/.config}/bash/bashrc" diff --git a/fedora/.config/bash/bashrc b/fedora/.config/bash/bashrc new file mode 100644 index 0000000..2c60286 --- /dev/null +++ b/fedora/.config/bash/bashrc @@ -0,0 +1,169 @@ +#!/bin/bash + +[[ $- != *i* ]] && return + +####################################################### +# SET OPTIONS +####################################################### +# history +HISTCONTROL=erasedups:ignoredups:ignorespace +HISTFILESIZE=10000 +HISTSIZE=500 + +# Allow ctrl-S for history navigation (with ctrl-R) +stty -ixon +PROMPT_COMMAND="history -a" +unset GREP_OPTIONS + +set -o vi +shopt -s autocd # goto without cd +shopt -s direxpand # expend directory name +shopt -s cdspell # ignore case cd +shopt -s checkwinsize # Check the window size after each command and, if necessary, update the values of LINES and COLUMNS +shopt -s histappend # Causes bash to append to history instead of overwriting it so if you start a new terminal, you have old session history + +# Completion settings +# Ignore case on auto-completion +# Note: bind used instead of sticking these in .inputrc +bind "set completion-ignore-case on" +# Show auto-completion list automatically, without double tab +bind "set show-all-if-ambiguous on" + +####################################################### +# Set command prompt +####################################################### +alias cpu="grep 'cpu ' /proc/stat | awk '{usage=(\$2+\$4)*100/(\$2+\$4+\$5)} END {print usage}' | awk '{printf(\"%.1f\n\", \$1)}'" +function __setprompt { + local LAST_COMMAND=$? # Must come first! + + # Define colors + local LIGHTGRAY="\033[0;37m" + local WHITE="\033[1;37m" + local BLACK="\033[0;30m" + local DARKGRAY="\033[1;30m" + local RED="\033[0;31m" + local LIGHTRED="\033[1;31m" + local GREEN="\033[0;32m" + local LIGHTGREEN="\033[1;32m" + local BROWN="\033[0;33m" + local YELLOW="\033[1;33m" + local BLUE="\033[0;34m" + local LIGHTBLUE="\033[1;34m" + local MAGENTA="\033[0;35m" + local LIGHTMAGENTA="\033[1;35m" + local CYAN="\033[0;36m" + local LIGHTCYAN="\033[1;36m" + local NOCOLOR="\033[0m" + + # Show error exit code if there is one + if [[ $LAST_COMMAND != 0 ]]; then + # PS1="\[${RED}\](\[${LIGHTRED}\]ERROR\[${RED}\])-(\[${LIGHTRED}\]Exit Code \[${WHITE}\]${LAST_COMMAND}\[${RED}\])-(\[${LIGHTRED}\]" + PS1="\[${DARKGRAY}\](\[${LIGHTRED}\]ERROR\[${DARKGRAY}\])-(\[${RED}\]Exit Code \[${LIGHTRED}\]${LAST_COMMAND}\[${DARKGRAY}\])-(\[${RED}\]" + if [[ $LAST_COMMAND == 1 ]]; then + PS1+="General error" + elif [ $LAST_COMMAND == 2 ]; then + PS1+="Missing keyword, command, or permission problem" + elif [ $LAST_COMMAND == 126 ]; then + PS1+="Permission problem or command is not an executable" + elif [ $LAST_COMMAND == 127 ]; then + PS1+="Command not found" + elif [ $LAST_COMMAND == 128 ]; then + PS1+="Invalid argument to exit" + elif [ $LAST_COMMAND == 129 ]; then + PS1+="Fatal error signal 1" + elif [ $LAST_COMMAND == 130 ]; then + PS1+="Script terminated by Control-C" + elif [ $LAST_COMMAND == 131 ]; then + PS1+="Fatal error signal 3" + elif [ $LAST_COMMAND == 132 ]; then + PS1+="Fatal error signal 4" + elif [ $LAST_COMMAND == 133 ]; then + PS1+="Fatal error signal 5" + elif [ $LAST_COMMAND == 134 ]; then + PS1+="Fatal error signal 6" + elif [ $LAST_COMMAND == 135 ]; then + PS1+="Fatal error signal 7" + elif [ $LAST_COMMAND == 136 ]; then + PS1+="Fatal error signal 8" + elif [ $LAST_COMMAND == 137 ]; then + PS1+="Fatal error signal 9" + elif [ $LAST_COMMAND -gt 255 ]; then + PS1+="Exit status out of range" + else + PS1+="Unknown error code" + fi + PS1+="\[${DARKGRAY}\])\[${NOCOLOR}\]\n" + else + PS1="" + fi + + # Date + PS1+="\[${DARKGRAY}\](\[${CYAN}\]\$(date +%a) $(date +%b-'%-m')" # Date + PS1+="${BLUE} $(date +'%-I':%M:%S%P)\[${DARKGRAY}\])-" # Time + + # CPU + PS1+="(\[${MAGENTA}\]CPU $(cpu)%" + + # Jobs + PS1+="\[${DARKGRAY}\]:\[${MAGENTA}\]\j" + + # Network Connections (for a server - comment out for non-server) + PS1+="\[${DARKGRAY}\]:\[${MAGENTA}\]Net $(awk 'END {print NR}' /proc/net/tcp)" + + PS1+="\[${DARKGRAY}\])-" + + # User and server + local SSH_IP=$(echo $SSH_CLIENT | awk '{ print $1 }') + local SSH2_IP=$(echo $SSH2_CLIENT | awk '{ print $1 }') + if [ $SSH2_IP ] || [ $SSH_IP ]; then + PS1+="(\[${RED}\]\u@\h" + else + PS1+="(\[${RED}\]\u" + fi + + # Current directory + PS1+="\[${DARKGRAY}\]:\[${BROWN}\]\w\[${DARKGRAY}\])-" + + # Total size of files in current directory + PS1+="(\[${GREEN}\]$(/bin/ls -lah | /bin/grep -m 1 total | /bin/sed 's/total //')\[${DARKGRAY}\]:" + + # Number of files + PS1+="\[${GREEN}\]\$(/bin/ls -A -1 | /usr/bin/wc -l)\[${DARKGRAY}\])" + + # Skip to the next line + PS1+="\n" + + if [[ $EUID -ne 0 ]]; then + PS1+="\[${GREEN}\]>\[${NOCOLOR}\] " # Normal user + else + PS1+="\[${RED}\]>\[${NOCOLOR}\] " # Root user + fi + + # PS2 is used to continue a command using the \ character + PS2="\[${DARKGRAY}\]>\[${NOCOLOR}\] " + + # PS3 is used to enter a number choice in a script + PS3='Please enter a number from above list: ' + + # PS4 is used for tracing a script in debug mode + PS4='\[${DARKGRAY}\]+\[${NOCOLOR}\] ' +} +# PROMPT_COMMAND='__setprompt' +PS1="\[\e[1m\]\[\e[31m\][\[\e[33m\]\u\[\e[32m\]@\[\e[34m\]\h \[\e[35m\]\W\[\e[31m\]]\[\e[37m\]\\$ \[\e[0m\]" + +####################################################### +# KEY BINDING +####################################################### + +bind '"\C-l":clear-screen' +bind '"\C-g":"lfcd\n"' + +####################################################### +# SOURCE +####################################################### + +eval "$(dircolors)" + +[ -f "${XDG_SCRIPTS_HOME:-${HOME}/.local/bin}/bash-preexec" ] && . "${XDG_SCRIPTS_HOME:-${HOME}/.local/bin}/bash-preexec" +[ -f "${XDG_CONFIG_HOME:-${HOME}/.config}/shell/rootshortcutrc" ] && . "${XDG_CONFIG_HOME:-${HOME}/.config}/shell/rootshortcutrc" +[ -f "${XDG_CONFIG_HOME:-${HOME}/.config}/shell/rootzshnameddirrc" ] && . "${XDG_CONFIG_HOME:-${HOME}/.config}/shell/rootzshnameddirrc" diff --git a/fedora/.config/bash/git.bash b/fedora/.config/bash/git.bash new file mode 100644 index 0000000..8fe7382 --- /dev/null +++ b/fedora/.config/bash/git.bash @@ -0,0 +1,7 @@ +#!/bin/bash + +# Speed up git completion +# http://talkings.org/post/5236392664/zsh-and-slow-git-completion +__git_files() { + _wanted files expl 'local files' _files +} diff --git a/fedora/.config/bash/keymaps.bash b/fedora/.config/bash/keymaps.bash new file mode 100644 index 0000000..cf355ad --- /dev/null +++ b/fedora/.config/bash/keymaps.bash @@ -0,0 +1,200 @@ +#!/bin/bash + +# --------- Bash port (u-prefix removed) --------- +# Put this into ~/.bashrc and run: source ~/.bashrc + +# enable vi editing mode +set -o vi + +# Try to set beam cursor at prompt (best-effort) +PROMPT_COMMAND='echo -ne "\e[5 q"' + +# ---------- helper: pre_cmd ---------- +pre_cmd() { + local txt="$1" + if [[ -z "${READLINE_LINE+set}" ]]; then + printf '%s ' "$txt" + return + fi + local left=${READLINE_LINE:0:READLINE_POINT} + local right=${READLINE_LINE:READLINE_POINT} + READLINE_LINE="${left}${txt} ${right}" + READLINE_POINT=$(( READLINE_POINT + ${#txt} + 1 )) +} + +# ---------- Clipboard detection ---------- +_detect_clipboard_setup() { + if command -v pbcopy >/dev/null 2>&1 && command -v pbpaste >/dev/null 2>&1; then + clipcopy() { cat "${1:-/dev/stdin}" | pbcopy; } + clippaste() { pbaste; } + return 0 + fi + if command -v wl-copy >/dev/null 2>&1 && command -v wl-paste >/dev/null 2>&1; then + clipcopy() { cat "${1:-/dev/stdin}" | wl-copy; } + clippaste() { wl-paste --no-newline; } + return 0 + fi + if command -v xclip >/dev/null 2>&1; then + clipcopy() { cat "${1:-/dev/stdin}" | xclip -selection clipboard; } + clippaste() { xclip -selection clipboard -out; } + return 0 + fi + if command -v xsel >/dev/null 2>&1; then + clipcopy() { cat "${1:-/dev/stdin}" | xsel --clipboard --input; } + clippaste() { xsel --clipboard --output; } + return 0 + fi + if command -v clip.exe >/dev/null 2>&1; then + clipcopy() { cat "${1:-/dev/stdin}" | clip.exe; } + clippaste() { powershell.exe -noprofile -command Get-Clipboard 2>/dev/null; } + return 0 + fi + if command -v tmux >/dev/null 2>&1 && [ -n "${TMUX:-}" ]; then + clipcopy() { tmux load-buffer -; } + clippaste() { tmux save-buffer -; } + return 0 + fi + return 1 +} +_detect_clipboard_setup || true + +paste_clipboard_to_readline() { + if ! command -v clippaste >/dev/null 2>&1; then + _detect_clipboard_setup || { printf 'No clipboard helper found\n' >&2; return 1; } + fi + local clip + clip=$(clippaste 2>/dev/null) || return 1 + clip="${clip%$'\n'}" + if [[ -z "${READLINE_LINE+set}" ]]; then + printf '%s' "$clip" + return + fi + local left=${READLINE_LINE:0:READLINE_POINT} + local right=${READLINE_LINE:READLINE_POINT} + READLINE_LINE="${left}${clip}${right}" + READLINE_POINT=$(( READLINE_POINT + ${#clip} )) +} + +copy_readline_to_clipboard() { + if [[ -z "${READLINE_LINE+set}" ]]; then + printf 'No current line to copy\n' >&2 + return 1 + fi + if ! command -v clipcopy >/dev/null 2>&1; then + _detect_clipboard_setup || { printf 'No clipboard helper found\n' >&2; return 1; } + fi + printf '%s' "${READLINE_LINE}" | clipcopy +} + +# ---------- basic utilities ---------- +clear_tree_2() { clear; tree -L 2 2>/dev/null || true; } +clear_tree_3() { clear; tree -L 3 2>/dev/null || true; } +insert_current_date() { + local txt="$(date -I)" + if [[ -z "${READLINE_LINE+set}" ]]; then printf '%s' "$txt"; return; fi + local left=${READLINE_LINE:0:READLINE_POINT}; local right=${READLINE_LINE:READLINE_POINT} + READLINE_LINE="${left}${txt}${right}"; READLINE_POINT=$(( READLINE_POINT + ${#txt} )) +} +insert_unix_timestamp() { + local txt="$(date +%s)" + if [[ -z "${READLINE_LINE+set}" ]]; then printf '%s' "$txt"; return; fi + local left=${READLINE_LINE:0:READLINE_POINT}; local right=${READLINE_LINE:READLINE_POINT} + READLINE_LINE="${left}${txt}${right}"; READLINE_POINT=$(( READLINE_POINT + ${#txt} )) +} +git_status_clear() { clear; git status 2>/dev/null || git status --short 2>/dev/null || true; } +tmux_left_pane() { tmux select-pane -L 2>/dev/null || true; tmux resize-pane -Z 2>/dev/null || true; } +vi_append_clip_selection() { paste_clipboard_to_readline; } +copybuffer() { copy_readline_to_clipboard; } +background_start() { local cmd="$1"; shift || return 0; for arg in "$@"; do "$cmd" "$arg" &>/dev/null & done; } + +# ---------- pre_cmd widgets ---------- +man_command_line() { pre_cmd "man"; } +sudo_command_line() { pre_cmd "sudo"; } + +# ---------- wrappers (u-prefix REMOVED) ---------- +bc() { command -v bc >/dev/null 2>&1 && /usr/bin/env bc "$@" || printf 'bc: not found\n' >&2; } +cdi() { command -v cdi >/dev/null 2>&1 && cdi "$@" || printf 'cdi: not found\n' >&2; } +lastvim() { command -v lastnvim >/dev/null 2>&1 && lastvim "$@" || printf 'lastvim: not found\n' >&2; } +htop() { command -v htop >/dev/null 2>&1 && htop "$@" || printf 'htop: not found\n' >&2; } +sessionizer() { command -v sessionizer >/dev/null 2>&1 && sessionizer "$@" || printf 'sessionizer: not found\n' >&2; } +upd() { command -v upd >/dev/null 2>&1 && upd "$@" || printf 'upd: not found\n' >&2; } +cht() { command -v cht >/dev/null 2>&1 && cht "$@" || printf 'cht: not found\n' >&2; } # from '^ucht' -> 'cht' +ali() { command -v ali >/dev/null 2>&1 && ali "$@" || printf 'ali: not found\n' >&2; } +fD() { command -v fD >/dev/null 2>&1 && fD "$@" || printf 'fD: not found\n' >&2; } +rgafiles() { command -v rgafiles >/dev/null 2>&1 && rgafiles "$@" || printf 'rgafiles: not found\n' >&2; } +lastvim_l() { command -v lastnvim >/dev/null 2>&1 && lastvim -l || printf 'lastvim: not found\n' >&2; } + +# ---------- Readline key bindings (bind -x) ---------- +# basic movement +bind '"\C-a": beginning-of-line' +bind '"\C-e": end-of-line' + +# function key bindings (map to bash functions above) +bind -x '"\C-x\C-e":clear_tree_2' +bind -x '"\C-x\C-w":clear_tree_3' +bind -x '"\C-x\C-s":git_status_clear' +bind -x '"\C-x\C-x\C-t":insert_current_date' # ^X^X^T (alternate: C-x C-t) +bind -x '"\C-x\C-t":insert_current_date' +bind -x '"\C-x\C-x\C-u":insert_unix_timestamp' # ^X^X^U +bind -x '"\C-x\C-u":insert_unix_timestamp' + +# clipboard binds +bind -x '"\C-x\C-p":paste_clipboard_to_readline' # ^X^P +bind -x '"\C-x\C-y":copy_readline_to_clipboard' # ^X^Y + +# edit in editor +edit_command_line() { + local tmp content + tmp=$(mktemp /tmp/bash-edit.XXXXXX) || return + printf '%s' "${READLINE_LINE:-}" > "$tmp" + "${EDITOR:-vim}" "$tmp" + content=$(<"$tmp") + READLINE_LINE="$content" + READLINE_POINT=${#content} + rm -f "$tmp" +} +bind -x '"\C-x\C-v":edit_command_line' # ^X^V + +# man & sudo insertion +bind -x '"\C-x\C-m":man_command_line' # ^X^M +stty -ixon 2>/dev/null || true +bind -x '"\C-s":sudo_command_line' # ^S (stty -ixon to avoid flow control) + +# tmux left pane (bind ESC + backslash) +bind -x $'\e\\':tmux_left_pane + +# ---------- mappings of the original bindkey -s lines (u removed) ---------- +bind -x '"\C-b":__bc' # will call function __bc below +__bc() { bc -lq "$@"; } + +bind -x '"\C-d":cdi' +bind -x '"\C-f":fzffiles' +bind -x '"\C-g":lf' +bind -x '"\C-n":lastnvim' +bind -x '"\C-o":tmo' +bind -x '"\C-p":fzfpass' +bind -x '"\C-q":htop' +bind -x '"\C-t":sessionizer' +bind -x '"\C-y":lfcd' +bind -x '"\C-z":upd' +# ^_ (Ctrl-_) mapped to cht (from '^ucht' -> 'cht') +bind -x $'"\C-_":cht' + +# ^X^... sequences (Ctrl-X then key) +bind -x '"\C-x\C-a":ali' +bind -x '"\C-x\C-b":gitopenbranch' +bind -x '"\C-x\C-d":fD' +bind -x '"\C-x\C-f":gitfiles' +bind -x '"\C-x\C-g":rgafiles' +bind -x '"\C-x\C-l":gloac' +bind -x '"\C-x\C-n":lastnvim_l' +bind -x '"\C-x\C-q":fpkill' +bind -x '"\C-x\C-r":fgst' +bind -x '"\C-x\C-t":gitstagedfiles' +bind -x '"\C-x\C-u":gitupdate' +bind -x '"\C-x\C-_":fzffns' # ^X^_ +bind -x '"\C-x\C-x\C-b":rbackup' +bind -x '"\C-x\C-x\C-p":pcyr' +bind -x '"\C-x\C-x\C-r":rbackup' # rbackup -r not directly supported via bind -x args; call rbackup then ask user for flags if needed +bind -x '"\C-x\C-x\C-s":sshadd' +bind -x '"\C-x\C-x\C-y":yay_remaps' diff --git a/fedora/.config/bash/packages.bash b/fedora/.config/bash/packages.bash new file mode 100644 index 0000000..f45925a --- /dev/null +++ b/fedora/.config/bash/packages.bash @@ -0,0 +1,35 @@ +#!/bin/bash + +# --- Packages (bash version) --- +declare -A packages=( + [zoxide]="--cmd cd --hook prompt" +) + +eval_packages() { + local package output + for package in "${!packages[@]}"; do + if command -v "$package" >/dev/null 2>&1; then + # split args by space into array (preserve empty => zero args) + local -a args=() + if [[ -n "${packages[$package]}" ]]; then + # Use builtin read to split on spaces (simple split) + IFS=' ' read -r -a args <<<"${packages[$package]}" + fi + + # Prefer initializing for bash (change to "zsh" if you really want zsh-init) + if ((${#args[@]})); then + output="$("$package" init bash "${args[@]}" 2>/dev/null)" + else + output="$("$package" init bash 2>/dev/null)" + fi + + # If the command produced output, evaluate it in current shell + if [[ -n "$output" ]]; then + eval "$output" + fi + fi + done +} + +# run initialization +eval_packages diff --git a/fedora/.config/bash/scripts.bash b/fedora/.config/bash/scripts.bash new file mode 100644 index 0000000..fa0abbc --- /dev/null +++ b/fedora/.config/bash/scripts.bash @@ -0,0 +1,342 @@ +#!/bin/bash + +# Use the best version of pico installed +edit() { + if [ "$(type -t jpico)" = "file" ]; then + # Use JOE text editor http://joe-editor.sourceforge.net/ + jpico -nonotice -linums -nobackups "$@" + elif [ "$(type -t nano)" = "file" ]; then + nano -c "$@" + elif [ "$(type -t pico)" = "file" ]; then + pico "$@" + else + vim "$@" + fi +} + +sedit() { + if [ "$(type -t jpico)" = "file" ]; then + # Use JOE text editor http://joe-editor.sourceforge.net/ + sudo jpico -nonotice -linums -nobackups "$@" + elif [ "$(type -t nano)" = "file" ]; then + sudo nano -c "$@" + elif [ "$(type -t pico)" = "file" ]; then + sudo pico "$@" + else + sudo vim "$@" + fi +} + +# Extracts any archive(s) (if unp isn't installed) +extract() { + for archive in $*; do + if [ -f $archive ]; then + case $archive in + *.tar.bz2) tar xvjf $archive ;; + *.tar.gz) tar xvzf $archive ;; + *.bz2) bunzip2 $archive ;; + *.rar) rar x $archive ;; + *.gz) gunzip $archive ;; + *.tar) tar xvf $archive ;; + *.tbz2) tar xvjf $archive ;; + *.tgz) tar xvzf $archive ;; + *.zip) unzip $archive ;; + *.Z) uncompress $archive ;; + *.7z) 7z x $archive ;; + *) echo "don't know how to extract '$archive'..." ;; + esac + else + echo "'$archive' is not a valid file!" + fi + done +} + +# Searches for text in all files in the current folder +ftext() { + # -i case-insensitive + # -I ignore binary files + # -H causes filename to be printed + # -r recursive search + # -n causes line number to be printed + # optional: -F treat search term as a literal, not a regular expression + # optional: -l only print filenames and not the matching lines ex. grep -irl "$1" * + grep -iIHrn --color=always "$1" . | less -r +} + +# Copy file with a progress bar +cpf() { + set -e + strace -q -ewrite cp -- "${1}" "${2}" 2>&1 | + awk '{ + count += $NF + if (count % 10 == 0) { + percent = count / total_size * 100 + printf "%3d%% [", percent + for (i=0;i<=percent;i++) + printf "=" + printf ">" + for (i=percent;i<100;i++) + printf " " + printf "]\r" + } + } + END { print "" }' total_size=$(stat -c '%s' "${1}") count=0 +} + +# Copy and go to the directory +cpg() { + if [ -d "$2" ]; then + cp $1 $2 && cd $2 + else + cp $1 $2 + fi +} + +# Move and go to the directory +mvg() { + if [ -d "$2" ]; then + mv $1 $2 && cd $2 + else + mv $1 $2 + fi +} + +# Create and go to the directory +mc() { + mkdir -p $1 && cd $1 +} + +# Goes up a specified number of directories (i.e. up 4) +up() { + local d="" + limit=$1 + for ((i = 1; i <= limit; i++)); do + d=$d/.. + done + d=$(echo $d | sed 's/^\///') + if [ -z "$d" ]; then + d=.. + fi + cd $d +} + +#Automatically do an ls after each cd +# cd () { +# if [ -n "$1" ]; then +# builtin cd "$@" && ls +# else +# builtin cd ~ && ls +# fi +# } + +# Returns the last 2 fields of the working directory +pwdtail() { + pwd | awk -F/ '{nlast = NF -1;print $nlast"/"$NF}' +} + +# Show the current distribution +distribution() { + local dtype + # Assume unknown + dtype="unknown" + + # First test against Fedora / RHEL / CentOS / generic Redhat derivative + if [ -r /etc/rc.d/init.d/functions ]; then + source /etc/rc.d/init.d/functions + [ zz$(type -t passed 2>/dev/null) == "zzfunction" ] && dtype="redhat" + + # Then test against SUSE (must be after Redhat, + # I've seen rc.status on Ubuntu I think? TODO: Recheck that) + elif [ -r /etc/rc.status ]; then + source /etc/rc.status + [ zz$(type -t rc_reset 2>/dev/null) == "zzfunction" ] && dtype="suse" + + # Then test against Debian, Ubuntu and friends + elif [ -r /lib/lsb/init-functions ]; then + source /lib/lsb/init-functions + [ zz$(type -t log_begin_msg 2>/dev/null) == "zzfunction" ] && dtype="debian" + + # Then test against Gentoo + elif [ -r /etc/init.d/functions.sh ]; then + source /etc/init.d/functions.sh + [ zz$(type -t ebegin 2>/dev/null) == "zzfunction" ] && dtype="gentoo" + + # For Mandriva we currently just test if /etc/mandriva-release exists + # and isn't empty (TODO: Find a better way :) + elif [ -s /etc/mandriva-release ]; then + dtype="mandriva" + + # For Slackware we currently just test if /etc/slackware-version exists + elif [ -s /etc/slackware-version ]; then + dtype="slackware" + + fi + echo $dtype +} + +# Show the current version of the operating system +ver() { + local dtype + dtype=$(distribution) + + if [ $dtype == "redhat" ]; then + if [ -s /etc/redhat-release ]; then + cat /etc/redhat-release && uname -a + else + cat /etc/issue && uname -a + fi + elif [ $dtype == "suse" ]; then + cat /etc/SuSE-release + elif [ $dtype == "debian" ]; then + lsb_release -a + # sudo cat /etc/issue && sudo cat /etc/issue.net && sudo cat /etc/lsb_release && sudo cat /etc/os-release # Linux Mint option 2 + elif [ $dtype == "gentoo" ]; then + cat /etc/gentoo-release + elif [ $dtype == "mandriva" ]; then + cat /etc/mandriva-release + elif [ $dtype == "slackware" ]; then + cat /etc/slackware-version + else + if [ -s /etc/issue ]; then + cat /etc/issue + else + echo "Error: Unknown distribution" + exit 1 + fi + fi +} + +# Automatically install the needed support files for this .bashrc file +install_bashrc_support() { + local dtype + dtype=$(distribution) + + if [ $dtype == "redhat" ]; then + sudo yum install multitail tree joe + elif [ $dtype == "suse" ]; then + sudo zypper install multitail + sudo zypper install tree + sudo zypper install joe + elif [ $dtype == "debian" ]; then + sudo apt-get install multitail tree joe + elif [ $dtype == "gentoo" ]; then + sudo emerge multitail + sudo emerge tree + sudo emerge joe + elif [ $dtype == "mandriva" ]; then + sudo urpmi multitail + sudo urpmi tree + sudo urpmi joe + elif [ $dtype == "slackware" ]; then + echo "No install support for Slackware" + else + echo "Unknown distribution" + fi +} + +# Show current network information +netinfo() { + echo "--------------- Network Information ---------------" + /sbin/ifconfig | awk /'inet addr/ {print $2}' + echo "" + /sbin/ifconfig | awk /'Bcast/ {print $3}' + echo "" + /sbin/ifconfig | awk /'inet addr/ {print $4}' + + /sbin/ifconfig | awk /'HWaddr/ {print $4,$5}' + echo "---------------------------------------------------" +} + +# IP address lookup +alias whatismyip="whatsmyip" +function whatsmyip() { + # Dumps a list of all IP addresses for every device + # /sbin/ifconfig |grep -B1 "inet addr" |awk '{ if ( $1 == "inet" ) { print $2 } else if ( $2 == "Link" ) { printf "%s:" ,$1 } }' |awk -F: '{ print $1 ": " $3 }'; + + # Internal IP Lookup + echo -n "Internal IP: " + /sbin/ifconfig eth0 | grep "inet addr" | awk -F: '{print $2}' | awk '{print $1}' + + # External IP Lookup + echo -n "External IP: " + wget http://smart-ip.net/myip -O - -q +} + +# View Apache logs +apachelog() { + if [ -f /etc/httpd/conf/httpd.conf ]; then + cd /var/log/httpd && ls -xAh && multitail --no-repeat -c -s 2 /var/log/httpd/*_log + else + cd /var/log/apache2 && ls -xAh && multitail --no-repeat -c -s 2 /var/log/apache2/*.log + fi +} + +# Edit the Apache configuration +apacheconfig() { + if [ -f /etc/httpd/conf/httpd.conf ]; then + sedit /etc/httpd/conf/httpd.conf + elif [ -f /etc/apache2/apache2.conf ]; then + sedit /etc/apache2/apache2.conf + else + echo "Error: Apache config file could not be found." + echo "Searching for possible locations:" + sudo updatedb && locate httpd.conf && locate apache2.conf + fi +} + +# Edit the PHP configuration file +phpconfig() { + if [ -f /etc/php.ini ]; then + sedit /etc/php.ini + elif [ -f /etc/php/php.ini ]; then + sedit /etc/php/php.ini + elif [ -f /etc/php5/php.ini ]; then + sedit /etc/php5/php.ini + elif [ -f /usr/bin/php5/bin/php.ini ]; then + sedit /usr/bin/php5/bin/php.ini + elif [ -f /etc/php5/apache2/php.ini ]; then + sedit /etc/php5/apache2/php.ini + else + echo "Error: php.ini file could not be found." + echo "Searching for possible locations:" + sudo updatedb && locate php.ini + fi +} + +# Edit the MySQL configuration file +mysqlconfig() { + if [ -f /etc/my.cnf ]; then + sedit /etc/my.cnf + elif [ -f /etc/mysql/my.cnf ]; then + sedit /etc/mysql/my.cnf + elif [ -f /usr/local/etc/my.cnf ]; then + sedit /usr/local/etc/my.cnf + elif [ -f /usr/bin/mysql/my.cnf ]; then + sedit /usr/bin/mysql/my.cnf + elif [ -f ~/my.cnf ]; then + sedit ~/my.cnf + elif [ -f ~/.my.cnf ]; then + sedit ~/.my.cnf + else + echo "Error: my.cnf file could not be found." + echo "Searching for possible locations:" + sudo updatedb && locate my.cnf + fi +} + +# For some reason, rot13 pops up everywhere +rot13() { + if [ $# -eq 0 ]; then + tr '[a-m][n-z][A-M][N-Z]' '[n-z][a-m][N-Z][A-M]' + else + echo $* | tr '[a-m][n-z][A-M][N-Z]' '[n-z][a-m][N-Z][A-M]' + fi +} + +# Trim leading and trailing spaces (for scripts) +trim() { + local var=$@ + var='${var#"${var%%[![:space:]]*}"}' # remove leading whitespace characters + var='${var%"${var##*[![:space:]]}"}' # remove trailing whitespace characters + echo -n "$var" +} diff --git a/fedora/.config/shell/aliasrc b/fedora/.config/shell/aliasrc new file mode 100644 index 0000000..6b35701 --- /dev/null +++ b/fedora/.config/shell/aliasrc @@ -0,0 +1,386 @@ +# alias - normal aliases (completed with trailing space) +# balias - blank aliases (completed without space) +# ialias - ignored aliases (not completed) + +# sudo not required for some system commands +for command in blkid lsblk mount umount dnf poweroff reboot shutdown su updatedb; do + alias $command="sudo $command" +done +unset command + +case "$(readlink -f /sbin/init)" in +*systemd*) + # journal + alias -g jctl='journalctl -xe' + alias -g jctlou='sudo journalctl -b -n 200 -f' + alias -g rpi='systemctl --user restart wireplumber pipewire pipewire-pulse pipewire-jack' + alias -g sctl='systemctl' + alias -g sctlss='systemctl status' + alias -g sctle='systemctl enable' + alias -g sctld='systemctl disable' + alias -g sctlr='systemctl restart' + alias -g sctls='systemctl start' + alias -g sctlt='systemctl stop' + alias -g sctldr='systemctl daemon-reload' + alias -g tctl='timedatectl' + ;; +esac + +# Go back +alias ...='../..' +alias ....='../../..' +alias .....='../../../..' + +# bash +alias sbp="source ~/.config/bash/bash_profile" +alias sbs="source ~/.config/bash/bashrc" + +# cd +alias cf='cd "$(dirname "$(readlink -f health.lua)")"' +alias pd='cd -' + +# chmod +alias che='find . -type f -exec chmod +x {};' +alias chfd='find . -type d -exec chmod 755 {}; -o -type f -exec chmod 644 {};' +alias cx='chmod a+x' +alias 000='chmod -R 000' +alias 600='chmod -R 600' +alias 644='chmod -R 644' +alias 666='chmod -R 666' +alias 755='chmod -R 755' +alias 777='chmod -R 777' + +# copy +alias CC='$(fc -l -n -1) | xclip -selection clipboard' +ialias cp='cp -iv' +alias pwdc='pwd | xclip -selection clipboard' + +# count +alias countfiles="for t in files links directories; do echo \`find . -type \${t:0:1} | wc -l\` \$t; done 2> /dev/null" + +# curl +ialias curl='curl --silent --show-error' +balias clh='curl localhost:' +balias clh8='curl localhost:8080' +balias clh9='curl localhost:9080' +balias c100='curl 192.168.99.100:' + +# date +alias da="date '+%Y-%m-%d %A %T %Z'" + +# delete +alias _fd='find . -type f -name "._*" -print0 | xargs -0 rm -f' +alias _fp='find . -type f -name "._*" -print' + +# diff +ialias diff='diff --color' + +# disk +alias diskspace="du -S | sort -n -r |more" +alias folders="du -h --max-depth=1" +alias folderssort="find . -maxdepth 1 -type d -print0 | xargs -0 du -sk | sort -rn" +alias tree="tree -CAhF --dirsfirst" +alias treed="tree -CAFd" +alias mountedinfo="df -hT" + +# docker +alias dk='docker' +alias dkp='docker ps' +alias dkpa='docker ps -a' +alias dkpaq='docker ps -a -q' +alias dkb='docker build -t' +alias dkbnc='docker build --no-cache -t' +alias dkr='docker run --rm' +alias dkrti='docker run --rm -ti' +alias dkrd='docker run -d' +alias dkrp8='docker run --rm -p 8080:8080' +alias dkrp9='docker run --rm -p 9080:9080' +alias dks='docker start' +alias dkt='docker stop' +alias dktt='docker stop $(docker ps -q)' +alias dkk='docker kill' +alias dkkk='docker kill $(docker ps -q)' +alias dkrm='docker rm' +alias dkri='docker rmi' +alias dke='docker exec -ti' +alias dkl='docker logs -f' +alias dki='docker images' +alias dkpu='docker pull' +alias dkph='docker push' +alias dkin='docker inspect' +alias dkn='docker network' +alias dkc='docker-compose' +alias dkcu='docker-compose up' +alias dkclean='docker ps -q -a -f status=exited | xargs -r docker rm && docker images -q -f dangling=true | xargs -r docker rmi' + +# find +balias fdn='find . -name "' +alias f="find . | grep " + +# grep +ialias -g grep='grep --color=auto --exclude-dir={.bzr,CVS,.git,.hg,.svn}' +alias grepi='grep -i' +alias grepr='grep -r' +alias grepri='grep -ri' +alias grepw='grep -R -i --include="*"' +alias grepb='grep -R -i --include="*" --exclude-dir="zsh"' +alias -g Gg='| grep' +alias -g Gi='| grep -i' +alias -g GH='| grep HTTP' + +# hash +alias h='hash -rf' + +# hexdump +alias hx='hexdump -C' + +# history +alias h="history | grep " + +# ip +ialias ip='ip -color=auto' +alias whatsmyip='curl -s ifconfig.me | xargs' +alias ipview="netstat -anpl | grep :80 | awk '{print $5}' | cut -d':' -f1 | sort | uniq -c | sort -n | sed -e 's/^ *//' -e 's/ *$//'" + +# killall +alias ka='killall' +alias k9='kill -9' +alias k15='kill -15' + +# logs +alias logs="sudo find /var/log -type f -exec file {} \; | grep 'text' | cut -d' ' -f1 | sed -e's/:$//g' | grep -v '[0-9]$' | xargs tail -f" + +# ls: eza or built-in +[ -x "$(command -v eza)" ] && { + ialias l='eza --icons --group-directories-first' + ialias la='eza --icons -aa --group-directories-first' + ialias lh='eza --icons -aa --group-directories-first' + ialias ll='eza -gl --icons --group-directories-first' + ialias lla='eza -glaa --icons --group-directories-first' + ialias lm='eza -glA --group-directories-first | more' + ialias lr='eza --icons -R --group-directories-first' + ialias ls='eza --icons -A --group-directories-first' + ialias lsb='eza --icons -b --group-directories-first' + ialias lsby='eza --icons -B --group-directories-first' + ialias lld='eza --icons -Dl --group-directories-first' + ialias llda='eza --icons -aaDl --group-directories-first' + ialias llf='eza --icons -fl' + ialias llfa='eza --icons -aafl' + ialias llsa='eza --icons -l -s=accessed' + ialias llsaa='eza --icons -aal -s=accessed' + ialias llsc='eza --icons -l -s=created' + ialias llsca='eza --icons -aal -s=created' + ialias llse='eza --icons -l -s=extension' + ialias llsea='eza --icons -aal -s=extension' + ialias llsm='eza --icons -l -s=modified' + ialias llsma='eza --icons -aal -s=modified' + ialias llsn='eza --icons -l -s=name' + ialias llsna='eza --icons -aal -s=name' + ialias llss='eza --icons -l -s=size' + ialias llssa='eza --icons -aal -s=size' + ialias llst='eza --icons -l -s=type' + ialias llsta='eza --icons -aal -s=type' + ialias lt='eza --icons -T -L' + ialias ltd='eza --icons -TD -L' + ialias ltdr='eza --icons -TDr -L' + ialias ltr='eza --icons -Tr -L' +} || { + ialias l='/usr/bin/ls -h --color=always --group-directories-first' + ialias la='/usr/bin/ls -alh --color=always --group-directories-first' + ialias ll='/usr/bin/ls -lh --color=always --group-directories-first' + ialias lla='/usr/bin/ls -aFls --color=always --group-directories-first' + ialias llf='/usr/bin/ls -Fls --color=always --group-directories-first' + ialias lm='/usr/bin/ls -alh --color=always --group-directories-first | more' + ialias lr='/usr/bin/ls -hlR --color=always --group-directories-first' + ialias lra='/usr/bin/ls -ahlR --color=always --group-directories-first' + ialias ls='/usr/bin/ls -AFh --color=always --group-directories-first' + ialias llsa='/usr/bin/ls -hlru --color=always --group-directories-first' + ialias llsc='/usr/bin/ls -hclr --color=always --group-directories-first' + ialias lld='/usr/bin/ls -l --color=always | grep "^d"' + ialias llda='/usr/bin/ls -la --color=always | grep "^d"' + ialias llse='/usr/bin/ls -BhlX --color=always --group-directories-first' + ialias llsf='/usr/bin/ls -l --color=always | grep -v "^d"' + ialias llsfa='/usr/bin/ls -la --color=always | grep -v "^d"' + ialias llsm='/usr/bin/ls -hlr --time=ctime --color=always --group-directories-first' + ialias llsn='/usr/bin/ls -alp --color=always --group-directories-first' + ialias llss='/usr/bin/ls -hlrS --color=always --group-directories-first' + ialias llst='/usr/bin/ls -hlrt --color=always --group-directories-first' + ialias lw='/usr/bin/ls -Ahx --color=always --group-directories-first' +} + +# mime +alias mimereset="update-desktop-database ${XDG_DATA_HOME:-${HOME}/.local/share}/applications" + +# mkdir +ialias mkdir='mkdir -pv' + +# modified commands +alias grep="/usr/bin/grep $GREP_OPTIONS" +alias cp="cp -i" +alias freshclam="sudo freshclam" +alias less="less -R" +alias mkdir="mkdir -p" +alias multitail="multitail --no-repeat -c" +alias mv="mv -i" +alias ping="ping -c 10" +alias ps="ps auxf" +alias rm="rm -iv" +alias svi="sudo vi" +alias v="vim" +alias vi="vim" +alias vis="vim '+set si'" + +# move +ialias mv='mv -iv' + +# nginx +alias ngx="cd /etc/nginx" + +# nvim +alias v='$EDITOR' +alias v.='$EDITOR .' +alias ve='$EDITOR -c enew' +alias nv.='nvim .' +alias nve='nvim -c enew' +alias nts='NVIM_APPNAME=TheSiahxyz nvim' +alias nav='NVIM_APPNAME=AstroNvim nvim' +alias nlu='NVIM_APPNAME=LunarVim nvim' +alias nlv='NVIM_APPNAME=LazyVim nvim' +alias nnc='NVIM_APPNAME=NvChad nvim' +alias snv='sudo nvim' +alias vll='lastnvim -l' +alias vln='$EDITOR -c '\''execute "edit " . v:oldfiles[0] | normal ''0'\' + +# ports +alias openports="netstat -nape --inet" + +# ps +ialias ps='ps auxf' +alias psj='ps aux | grep "[j]ava"' +balias psg='ps auxf | grep' +alias topcpu='/bin/ps -eo pcpu,pid,user,args | sort -k 1 -r | head -10' + +# python +alias py='python3' + +# realpath +alias rp='realpath' + +# remove +ialias rm='rm -vI' + +# rsync +alias rsc='rsync -vrazPlu' +alias rscd='rsync -vrazPlu --delete' +alias rscr='rsync -vrazPlu --remove-source-files' + +# rules +alias rrr='sudo udevadm control --reload-rules' + +# scp +ialias scp='scp -r' + +# sha1 +alias sha1='openssl sha1' + +# shell +alias tobash="sudo chsh $USER -s /bin/bash && 'Now log out.'" +alias tozsh="sudo chsh $USER -s /bin/zsh && 'Now log out.'" +alias tofish="sudo chsh $USER -s /bin/fish && 'Now log out.'" + +# shellcheck +alias shck='shellcheck --color=always' + +# shortcut +alias ref='shortcuts >/dev/null; source ${XDG_CONFIG_HOME:-${HOME}/.config}/shell/shortcutrc; source ${XDG_CONFIG_HOME:-${HOME}/.config}/shell/shortcutenvrc; source ${XDG_CONFIG_HOME:-${HOME}/.config}/shell/zshnameddirrc' + +# sudo +alias su='sudo su -l root' +alias sm='setopt no_nomatch && rm -rf *.rej *.orig >/dev/null 2>&1' +alias smi='setopt no_nomatch && rm -rf *.rej *.orig >/dev/null 2>&1 && unsetopt no_nomatch; sudo make clean install; rm -f config.h' + +# suffix +alias -s {pdf,PDF}='background mupdf' +alias -s {jpg,JPG,png,PNG}='background gpicview' +alias -s {ods,ODS,odt,ODT,odp,ODP,doc,DOC,docx,DOCX,xls,XLS,xlsx,XLSX,xlsm,XLSM,ppt,PPT,pptx,PPTX,csv,CSV}='background libreoffice' +alias -s {html,HTML}='background chromium' +alias -s {mp4,MP4,mov,MOV,mkv,MKV}='background vlc' +alias -s {zip,ZIP,war,WAR}="unzip -l" +alias -s {jar,JAR}="java -jar" +alias -s gz="tar -tf" +alias -s {tgz,TGZ}="tar -tf" + +# tar +alias txf='tar -xf' +alias ttf='tar -tf' +alias mktar="tar -cvf" +alias mkbz2="tar -cvjf" +alias mkgz="tar -cvzf" +alias untar="tar -xvf" +alias unbz2="tar -xvjf" +alias ungz="tar -xvzf" + +# tmux +alias sts='tmux source $XDG_CONFIG_HOME/tmux/tmux.conf' +alias ta='tmux a' +alias tmc='tmuxcreate' +alias tmka='tmux kill-session -a' +alias tmls='tmux ls' +alias tmo='tmuxopen' +alias tmpk='command pkill tmux' +alias tm.='tmux new -s "$(basename $PWD)"' + +# tor +alias torh="cat /var/lib/tor/hidden_service/hostname" + +# trash +alias trd='trash-rm' +alias tre='trash-empty' +alias trl='trash-list' +alias trp='trash-put' +alias trr='trash-restore' + +# tree +ialias tree='tree -a -I ".svn|.git|.hg|.idea"' +alias tree2='tree -L 2' +alias tree3='tree -L 3' + +# unix +alias -g md='mkdir -p' +alias -g wh='which' +alias -g wt='while true; do' +alias -g s1='sleep 1' +alias -g s2='sleep 2' +alias -g s01='sleep 0.1' +alias -g s05='sleep 0.5' +alias -g A1="| awk '{print \$1}'" +alias -g L='| less' +alias -g H='| head' +alias -g H2='| head -n 20' +alias -g X='| xargs -I@' +alias -g C='| xclip -selection clipboard' +alias -g Fj='| jq .' +alias -g Fy='| yq .' +alias -g Fx='| xmllint --format -' +alias -g V='| nvim -' + +# unzip +alias uz='unzip' +alias uzl='unzip -l' + +# vim +alias vi='vim' +alias vi.='vim .' + +# watch +alias w1='watch -n 1' + +# wget +ialias wget --hsts-file="${XDG_CACHE_HOME:-${HOME}/.cache}/wget-hsts" + +# xprog +alias progn='xprop | awk '\''/^WM_CLASS/{sub(/.* = /, "instance:"); sub(/, /, "\nclass:"); print} /^WM_NAME/{sub(/.* = /, "title:"); print}'\''' + +# zsh +alias sps="source ${XDG_CONFIG_HOME:-${HOME}/.config}/shell/profile" +alias szs="source ${XDG_CONFIG_HOME:-${HOME}/.config}/zsh/.zshrc" diff --git a/fedora/.config/shell/bm-dirs b/fedora/.config/shell/bm-dirs new file mode 100644 index 0000000..2afa0b0 --- /dev/null +++ b/fedora/.config/shell/bm-dirs @@ -0,0 +1,37 @@ +# Keys Filename +bb ${XDG_SCRIPTS_HOME:-${HOME}/.local/bin} +btp ${XDG_SCRIPTS_HOME:-${HOME}/.local/bin}/tmux +bz ${XDG_SCRIPTS_HOME:-${HOME}/.local/bin}/zsh +cac ${XDG_CACHE_HOME:-${HOME}/.cache} +cbc ${XDG_CONFIG_HOME:-${HOME}/.config}/bash +cfg ${XDG_CONFIG_HOME:-${HOME}/.config} +cgc ${XDG_CONFIG_HOME:-${HOME}/.config}/git +cnv ${XDG_CONFIG_HOME:-${HOME}/.config}/nvim +csh ${XDG_CONFIG_HOME:-${HOME}/.config}/shell +ctm ${XDG_CONFIG_HOME:-${HOME}/.config}/tmux +cts ${XDG_CONFIG_HOME:-${HOME}/.config}/TheSiahxyz +cvc ${XDG_CONFIG_HOME:-${HOME}/.config}/vim +czc ${XDG_CONFIG_HOME:-${HOME}/.config}/zsh +Esm /etc/samba +gdc ${XDG_DOCUMENTS_DIR:-${HOME}/Documents} +gdk ${XDG_DESKTOP_DIR:-${HOME}/Desktop} +gdn ${XDG_DOWNLOAD_DIR:-${HOME}/Downloads} +gdo ${XDG_DOTFILES_DIR:-${HOME}/.dotfiles} +gmu ${XDG_MUSIC_DIR:-${HOME}/Music} +gpb ${XDG_PUBLICSHARE_DIR:-${HOME}/Public} +gpp ${XDG_PICTURES_DIR:-${HOME}/Pictures} +gpv $HOME/Private +grr ${XDG_PICTURES_DIR:-${HOME}/Pictures}/resources +gss ${XDG_PICTURES_DIR:-${HOME}/Pictures}/screenshots +gvv ${XDG_VIDEOS_DIR:-${HOME}/Videos} +Hme /media/$USER +Hmt /mnt +pae ${PASSWORD_STORE_DIR:-$XDG_DATA_HOME/.password-store}/exported_keys +pah ${PASSWORD_STORE_DIR:-$XDG_DATA_HOME/.password-store}/ssh +pas ${PASSWORD_STORE_DIR:-$XDG_DATA_HOME/.password-store} +shh ${XDG_DATA_HOME:-${HOME}/.local/share}/history +shr ${XDG_DATA_HOME:-${HOME}/.local/share} +shv ${XDG_DATA_HOME:-${HOME}/.local/share}/venvs +sr ${XDG_SOURCES_HOME:-${HOME}/.local/src} +trs ${XDG_DATA_HOME:-${HOME}/.local/share}/Trash/files +tt ${XDG_STATE_HOME:-${HOME}/.local/state} diff --git a/fedora/.config/shell/bm-files b/fedora/.config/shell/bm-files new file mode 100644 index 0000000..0be00a6 --- /dev/null +++ b/fedora/.config/shell/bm-files @@ -0,0 +1,19 @@ +# Keys Filename Description +vbc ${XDG_CONFIG_HOME:-${HOME}/.config}/bash/bashrc # Bash (shell) config +vbd ${XDG_CONFIG_HOME:-${HOME}/.config}/shell/bm-dirs # A list of bookmarked directories similar to this file +vbf ${XDG_CONFIG_HOME:-${HOME}/.config}/shell/bm-files # This file, a list of bookmarked files +vbi ${XDG_CONFIG_HOME:-${HOME}/.config}/shell/inputrc # This file is for gnu readline +vbp ${XDG_CONFIG_HOME:-${HOME}/.config}/bash/bash_profile # Bash profile +vga ${XDG_CONFIG_HOME:-${HOME}/.config}/shell/git-aliasrc # Git aliases +vgc ${XDG_CONFIG_HOME:-${HOME}/.config}/git/config # Git config +vgi ${XDG_CONFIG_HOME:-${HOME}/.config}/git/ignore # Git ignore +Vsm /etc/samba/smb.conf # Samba config +vtm ${XDG_CONFIG_HOME:-${HOME}/.config}/tmux/tmux.conf # Tmux config +vvc ${XDG_CONFIG_HOME:-${HOME}/.config}/vim/vimrc # Vim config +vvi ${XDG_CONFIG_HOME:-${HOME}/.config}/vim/init.vim # Vim init +vvp ${XDG_CONFIG_HOME:-${HOME}/.config}/vim/plugins.vim # Vim plugins +vza ${XDG_CONFIG_HOME:-${HOME}/.config}/shell/aliasrc # Aliases used by zsh (and potentially other shells) +vzc ${ZDOTDIR:-${XDG_CONFIG_HOME:-${HOME}/.config}/zsh}/.zshrc # Zsh config +vzk ${ZDOTDIR:-${XDG_CONFIG_HOME:-${HOME}/.config}/zsh}/keymaps.zsh # Zsh keymaps +vzp ${XDG_CONFIG_HOME:-${HOME}/.config}/shell/profile # Zsh profile used for system +vzs ${ZDOTDIR:-${XDG_CONFIG_HOME:-${HOME}/.config}/zsh}/scripts.zsh # Zsh scripts diff --git a/fedora/.config/shell/git-aliasrc b/fedora/.config/shell/git-aliasrc new file mode 100644 index 0000000..f87a556 --- /dev/null +++ b/fedora/.config/shell/git-aliasrc @@ -0,0 +1,415 @@ +# Git version checking +autoload -Uz is-at-least +git_version="${${(As: :)$(git version 2>/dev/null)}[3]}" + +# +# Functions Current +# (sorted alphabetically by function name) +# (order should follow README) +# + +# The name of the current branch +# Back-compatibility wrapper for when this function was defined here in +# the plugin, before being pulled in to core lib/git.zsh as git_current_branch() +# to fix the core -> git plugin dependency. +current_branch() { + git_current_branch +} + +# Check for develop and similarly named branches +git_develop_branch() { + command git rev-parse --git-dir &>/dev/null || return + local branch + for branch in dev devel develop development; do + if command git show-ref -q --verify refs/heads/$branch; then + echo $branch + return 0 + fi + done + + echo develop + return 1 +} + +# Check if main exists and use instead of master +git_main_branch() { + command git rev-parse --git-dir &>/dev/null || return + local ref + for ref in refs/{heads,remotes/{origin,upstream}}/{main,trunk,mainline,default,master}; do + if command git show-ref -q --verify $ref; then + echo ${ref:t} + return 0 + fi + done + + # If no main branch was found, fall back to master but return error + echo master + return 1 +} + +grename() { + if [[ -z "$1" || -z "$2" ]]; then + echo "Usage: $0 old_branch new_branch" + return 1 + fi + + # Rename branch locally + git branch -m "$1" "$2" + # Rename branch in origin remote + if git push origin :"$1"; then + git push --set-upstream origin "$2" + fi +} + +# +# Functions Work in Progress (WIP) +# (sorted alphabetically by function name) +# (order should follow README) +# + +# Similar to `gunwip` but recursive "Unwips" all recent `--wip--` commits not just the last one +gunwipall() { + local _commit=$(git log --grep='--wip--' --invert-grep --max-count=1 --format=format:%H) + + # Check if a commit without "--wip--" was found and it's not the same as HEAD + if [[ "$_commit" != "$(git rev-parse HEAD)" ]]; then + git reset $_commit || return 1 + fi +} + +# Warn if the current branch is a WIP +work_in_progress() { + command git -c log.showSignature=false log -n 1 2>/dev/null | grep -q -- "--wip--" && echo "WIP!!" +} + +# +# Aliases +# (sorted alphabetically by command) +# (order should follow README) +# (in some cases force the alisas order to match README, like for example gke and gk) +# + +alias grt='cd "$(git rev-parse --show-toplevel || echo .)"' + +ggpnp() { + if [[ "$#" == 0 ]]; then + ggl && ggp + else + ggl "${*}" && ggp "${*}" + fi +} +compdef _git ggpnp=git-checkout + +alias ggpur='ggu' +alias g='git' +! pidof transmission-daemon >/dev/null && alias gaa='git add --all' || alias gaa='echo "Turn off transmission-daemon first!"' +alias gapa='git add --patch' +alias gau='git add --update' +alias gav='git add --verbose' +alias gwip='git add -A; git rm $(git ls-files --deleted) 2> /dev/null; git commit --no-verify --no-gpg-sign --message "--wip-- [skip ci]"' +alias gam='git am' +alias gama='git am --abort' +alias gamc='git am --continue' +alias gamscp='git am --show-current-patch' +alias gams='git am --skip' +alias gap='git apply' +alias gapt='git apply --3way' +alias gbs='git bisect' +alias gbsb='git bisect bad' +alias gbsg='git bisect good' +alias gbsn='git bisect new' +alias gbso='git bisect old' +alias gbsr='git bisect reset' +alias gbss='git bisect start' +alias gb='git branch' +alias gba='git branch --all' +alias gbD='git branch --delete --force' + +gbda() { + git branch --no-color --merged | command grep -vE "^([+*]|\s*($(git_main_branch)|$(git_develop_branch))\s*$)" | command xargs git branch --delete 2>/dev/null +} + +# Copied and modified from James Roeder (jmaroeder) under MIT License +# https://github.com/jmaroeder/plugin-git/blob/216723ef4f9e8dde399661c39c80bdf73f4076c4/functions/gbda.fish +gbds() { + local default_branch=$(git_main_branch) + (( ! $? )) || default_branch=$(git_develop_branch) + + git for-each-ref refs/heads/ "--format=%(refname:short)" | \ + while read branch; do + local merge_base=$(git merge-base $default_branch $branch) + if [[ $(git cherry $default_branch $(git commit-tree $(git rev-parse $branch\^{tree}) -p $merge_base -m _)) = -* ]]; then + git branch -D $branch + fi + done +} + +alias gbgd='LANG=C git branch --no-color -vv | grep ": gone\]" | awk '"'"'{print $1}'"'"' | xargs git branch -d' +alias gbgD='LANG=C git branch --no-color -vv | grep ": gone\]" | awk '"'"'{print $1}'"'"' | xargs git branch -D' +alias gbm='git branch --move' +alias gbnm='git branch --no-merged' +alias gbr='git branch --remote' +alias ggsup='git branch --set-upstream-to=origin/$(git_current_branch)' +alias gbg='LANG=C git branch -vv | grep ": gone\]"' +alias gcor='git checkout --recurse-submodules' +alias gcB='git checkout -B' +alias gcd='git checkout $(git_develop_branch)' +alias gcm='git checkout $(git_main_branch)' +alias gcpa='git cherry-pick --abort' +alias gcpc='git cherry-pick --continue' +alias gcl='git clone --recurse-submodules' + +gccd() { + setopt localoptions extendedglob + + # get repo URI from args based on valid formats: https://git-scm.com/docs/git-clone#URLS + local repo='${${@[(r)(ssh://*|git://*|ftp(s)#://*|http(s)#://*|*@*)(.git/#)#]}:-$_}' + + # clone repository and exit if it fails + command git clone --recurse-submodules "$@" || return + + # if last arg passed was a directory, that's where the repo was cloned + # otherwise parse the repo URI and use the last part as the directory + [[ -d "$_" ]] && cd '$_' || cd '${${repo:t}%.git/#}' +} +compdef _git gccd=git-clone + +alias gcam='git commit --all --message' +alias gcas='git commit --all --signoff' +alias gcasm='git commit --all --signoff --message' +alias gcs='git commit --gpg-sign' +alias gcss='git commit --gpg-sign --signoff' +alias gcssm='git commit --gpg-sign --signoff --message' +alias gcmsg='git commit --message' +alias gcsm='git commit --signoff --message' +alias gc='git commit --verbose' +alias gca='git commit --verbose --all' +alias gca!='git commit --verbose --all --amend' +alias gcan!='git commit --verbose --all --no-edit --amend' +alias gcans!='git commit --verbose --all --signoff --no-edit --amend' +alias gc!='git commit --verbose --amend' +alias gcn!='git commit --verbose --no-edit --amend' +alias gdct='git describe --tags $(git rev-list --tags --max-count=1)' +alias gdca='git diff --cached' +alias gdcw='git diff --cached --word-diff' +alias gds='git diff --staged' +alias gdw='git diff --word-diff' + +gdv() { git diff -w "$@" | view - } +compdef _git gdv=git-diff + +alias gdup='git diff @{upstream}' + +gdnolock() { + git diff "$@" ":(exclude)package-lock.json" ":(exclude)*.lock" +} +compdef _git gdnolock=git-diff + +alias gdt='git diff-tree --no-commit-id --name-only -r' +alias gf='git fetch' +# --jobs=<n> was added in git 2.8 +is-at-least 2.8 "$git_version" \ + && alias gfa='git fetch --all --prune --jobs=10' \ + || alias gfa='git fetch --all --prune' +alias gfo='git fetch origin' +alias gg='git gui citool' +alias gga='git gui citool --amend' +alias ghh='git help' +alias glgg='git log --graph' +alias glggp='git log --graph --parents' +alias glgga='git log --graph --decorate --all' +alias glggpa='git log --graph --decorate --parents --all' +alias glgm='git log --graph --max-count=10' +alias glgpm='git log --graph --parents --max-count=10' +alias gloac='git log --graph --pretty=format:"%Cred%h%Creset -%C(yellow)%d%Creset %s %Cgreen(%cr) %C(bold blue)<%ae>%Creset" --abbrev-commit --all' +alias glods='git log --graph --pretty="%Cred%h%Creset -%C(auto)%d%Creset %s %Cgreen(%ad) %C(bold blue)<%an>%Creset" --date=short' +alias glopds='git log --graph --pretty="%Cred%h%Creset -%C(auto)%d%Creset %s %Cgreen(%ad) %C(bold blue)<%an>%Creset" --parents --date=short' +alias glod='git log --graph --pretty="%Cred%h%Creset -%C(auto)%d%Creset %s %Cgreen(%ad) %C(bold blue)<%an>%Creset"' +alias glopd='git log --graph --pretty="%Cred%h%Creset -%C(auto)%d%Creset %s %Cgreen(%ad) %C(bold blue)<%an>%Creset" --parents' +alias glola='git log --graph --pretty="%Cred%h%Creset -%C(auto)%d%Creset %s %Cgreen(%ar) %C(bold blue)<%an>%Creset" --all' +alias glolpa='git log --graph --pretty="%Cred%h%Creset -%C(auto)%d%Creset %s %Cgreen(%ar) %C(bold blue)<%an>%Creset" --parents --all' +alias glols='git log --graph --pretty="%Cred%h%Creset -%C(auto)%d%Creset %s %Cgreen(%ar) %C(bold blue)<%an>%Creset" --stat' +alias glolps='git log --graph --pretty="%Cred%h%Creset -%C(auto)%d%Creset %s %Cgreen(%ar) %C(bold blue)<%an>%Creset" --parents --stat' +alias glol='git log --graph --pretty="%Cred%h%Creset -%C(auto)%d%Creset %s %Cgreen(%ar) %C(bold blue)<%an>%Creset"' +alias glolp='git log --graph --pretty="%Cred%h%Creset -%C(auto)%d%Creset %s %Cgreen(%ar) %C(bold blue)<%an>%Creset" --parents' +alias glog='git log --oneline --decorate --graph' +alias glogp='git log --oneline --decorate --graph --parents' +alias gloga='git log --oneline --decorate --graph --all' +alias glogpa='git log --oneline --decorate --graph --parents --all' + +# Pretty log messages +_git_log_prettily(){ + if ! [ -z $1 ]; then + git log --pretty=$1 + fi +} +compdef _git _git_log_prettily=git-log + +alias glp='_git_log_prettily' +alias glg='git log --stat' +alias glgp='git log --stat --patch' +alias gignored='git ls-files -v | grep "^[[:lower:]]"' +alias gfg='git ls-files | grep' +alias gm='git merge' +alias gma='git merge --abort' +alias gms="git merge --squash" +alias gmom='git merge origin/$(git_main_branch)' +alias gmum='git merge upstream/$(git_main_branch)' +alias gmtl='git mergetool --no-prompt' +alias gmtlvim='git mergetool --no-prompt --tool=vimdiff' + +alias gl='git pull' +alias gprb='git pull --rebase' +alias gprbv='git pull --rebase -v' +alias gpra='git pull --rebase --autostash' +alias gprav='git pull --rebase --autostash -v' + +ggu() { + [[ "$#" != 1 ]] && local b="$(git_current_branch)" + git pull --rebase origin "${b:=$1}" +} +compdef _git ggu=git-checkout + +alias gprom='git pull --rebase origin $(git_main_branch)' +alias gpromi='git pull --rebase=interactive origin $(git_main_branch)' +alias ggpull='git pull origin "$(git_current_branch)"' + +ggl() { + if [[ "$#" != 0 ]] && [[ "$#" != 1 ]]; then + git pull origin "${*}" + else + [[ "$#" == 0 ]] && local b="$(git_current_branch)" + git pull origin "${b:=$1}" + fi +} +compdef _git ggl=git-checkout + +alias gluc='git pull upstream $(git_current_branch)' +alias glum='git pull upstream $(git_main_branch)' +# alias gp='git push' +alias gpd='git push --dry-run' + +ggf() { + [[ "$#" != 1 ]] && local b="$(git_current_branch)" + git push --force origin "${b:=$1}" +} +compdef _git ggf=git-checkout + +alias gpf!='git push --force' +is-at-least 2.30 "$git_version" \ + && alias gpf='git push --force-with-lease --force-if-includes' \ + || alias gpf='git push --force-with-lease' + +ggfl() { + [[ "$#" != 1 ]] && local b="$(git_current_branch)" + git push --force-with-lease origin "${b:=$1}" +} +compdef _git ggfl=git-checkout + +alias gpsup='git push --set-upstream origin $(git_current_branch)' +is-at-least 2.30 "$git_version" \ + && alias gpsupf='git push --set-upstream origin $(git_current_branch) --force-with-lease --force-if-includes' \ + || alias gpsupf='git push --set-upstream origin $(git_current_branch) --force-with-lease' +alias gpvb='git push --verbose' +alias gpoat='git push origin --all && git push origin --tags' +alias gpod='git push origin --delete' +alias ggpush='git push origin "$(git_current_branch)"' + +ggp() { + if [[ "$#" != 0 ]] && [[ "$#" != 1 ]]; then + git push origin "${*}" + else + [[ "$#" == 0 ]] && local b="$(git_current_branch)" + git push origin "${b:=$1}" + fi +} +compdef _git ggp=git-checkout + +alias gpu='git push upstream' +alias grba='git rebase --abort' +alias grbc='git rebase --continue' +alias grbi='git rebase --interactive' +alias grbo='git rebase --onto' +alias grbs='git rebase --skip' +alias grbd='git rebase $(git_develop_branch)' +alias grbm='git rebase $(git_main_branch)' +alias grbom='git rebase origin/$(git_main_branch)' +alias gr='git remote' +alias grv='git remote --verbose' +alias gra='git remote add' +alias grrm='git remote remove' +alias grmv='git remote rename' +alias grset='git remote set-url' +alias grup='git remote update' +alias gru='git reset --' +alias grhh='git reset --hard' +alias grhk='git reset --keep' +alias grhs='git reset --soft' +alias gpristine='git reset --hard && git clean --force -dfx' +alias groh='git reset origin/$(git_current_branch) --hard' +alias grs='git restore' +alias grss='git restore --source' +alias grst='git restore --staged' +alias gunwip='git rev-list --max-count=1 --format="%s" HEAD | grep -q "\--wip--" && git reset HEAD~1' +alias grev='git revert' +alias grm='git rm' +alias grmc='git rm --cached' +alias gcount='git shortlog --summary --numbered' +alias gsh='git show' +alias gsps='git show --pretty=short --show-signature' +alias gstall='git stash --all' +alias gstaa='git stash apply' +alias gstc='git stash clear' +alias gstd='git stash drop' +alias gstl='git stash list' +alias gstp='git stash pop' +# use the default stash push on git 2.13 and newer +is-at-least 2.13 "$git_version" \ + && alias gsta='git stash push' \ + || alias gsta='git stash save' +alias gsts='git stash show --patch' +alias gst='git status' +alias gsb='git status --short --branch' +alias gsi='git submodule init' +alias gsu='git submodule update' +alias gsd='git svn dcommit' +alias git-svn-dcommit-push='git svn dcommit && git push github $(git_main_branch):svntrunk' +alias gsr='git svn rebase' +alias gsw='git switch' +alias gswc='git switch --create' +alias gswd='git switch $(git_develop_branch)' +alias gswm='git switch $(git_main_branch)' +alias gtan='git tag --annotate' +alias gtsn='git tag --sign' +alias gtv='git tag | sort -V' +alias gignore='git update-index --assume-unchanged' +alias gunignore='git update-index --no-assume-unchanged' +alias gwch='git whatchanged -p --abbrev-commit --pretty=medium' +alias gwt='git worktree' +alias gwta='git worktree add' +alias gwtls='git worktree list' +alias gwtmv='git worktree move' +alias gwtrm='git worktree remove' +alias gstu='gsta --include-untracked' +alias gtl='gtl(){ git tag --sort=-v:refname -n --list "${1}*" }; noglob gtl' +alias gk='\gitk --all --branches &!' +alias gke='\gitk --all $(git log --walk-reflogs --pretty=%h) &!' + +unset git_version + +# Logic for adding warnings on deprecated aliases +local old_alias new_alias +for old_alias new_alias ( + # TODO(2023-10-19): remove deprecated `git pull --rebase` aliases + gup gpr + gupv gprv + gupa gpra + gupav gprav + gupom gprom + gupomi gpromi +); do + aliases[$old_alias]=' + print -Pu2 \"%F{yellow}[oh-my-zsh] '%F{red}${old_alias}%F{yellow}' is a deprecated alias, using '%F{green}${new_alias}%F{yellow}' instead.%f\" + $new_alias' +done +unset old_alias new_alias diff --git a/fedora/.config/shell/inputrc b/fedora/.config/shell/inputrc new file mode 100644 index 0000000..81cdf85 --- /dev/null +++ b/fedora/.config/shell/inputrc @@ -0,0 +1,31 @@ +$include /etc/inputrc + +set completion-display-width 0 +set completion-query-items 1000 + +# Prettyfi +set colored-stats on +set colored-completion-prefix on + +# ^C no longer shows on C-c keypress +set echo-control-characters off + +# Map tab to cycle through all the possible completions. +TAB: menu-complete + +# vi mode +set editing-mode vi + +$if mode=vi +set show-mode-in-prompt on +set vi-ins-mode-string \1\e[6 q\2 +set vi-cmd-mode-string \1\e[2 q\2 +set keymap vi-command + +# these are for vi-command mode +Control-l: clear-screen + +set keymap vi-insert +# these are for vi-insert mode +Control-l: clear-screen +$endif diff --git a/fedora/.config/shell/profile b/fedora/.config/shell/profile new file mode 100644 index 0000000..677943a --- /dev/null +++ b/fedora/.config/shell/profile @@ -0,0 +1,151 @@ +################################################### +### --- PROFILE --- ### +################################################### +[ "$(tty)" = "/dev/tty1" ] && set -e # Exit immediately if a command exits with a non-zero status. + +################################################### +### --- ENV PATH --- ### +################################################### +# Add all directories in each subdirectory to $PATH +export PATH="$PATH:$(find ~/.local/bin -path '*/.git*' -prune -o \( -type f -o -type l \) -perm -u=x -exec dirname {} \; | sort -u | paste -sd ':' -)" +export PATH="$PATH:$(find ~/.local/share/.password-store -type d -name '.extensions' | paste -sd ':' -)" +command -v asdf >/dev/null 2>&1 && export PATH="$PATH:$(find -L ~/.local/share/asdf/installs -name bin -type d -print 2>/dev/null | sort -u | paste -s -d ':' -)" +command -v npm >/dev/null 2>&1 && export PATH="$PATH:$(find -L ~/.local/share/npm -name bin -type d -print 2>/dev/null | sort -u | paste -s -d ':' -)" + +unsetopt PROMPT_SP 2>/dev/null + +################################################### +### --- DEFAULT PROGRAMS --- ### +################################################### +export EDITOR="nvim" +export EDITOR2="vim" +# export FILE_MANAGER="lf $(lf -version)" +export KEYTIMEOUT=10 +export SUDO_EDITOR=$EDITOR +export TERM="xterm-256color" +export VISUAL=$EDITOR + +################################################### +### --- XDG ENV PATHES --- ### +################################################### +### --- XDG DEFAULT --- ### +export XDG_CACHE_HOME="$HOME/.cache" +export XDG_CONFIG_HOME="$HOME/.config" +export XDG_DATA_HOME="$HOME/.local/share" +export XDG_STATE_HOME="$HOME/.local/state" + +### --- XDG CUSTOMS --- ### +export XDG_DOTFILES_DIR="$HOME/.dotfiles" +export XDG_SCRIPTS_HOME="$HOME/.local/bin" +export XDG_SOURCES_HOME="$HOME/.local/src" +export XDG_DESKTOP_DIR="$HOME/Desktop" +export XDG_DOCUMENTS_DIR="$HOME/Documents" +export XDG_DOWNLOAD_DIR="$HOME/Downloads" +export XDG_MUSIC_DIR="$HOME/Music" +export XDG_PICTURES_DIR="$HOME/Pictures" +export XDG_PUBLICSHARE_DIR="$HOME/Public" +export XDG_TEMPLATES_DIR="$HOME/Templates" +export XDG_VIDEOS_DIR="$HOME/Videos" + +################################################### +### --- DEFAULT ENV PATHES FOR ALL PROGRAMS --- ### +################################################### +### --- ANDROID --- ### +export ANDROID_SDK_HOME="$XDG_CONFIG_HOME/android" + +### --- ANSIBLE --- ### +export ANSIBLE_CONFIG="$XDG_CONFIG_HOME/ansible/ansible.cfg" + +### --- BAT --- ### +export BAT_CONFIG_PATH="$XDG_CONFIG_HOME/bat/config" + +### --- CARGO --- ### +export CARGO_HOME="$XDG_DATA_HOME/cargo" + +### --- DICS --- ### +export DICS="/usr/share/stardict/dic/" + +### --- ELECTRUM --- ### +export ELECTRUMDIR="$XDG_DATA_HOME/electrum" + +### --- HISTORY --- ### +export HISTFILE="$XDG_DATA_HOME/history/sh_history" + +### --- INPUTRC --- ### +export INPUTRC="$XDG_CONFIG_HOME/shell/inputrc" + +### --- JAVA --- ### +export AWT_TOOLKIT="MToolkit wmname LG3D" # May have to install wmname +export _JAVA_AWT_WM_NONREPARENTING=1 # Fix for Java applications in dwm + +### --- MANPAGER --- ### +([ -x "$(command -v batcat)" ] || [ -x "$(command -v batman)" ]) && { + export MANPAGER="sh -c 'col -bx | bat -l man -p'" + export MANROFFOPT="-c" +} || { + export MANPAGER='less -s' + export LESS="R" + export LESS_TERMCAP_mb="$(printf '%b' '[1;31m')" + export LESS_TERMCAP_md="$(printf '%b' '[1;36m')" + export LESS_TERMCAP_me="$(printf '%b' '[0m')" + export LESS_TERMCAP_so="$(printf '%b' '[01;44;33m')" + export LESS_TERMCAP_se="$(printf '%b' '[0m')" + export LESS_TERMCAP_us="$(printf '%b' '[1;32m')" + export LESS_TERMCAP_ue="$(printf '%b' '[0m')" + export LESSOPEN="| lesspipe.sh %s" +} + +### --- NPM --- ### +export NPM_CONFIG_USERCONFIG="~/.config/npm/.npmrc" + +### --- NVM --- ### +export NVM_DIR="$XDG_CONFIG_HOME/nvm" + +### --- PASSWORD STORE --- ### +export PASSWORD_STORE_DIR="$XDG_DATA_HOME/.password-store" +export PASSWORD_STORE_CLIP_TIME=180 # Specifies the number of seconds to wait before restoring the clipboard, by default 45 seconds. +# export PASSWORD_STORE_GENERATED_LENGTH=18 # by default 25. +# export PASSWORD_STORE_CHARACTER_SET='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*()-_=+[]{};:,.<>?' +# export PASSWORD_STORE_CHARACTER_SET_NO_SYMBOLS='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*()-_=+[]{};:,.<>?' +export PASSWORD_STORE_ENABLE_EXTENSIONS="true" +# export PASSWORD_STORE_EXTENSIONS_DIR="$PASSWORD_STORE_DIR/.extensions" +# export BASH_COMPLETION_USER_DIR=$XDG_DATA_HOME/bash-completion/completions + +### --- POWERLEVEL10K --- ### +export POWERLEVEL9K_INSTALLATION_DIR="/usr/share/zsh-theme-powerlevel10k" + +### --- PYTHON --- ### +export PYTHONPYCACHEPREFIX=$XDG_CACHE_HOME/python +export PYTHONSTARTUP="$XDG_CONFIG_HOME/python/pythonrc" + +### --- RUST --- ### +export RUSTUP_HOME="$XDG_DATA_HOME/rustup" + +### --- SQLITE --- ### +export SQLITE_HISTORY="$XDG_DATA_HOME/history/sqlite_history" + +### --- TMUX --- ### +export TMUX_TMPDIR="$XDG_RUNTIME_DIR" + +### --- VIM --- ### +# export GVIMINIT='let $MYGVIMRC = !has("nvim") ? "$XDG_CONFIG_HOME/vim/gvimrc" : "$XDG_CONFIG_HOME/nvim/init.lua" | so $MYGVIMRC' +# export VIMINIT='let $MYVIMRC = !has("nvim") ? "$XDG_CONFIG_HOME/vim/vimrc" : "$XDG_CONFIG_HOME/nvim/init.lua" | so $MYVIMRC' + +### --- VIRTUAL ENVIRONMENT --- ### +export WORKON_HOME="$XDG_DATA_HOME/venvs" + +### --- VISUAL STUDIO CODE --- ### +export VSCODE_PORTABLE="$XDG_DATA_HOME/vscode" + +### --- WGET --- ### +export WGETRC="$XDG_CONFIG_HOME/wget/wgetrc" + +### --- ZSH --- ### +export ZDOTDIR="$XDG_CONFIG_HOME/zsh" +export ZPLUGINDIR="$XDG_SCRIPTS_HOME/zsh" + +### --- SHORTCUTS --- ### +[ ! -f "$XDG_CONFIG_HOME/shell/shortcutrc" ] && setsid -f shortcuts >/dev/null 2>&1 + +### --- LAPTOP KEYMAP --- ### +sudo -n loadkeys "$XDG_DATA_HOME/thesiah/ttymaps.kmap" 2>/dev/null diff --git a/fedora/.config/shell/scripts.bash b/fedora/.config/shell/scripts.bash new file mode 100644 index 0000000..f257809 --- /dev/null +++ b/fedora/.config/shell/scripts.bash @@ -0,0 +1,54 @@ +#!/bin/bash + +########################################################################################### +########################################################################################### +### --- COMMAND OUTPUT --- ### +alias ilco=insert_last_command_output +insert_last_command_output() { + local last_cmd + last_cmd=$(history | tail -n 2 | head -n 1 | sed 's/^[ ]*[0-9]\+[ ]*//') + eval "$last_cmd" +} + +########################################################################################### +########################################################################################### +### --- CREATE --- ### +alias mc=mkcd +mkcd() { mkdir -p "$1" && cd "$1" || return; } + +mkdt() { + mkdir -p "${1:+$1/}$(date +%F)" +} + +########################################################################################### +########################################################################################### +### --- PASS --- ### +pass_otp() { pass otp uri -q "$1"; } +pass_otp_insert() { pass otp insert "$1"; } + +alias cpqr=pass_qr +pass_qr() { qrencode -o "$1.png" -t png -Sv 40 < "$1.pgp"; } + +########################################################################################### +########################################################################################### +### --- STOW --- ### +alias dstw=dotfiles_stw +dotfiles_stw() { + "${XDG_DOTFILES_DIR:-${HOME}/.dotfiles}/$(whereami)/.local/bin/stw" +} + +########################################################################################### +########################################################################################### +### --- SUDO --- ### +pre_cmd() { + local prepend_command="$1" + local buffer="${READLINE_LINE:-}" + + if [ -z "$buffer" ]; then + buffer=$(history | tail -n 2 | head -n 1 | sed 's/^[ ]*[0-9]\+[ ]*//') + fi + + READLINE_LINE="$prepend_command $buffer" + READLINE_POINT=${#READLINE_LINE} +} +bind -x '"\es":pre_cmd sudo' diff --git a/fedora/.config/vim/UltiSnips/all.snippets b/fedora/.config/vim/UltiSnips/all.snippets new file mode 100644 index 0000000..cf55536 --- /dev/null +++ b/fedora/.config/vim/UltiSnips/all.snippets @@ -0,0 +1,30 @@ +# place your snippets# symbols +snippet .- "• " w +• +endsnippet + +snippet .v "✓" w +✓ +endsnippet + + +# functions +snippet datek "Date (Korean format)" w +`!v strftime("%Y.%m.%d")` +endsnippet + +snippet datea "Date (American format)" w +`!v strftime("%m.%d.%Y")` +endsnippet + +snippet unix "Unix timestamp" w +`date +%s` +endsnippet + +snippet file "file name" w +`!v expand('%:t')` +endsnippet + +snippet path "absolute file path" w +`!v expand('%:p')` +endsnippet diff --git a/fedora/.config/vim/init.vim b/fedora/.config/vim/init.vim new file mode 100644 index 0000000..fbb9097 --- /dev/null +++ b/fedora/.config/vim/init.vim @@ -0,0 +1,446 @@ +" AUTOCMD ---------------------------------------------------------------- {{{ + +" Close with q +autocmd FileType checkhealth,help,lspinfo,neotest-output,neotest-output-panel,neotest-summary,netrw,notify,qf,query,spectre_panel,startuptime,terminal,tsplayground noremap <buffer> q :bd<CR> + +" Disables automatic commenting on newline: +autocmd FileType * setlocal formatoptions-=c formatoptions-=r formatoptions-=o + +" Nerd tree +autocmd bufenter * if (winnr("$") == 1 && exists("b:NERDTree") && b:NERDTree.isTabTree()) | q | endif + +" Runs a script that cleans out tex build files whenever I close out of a .tex file. +autocmd VimLeave *.tex !texclear % + +" Text files +let g:vimwiki_ext2syntax = {'.Rmd': 'markdown', '.rmd': 'markdown','.md': 'markdown', '.markdown': 'markdown', '.mdown': 'markdown'} +let g:vimwiki_list = [{'path': '~/.local/share/nvim/vimwiki', 'syntax': 'markdown', 'ext': '.md'}] +autocmd BufRead,BufNewFile /tmp/calcurse*,~/.calcurse/notes/* set filetype=markdown +autocmd BufRead,BufNewFile *.ms,*.me,*.mom,*.man set filetype=groff +autocmd BufRead,BufNewFile *.tex set filetype=tex + +" Enable Goyo by default for mutt writing +autocmd BufRead,BufNewFile /tmp/neomutt* :Goyo 80 | call feedkeys("jk") +autocmd BufRead,BufNewFile /tmp/neomutt* map ZZ :Goyo!\|x!<CR> +autocmd BufRead,BufNewFile /tmp/neomutt* map ZQ :Goyo!\|q!<CR> + +" Automatically deletes all trailing whitespace and newlines at end of file on save. & reset cursor position +autocmd BufWritePre * let currPos = getpos(".") +autocmd BufWritePre * %s/\s\+$//e +autocmd BufWritePre * %s/\n\+\%$//e +autocmd BufWritePre *.[ch] %s/\%$/\r/e " add trailing newline for ANSI C standard +autocmd BufWritePre *neomutt* %s/^--$/-- /e " dash-dash-space signature delimiter in emails +autocmd BufWritePre * cal cursor(currPos[1], currPos[2]) + +" When shortcut files are updated, renew bash and ranger configs with new material: +autocmd BufWritePost bm-files,bm-dirs !shortcuts + +" Run xrdb whenever Xdefaults or Xresources are updated. +autocmd BufRead,BufNewFile Xresources,Xdefaults,xresources,xdefaults set filetype=xdefaults +autocmd BufWritePost Xresources,Xdefaults,xresources,xdefaults !xrdb % + +" Recompile dwmblocks on config edit. +autocmd BufWritePost ${XDG_SOURCES_HOME:-$HOME/.local/src}/suckless/dwmblocks/config.h !cd ${XDG_SOURCES_HOME:-$HOME/.local/src}/suckless/dwmblocks/; sudo make install && { killall -q dwmblocks;setsid -f dwmblocks } + +" Which key description +autocmd! User vim-which-key call which_key#register('<Space>', 'g:which_key_map') +let g:which_key_map = {} + +" }}} + + +" BACKUP ----------------------------------------------------------------- {{{ + +if version >= 703 + set undodir=${XDG_CONFIG_HOME:-$HOME/.config}/vim/undodir + set undofile + set undoreload=10000 +endif + +" }}} + + +" PLUGINS INIT ----------------------------------------------------------- {{{ + +let config_path = empty($XDG_CONFIG_HOME) ? expand("$HOME/.config") : expand("$XDG_CONFIG_HOME") +if filereadable(config_path . "/vim/plugins.vim") + silent! call mkdir(config_path . "/vim/plugged", "p") + execute "source " . config_path . "/vim/plugins.vim" +endif + +" goyo +let g:is_goyo_active = v:false +function! GoyoEnter() + if executable('tmux') && strlen($TMUX) + silent !tmux set status off + silent !tmux list-panes -F '\#F' | grep -q Z || tmux resize-pane -Z + endif + + let g:default_colorscheme = exists('g:colors_name') ? g:colors_name : 'desert' + set background=light + set linebreak + set wrap + set textwidth=0 + set wrapmargin=0 + + Goyo 80x85% + colorscheme seoul256 + let g:is_goyo_active = v:true +endfunction + +function! GoyoLeave() + if executable('tmux') && strlen($TMUX) + silent !tmux set status on + silent !tmux list-panes -F '\#F' | grep -q Z && tmux resize-pane -Z + endif + + Goyo! + execute 'colorscheme ' . g:default_colorscheme + let g:is_goyo_active = v:false +endfunction + +function! ToggleGoyo() + if g:is_goyo_active + call GoyoLeave() + else + call GoyoEnter() + endif +endfunction + +" }}} + + +" PLUGIN MAPPINGS & SETTINGS -------------------------------------------------------- {{{ + +" Open quickfix/location list +let g:which_key_map.o = { + \ 'name' : '+Open' , + \ 'q' : 'Quickfix-list' , + \ 'l' : 'Location-list' , + \ } + +" Check health +nnoremap <Leader>ch :CheckHealth<CR> +let g:which_key_map.c = { 'name' : 'Check' } +let g:which_key_map.c.h = 'Check-health' + +" Bookmarks +let g:bookmark_no_default_key_mappings = 1 +let g:bookmark_save_per_working_dir = 1 +let g:bookmark_auto_save = 1 +nmap <Leader>mm <Plug>BookmarkToggle +nmap <Leader>mi <Plug>BookmarkAnnotate +nmap <Leader>ma <Plug>BookmarkShowAll +nmap <Leader>m] <Plug>BookmarkNext +nmap <Leader>m[ <Plug>BookmarkPrev +nmap <Leader>mc <Plug>BookmarkClear +nmap <Leader>mx <Plug>BookmarkClearAll +nmap <Leader>mk <Plug>BookmarkMoveUp +nmap <Leader>mj <Plug>BookmarkMoveDown +nmap <Leader>mg <Plug>BookmarkMoveToLine + +" Fugitive +nnoremap <Leader>gs :Git<CR> +let g:which_key_map.g = { 'name' : 'Git/Goyo' } +let g:which_key_map.g.s = 'Git' + +" Goyo plugin makes text more readable when writing prose: +nnoremap <Leader>gy :call ToggleGoyo()<CR> +let g:which_key_map.g.y = 'Toggle-goyo' + +" Nerd tree +map <Leader>n :NERDTreeToggle<CR> +let g:which_key_map.n = 'Toggle-nerd-tree' + +" Undotree +nnoremap <Leader>u :UndotreeToggle<CR> +let g:which_key_map.u = 'Toggle-undo-tree' + +" vimwiki +map <Leader>vw :VimwikiIndex<CR> +let g:which_key_map.v = { 'name' : '+Vim-wiki' } +let g:which_key_map.v.w = 'Vim-wiki-index' + +" vim-plug +nnoremap <Leader>pc :PlugClean<CR> +nnoremap <Leader>pi :PlugInstall<CR> +nnoremap <Leader>pu :PlugUpdate<CR> +let g:which_key_map.p = { 'name' : '+Plug' } +let g:which_key_map.p.c = 'Plug-clean' +let g:which_key_map.p.i = 'Plug-install' +let g:which_key_map.p.u = 'Plug-update' + +" whichkey +nnoremap <silent> <Leader> :<C-U>WhichKey '<Space>'<CR> +nnoremap <silent> <localleader> :<C-U>WhichKey '\'<CR> + +" lsp +if executable('pylsp') + " pip install python-lsp-server + au User lsp_setup call lsp#register_server({ + \ 'name': 'pylsp', + \ 'cmd': {server_info->['pylsp']}, + \ 'allowlist': ['python'], + \ }) +endif + +function! s:on_lsp_buffer_enabled() abort + setlocal omnifunc=lsp#complete + setlocal signcolumn=yes + if exists('+tagfunc') | setlocal tagfunc=lsp#tagfunc | endif + nmap <buffer> gd <plug>(lsp-definition) + nmap <buffer> gs <plug>(lsp-document-symbol-search) + nmap <buffer> gS <plug>(lsp-workspace-symbol-search) + nmap <buffer> gr <plug>(lsp-references) + nmap <buffer> gi <plug>(lsp-implementation) + nmap <buffer> gt <plug>(lsp-type-definition) + nmap <buffer> <Leader>lr <plug>(lsp-rename) + nmap <buffer> [t <plug>(lsp-previous-diagnostic) + nmap <buffer> ]t <plug>(lsp-next-diagnostic) + nmap <buffer> K <plug>(lsp-hover) + " nnoremap <buffer> <expr><C-D> lsp#scroll(+4) + " nnoremap <buffer> <expr><C-U> lsp#scroll(-4) + + let g:lsp_format_sync_timeout = 1000 + autocmd! BufWritePre *.rs,*.go,*.py call execute('LspDocumentFormatSync') + + " refer to doc to add more commands +endfunction + +let g:which_key_map.g = { + \ 'name' : '+Goto' , + \ 'd' : 'Definition' , + \ 's' : 'Symbol' , + \ 'S' : 'Workspace-symbol' , + \ 'r' : 'References' , + \ 'i' : 'Implementation' , + \ 't' : 'Type-definition' , + \ } + +let g:which_key_map['['] = { 'name' : '+Previous' } +let g:which_key_map[']'] = { 'name' : '+Next' } +let g:which_key_map['[t'] = 'Diagnostic' +let g:which_key_map[']t'] = 'Diagnostic' +let g:which_key_map.K = 'Keyword' + +augroup lsp_install + au! + " call s:on_lsp_buffer_enabled only for languages that has the server registered. + autocmd User lsp_buffer_enabled call s:on_lsp_buffer_enabled() +augroup END + +let g:lsp_fold_enabled = 0 +let g:lsp_log_verbose = 1 +let g:lsp_log_file = expand('~/.cache/vim/vim-lsp.log') +let g:asyncomplete_log_file = expand('~/.cache/vim/asyncomplete.log') +let g:lsp_settings_filetype_python = ['pyright-langserver', 'ruff', 'ruff-lsp'] + +nnoremap <Leader>li :LspInstallServer<CR> + +" vim-airline +if !exists('g:airline_symbols') + let g:airline_symbols = {} +endif +let g:airline_symbols.colnr = ' C:' +let g:airline_symbols.linenr = ' L:' +let g:airline_symbols.maxlinenr = ' ' +let g:airline#extensions#whitespace#symbol = '!' + +" colorscheme +if isdirectory(expand("${XDG_CONFIG_HOME:-$HOME/.config}/vim/plugged/catppuccin")) + let g:airline_theme = 'catppuccin_mocha' + colorscheme catppuccin_mocha +endif + +" fzf +let g:fzf_vim = {} +let $FZF_DEFAULT_OPTS = "--layout=default --preview-window 'right:60%' --preview 'bat --style=numbers --line-range :300 {}' + \ --bind ctrl-y:preview-up, + \ ctrl-e:preview-down, + \ ctrl-b:preview-page-up, + \ ctrl-f:preview-page-down, + \ ctrl-u:preview-half-page-up, + \ ctrl-d:preview-half-page-down, + \ shift-up:preview-top, + \ shift-down:preview-bottom, + \ alt-up:half-page-up, + \ alt-down:half-page-down + \ " + +" tmux +if exists('$TMUX') + let g:fzf_layout = { 'tmux': '90%,70%' } + let g:tmux_navigator_no_wrap = 1 +else + let g:fzf_layout = { 'window': { 'width': 0.9, 'height': 0.6, 'relative': v:true } } +endif +let g:fzf_vim.preview_window = ['right,50%,<70(up,40%)', 'ctrl-/'] +let g:fzf_vim.commits_log_options = '--graph --color=always --format="%C(auto)%h%d %s %C(black)%C(bold)%cr"' +let g:fzf_vim.tags_command = 'ctags -R' + +function! s:build_quickfix_list(lines) + call setqflist(map(copy(a:lines), '{ "filename": v:val, "lnum": 1 }')) + copen + cc +endfunction + +let g:fzf_action = { + \ 'ctrl-q' : function('s:build_quickfix_list'), + \ 'ctrl-t' : 'tab split' , + \ 'ctrl-x' : 'split' , + \ 'ctrl-v' : 'vsplit' , + \ } + +nnoremap <Leader>cl :Colors<CR> +nnoremap <Leader>fb :Files ~/.local/bin<CR> +nnoremap <Leader>fc :Files ~/.config<CR> +nnoremap <Leader>fd :Files ~/.dotfiles<CR> +nnoremap <Leader>ff :Files .<CR> +nnoremap <Leader>fF :Files ~<CR> +nnoremap <Leader>fg :GFiles<CR> +nnoremap <Leader>fG :GFiles?<CR> +nnoremap <Leader>fs :Files ~/.local/src/suckless<CR> +nnoremap <Leader>fv :Files ~/.config/vim<CR> +nnoremap <Leader>sb :Buffers<CR> +nnoremap <Leader>sc :Changes<CR> +nnoremap <Leader>sC :Commands<CR> +nnoremap <Leader>sg :Rg<CR> +nnoremap <Leader>sG :RG<CR> +nnoremap <Leader>shc :History:<CR> +nnoremap <Leader>shh :History<CR> +nnoremap <Leader>shp :Helptags<CR> +nnoremap <Leader>shs :History/<CR> +nnoremap <Leader>sj :Jumps<CR> +nnoremap <Leader>sk :Maps<CR> +nnoremap <Leader>sl :Locate<CR> +nnoremap <Leader>sm :Marks<CR> +nnoremap <Leader>sn :Snippets<CR> +nnoremap <Leader>st :Filetypes<CR> +nnoremap <Leader>gc :Commits<CR> +nnoremap <Leader>gC :BCommits<CR> + +let g:which_key_map.c = 'Color-schemes' +let g:which_key_map.f = { + \ 'name' : '+Find' , + \ 'b' : 'Scripts' , + \ 'c' : 'Config' , + \ 'd' : 'Dotfiles' , + \ 'f' : 'Files' , + \ 'F' : 'Root-files' , + \ 'g' : 'Git-files' , + \ 'G' : 'Git-status' , + \ 's' : 'Suckless' , + \ 'v' : 'Vim-config' , + \ } + +let g:which_key_map.g = { + \ 'name' : '+Git' , + \ 'c' : 'Commits' , + \ 'C' : 'Buffer-commits' , + \ } + +let g:which_key_map.s = { + \ 'name' : '+Search' , + \ 'b' : 'Buffers' , + \ 'c' : 'Changes' , + \ 'C' : 'Commands' , + \ 'g' : 'Rip-grep' , + \ 'G' : 'Rip-Grep' , + \ 'h' : { + \ 'name' : '+History' , + \ 'c' : 'Command-history' , + \ 'h' : 'History' , + \ 'p' : 'Help-tags' , + \ 's' : 'Search-history' , + \ }, + \ 'j' : 'Jumps' , + \ 'k' : 'Key-maps' , + \ 'l' : 'Locate' , + \ 'm' : 'Marks' , + \ 'n' : 'Snippets' , + \ 't' : 'File-types' , + \ } + + +" snippets +let g:SuperTabDefaultCompletionType = '<C-N>' +let g:SuperTabCrMapping = 0 +let g:UltiSnipsExpandTrigger = '<C-E>' +let g:UltiSnipsJumpForwardTrigger = '<tab>' +let g:UltiSnipsJumpBackwardTrigger = '<s-tab>' +let g:UltiSnipsEditSplit = 'vertical' +let g:UltiSnipsAutoTrigger = 1 +let g:asyncomplete_auto_completeopt = 0 +let g:asyncomplete_auto_popup = 1 + +set completeopt=menuone,noinsert,noselect,preview +autocmd! CompleteDone * if pumvisible() == 0 | pclose | endif + +if has('python3') + call asyncomplete#register_source(asyncomplete#sources#ultisnips#get_source_options({ + \ 'name': 'ultisnips', + \ 'allowlist': ['*'], + \ 'completor': function('asyncomplete#sources#ultisnips#completor'), + \ })) +endif + +inoremap <expr> <Tab> pumvisible() ? "\<C-N>" : "\<Tab>" +inoremap <expr> <S-Tab> pumvisible() ? "\<C-P>" : "\<S-Tab>" +inoremap <expr> <CR> pumvisible() ? asyncomplete#close_popup() : "\<CR>" + +" whichkey +set timeoutlen=500 + +let g:which_key_map.a = 'Select-all-the-text' +let g:which_key_map.b = { 'name' : '+Buffer' } +let g:which_key_map.b.n = 'New/open-buffer' +let g:which_key_map.c = { 'name' : '+Format' } +let g:which_key_map.c.f = 'Format-buffer' +let g:which_key_map.e = 'Explorer' +let g:which_key_map.h = { 'name' : '+Hex' } +let g:which_key_map.h.x = 'Toggle-hex/reverse-conversion' +let g:which_key_map.l = { 'name' : '+Lex/Lsp' } +let g:which_key_map.l.e = 'Open-lex' +let g:which_key_map.l.i = 'Lsp-install-server' +let g:which_key_map.l.r = 'Rename' +let g:which_key_map.o = { 'name' : '+Open' } +let g:which_key_map.o.g = 'Orthography' +let g:which_key_map.Q = 'Force-quit-all' +let g:which_key_map.r = { 'name' : '+Replace' } +let g:which_key_map.r.w = 'Replace word' +let g:which_key_map.s = { 'name' : '+Surround' } +let g:which_key_map.s.o = 'Source-file' +let g:which_key_map.s.w = 'Surround-word' +let g:which_key_map.t = 'Go-to-tab' +let g:which_key_map["'"] = 'Register' +let g:which_key_map['w'] = { + \ 'name' : '+windows' , + \ 'd' : ['<C-W>c' , 'Delete-window'] , + \ 'h' : ['<C-W>h' , 'Window-left'] , + \ 'H' : ['<C-W>5<' , 'Expand-window-left'] , + \ 'j' : ['<C-W>j' , 'Window-below'] , + \ 'J' : [':resize +5' , 'Expand-window-below'] , + \ 'k' : ['<C-W>k' , 'Window-up'] , + \ 'K' : [':resize -5' , 'Expand-window-up'] , + \ 'l' : ['<C-W>l' , 'Window-right'] , + \ 'L' : ['<C-W>5>' , 'Expand-window-right'] , + \ 's' : ['<C-W>s' , 'Split-window-below'] , + \ 'v' : ['<C-W>v' , 'Split-window-below'] , + \ 'w' : ['<C-W>w' , 'Other-window'] , + \ '2' : ['<C-W>v' , 'Layout-double-columns'] , + \ '-' : ['<C-W>s' , 'Split-window-below'] , + \ '|' : ['<C-W>v' , 'Split-window-right'] , + \ '=' : ['<C-W>=' , 'Balance-window'] , + \ '?' : ['Windows' , 'Fzf-window'] , + \ } + +" }}} + + +" SHORTCUTS ---------------------------------------------------------------- {{{ + +if filereadable(expand("${XDG_CONFIG_HOME:-$HOME/.config}/nvim/shortcuts.vim")) + silent! source ${XDG_CONFIG_HOME:-$HOME/.config}/nvim/shortcuts.vim +endif + +" }}} diff --git a/fedora/.config/vim/vimrc b/fedora/.config/vim/vimrc new file mode 100644 index 0000000..0535aec --- /dev/null +++ b/fedora/.config/vim/vimrc @@ -0,0 +1,582 @@ + +" VIM ENV --------------------------------------------------------------- {{{ + +if $USER != "root" + set runtimepath^=$XDG_CONFIG_HOME/vim + set runtimepath+=$XDG_DATA_HOME/vim + set runtimepath+=$XDG_CONFIG_HOME/vim/after + set viminfofile=$XDG_DATA_HOME/vim/.viminfo + + set packpath^=$XDG_DATA_HOME/vim,$XDG_CONFIG_HOME/vim + set packpath+=$XDG_CONFIG_HOME/vim/after,$XDG_DATA_HOME/vim/after + let g:netrw_home = $XDG_DATA_HOME."/vim" + call mkdir($XDG_DATA_HOME."/vim/spell", 'p') + + set backupdir=$XDG_CONFIG_HOME/vim/backup | call mkdir(&backupdir, 'p') + set directory=$XDG_CONFIG_HOME/vim/swap | call mkdir(&directory, 'p') + set undodir=$XDG_DATA_HOME/history/vim_history | call mkdir(&undodir, 'p') + set viewdir=$XDG_CONFIG_HOME/vim/view | call mkdir(&viewdir, 'p') +else + set runtimepath^=/root/.config/vim + set runtimepath+=/root/.local/share/vim + set runtimepath+=/root/.config/vim/after + set viminfofile=/root/.local/share/vim/.viminfo + + set packpath^=/root/.local/share/vim,/root/.config/vim + set packpath+=/root/.config/vim/after,/root/.local/share/vim/after + + let g:netrw_home = "/root/.local/share/vim" + call mkdir("/root/.local/share/vim/spell", 'p') + + set backupdir=/root/.config/vim/backup | call mkdir(&backupdir, 'p') + set directory=/root/.config/vim/swap | call mkdir(&directory, 'p') + set undodir=/root/.local/share/history/vim_history | call mkdir(&undodir, 'p') + set viewdir=/root/.config/vim/view | call mkdir(&viewdir, 'p') +endif + +" }}} + + +" AUTOCMD ---------------------------------------------------------------- {{{ + +autocmd VimEnter * silent execute '!echo -ne "\e[2 q"' + +" }}} + + +" Hex_Toggle_Functions --------------------------------------------------- {{{ + +function! DoHex() + " Get the current buffer name + let current_file = expand('%') + + " New file name + let new_file = current_file . '.hex' + + " Save the current buffer as a hex file + execute 'w !xxd > ' . new_file + + echo "Hex file created and saved as " . new_file +endfunction + +function! UndoHex() + " Get the current buffer name + let current_file = expand('%') + + " Name stage 1: Remove the .hex extension if it exists + let new_file_stage1 = substitute(current_file, '\.hex$', '', '') + + " Get the file name without extension + let file_name = substitute(new_file_stage1, '\(.*\)\.\(\w\+\)$', '\1', '') + + " Get the file extension + let file_extension = substitute(new_file_stage1, '\(.*\)\.\(\w\+\)$', '\2', '') + + " Add 'M' before the extension(M = Modded) + let new_file = file_name . 'M.' . file_extension + + " Save the current buffer as a reversed hex file + execute 'w !xxd -r > ' . new_file + + echo "Reversed Hex file created and saved as " . new_file +endfunction + +" Function to toggle between hex and original states +function! HexState() + " Get user input to choose the operation (0 for DoHex, 1 for UndoHex) + let operation = input("Choose operation (0 for DoHex, 1 for UndoHex): ") + + if operation == 0 + " Execute the DoHex function + call DoHex() + elseif operation == 1 + " Execute the UndoHex function + call UndoHex() + else + echo "Invalid choice. Aborting." + endif +endfunction + +" }}} + + +" GVIM - GUI VERSION ----------------------------------------------------- {{{ + +if has('gui_running') + + " Font + if has("macvim") + set guifont=Menlo\ Regular:h14 + elseif has("win32") + set guifont=Consolas\ 14 + else + set guifont=Consolas\ 18 + endif + + " Hide the toolbar. + set guioptions-=T + + " Hide the right-side scroll bar. + set guioptions-=r + + " Start Lex Tree and put the cursor back in the other window. + autocmd VimEnter * :Lexplore | wincmd p + +endif + +" }}} + + +" MAPPINGS --------------------------------------------------------------- {{{ + +" Set the space as the leader key. +let mapleader = " " +let maplocalleader = "\\" + +" Diable +nnoremap Q <nop> + +" Cmd & Esc +nnoremap <C-C> : +inoremap <C-C> <Esc>: + +" Spell-check on\off to <Leader>o, 'o' for 'orthography': +map <Leader>og :setlocal spell! spelllang=en_us<CR> + +" Type jk to exit insert mode quickly. +inoremap jk <Esc> + +" Format a paragraph into lines +map <Leader>cf gq<CR> + +" Select all the text +nnoremap <Leader>a ggVG + +" Opening a file explore +map <Leader>le :Lex<CR> + +" Opening a file from explorer +map <Leader>e :Explore<CR> + +" Opening a terminal window +map <C-T> :ter<CR> + +" Closing the terminal window +tnoremap <C-T> exit<CR> + +" Buffer +nnoremap H :bprev<CR> +nnoremap L :bnext<CR> + +" CTRL+I OR Esc to make the terminal scrollable and I to input mode +tnoremap <C-I> <C-W><S-N> +tnoremap <Esc> <C-\><C-n> + +" You can split the window in Vim. y - in the y access , x - in the x access +map <Leader>w\- :split<CR> +map <Leader>w\| :vsplit<CR> + +" Better move +nnoremap <C-U> 11kzz +nnoremap <C-D> 11jzz +nnoremap n nzzzv +nnoremap N Nzzzv + +" Navigate the split view easier by pressing CTRL+j, CTRL+k, CTRL+h, or CTRL+l. +nnoremap <C-J> <C-W>j +nnoremap <C-K> <C-W>k +nnoremap <C-H> <C-W>h +nnoremap <C-L> <C-W>l + +" Resize split windows using arrow keys by pressing: +" CTRL+UP, CTRL+DOWN, CTRL+LEFT, or CTRL+RIGHT. +noremap <C-Up> <C-W>+ +noremap <C-Down> <C-W>- +noremap <C-Left> <C-W>< +noremap <C-Right> <C-W>> + +" Moving between tabs +map <Leader>t gt + +" Opening/Creating a file in a new tab - write the tab to open +nnoremap <Leader>bn :tabedit<Space> + +" Saving a file using CTRL+S +map <C-S> :w<CR> + +" Quitting and saving a file using CTRL+S +map <Leader>bd :bd<CR> +map <Leader>BD :bd!<CR> +map <Leader>wq :wq<CR> +nnoremap <Leader>q :q!<CR> +nnoremap <Leader>Q :qa!<CR> + +" Surround word with a wanted character +nnoremap <Leader>sw <CMD>echo "Press a character: " \| let c = nr2char(getchar()) \| exec "normal viwo\ei" . c . "\eea" . c . "\e" \| redraw<CR> + +" Replace all occurrences of a word +nnoremap <Leader>rw :%s/\<<C-R><C-W>\>//g<Left><Left> + +" Toggle between creating a Hex conversion file and reversing the conversion +nnoremap <Leader>hx <CMD>call HexState()<CR> + +" For copy and past if supports clipbard +if has('gui_running') + map p "+P + xnoremap <Leader>p "_dP + nmap <Leader>Y "+Y + nnoremap <Leader>y "*y :let @+=@*<CR> + vnoremap <Leader>y "*y :let @+=@*<CR> + nmap <Leader>D "+D + nnoremap <Leader>d "+d + vnoremap <Leader>d "+d +endif + +" Change +nnoremap c "_c + +" Delete +nnoremap x "_x + +" Seeing the registers +nnoremap <Leader>' <CMD>registers<CR> + +" Moving lines in visual mode +vnoremap J :m '>+1<CR>gv=gv +vnoremap K :m '>-2<CR>gv=gv + +" Join +nnoremap J mzJ`z + +" Perform dot commands over visual blocks: +vnoremap . :normal .<CR> + +" Source file +nnoremap <Leader>so :so<CR> + +" Compiler +nnoremap <Leader>rr :w<CR>:terminal compiler %<CR>:resize 10<CR> + +" Open quickfix/location list" +nnoremap <silent> <Leader>oq :copen<CR> +nnoremap <silent> <Leader>ol :lopen<CR> + +" }}} + + +" SETTINGS --------------------------------------------------------------- {{{ + +" Cursor shapes +let &t_SI = "\<Esc>[6 q" +let &t_SR = "\<Esc>[4 q" +let &t_EI = "\<Esc>[2 q" + +" Clipboard +set clipboard+=unnamedplus + +" Disable auto commenting in a new line +autocmd Filetype * setlocal formatoptions-=c formatoptions-=r formatoptions-=o + +" Setting the character encoding of Vim to UTF-8 +set encoding=UTF-8 + +" Enable type file detection. Vim will be able to try to detect the type of file is use. +filetype on + +" Enable spell check +set nospell +highlight SpellBad ctermfg=204 guifg=#F28FAD gui=undercurl guisp=#F28FAD +highlight SpellCap ctermfg=75 guifg=#9D7CD8 gui=undercurl guisp=#9D7CD8 +highlight SpellRare ctermfg=81 guifg=#0DB9D7 gui=undercurl guisp=#0DB9D7 +highlight SpellLocal ctermfg=142 guifg=#FAB387 gui=undercurl guisp=#FAB387 + +" Avoids updating the screen before commands are completed +set lazyredraw + +" Smart tab +set smarttab + +" Search down to subfolders +set path+=** + +" Enable plugins and load plugin for the detected file type. +filetype plugin on + +" Load an indent file for the detected file type. +filetype indent on + +" Turn syntax highlighting on. +syntax on + +" Turns off highlighting on the bits of code that are changed, so the line that is changed is highlighted but the actual text that has changed stands out on the line and is readable. +if &diff + highlight! link DiffText MatchParen +endif + +" Add numbers to the file. +set number relativenumber + +" Mouse functionality +set mouse=a + +" Background color +" set bg=light + +" Color scheme +colorscheme desert + +" Highlight cursor line underneath the cursor horizontally. +set cursorline + +" Disable highlight cursor line underneath the cursor vertically. +set nocursorcolumn + +" Set shift width to 4 spaces.Set tab width to 4 columns. +set shiftwidth=4 +set tabstop=4 + +" If the current file type is HTML, set indentation to 2 spaces. +autocmd Filetype html setlocal tabstop=2 shiftwidth=2 expandtab + +" Do not save backup files. +set nobackup + +" Do wrap lines. +set wrap + +" While searching though a file incrementally highlight matching characters as you type. +set incsearch +set hlsearch + +" Ignore capital letters during search. +set ignorecase + +" Show partial command you type in the last line of the screen. +set showcmd + +" Show the mode you are on the last line. +set showmode + +" Show matching words during a search. +set showmatch + +" Show title of the file +set title + +" Timeout +set timeoutlen=300 " Time (in milliseconds) to wait for a mapping +set ttimeoutlen=10 " Time (in milliseconds) to wait for terminal key codes + +" Esc +set noesckeys + +" Set the commands to save in history default number is 20. +set history=1000 + +" Setting the split window to open as i like (like in a WM - qtile) +set splitbelow splitright + +" Enable auto completion menu after pressing TAB. +set wildmenu + +" There are certain files that we would never want to edit with Vim. +" Wild menu will ignore files with these extensions. +set wildignore=*.docx,*.jpg,*.png,*.gif,*.pdf,*.pyc,*.exe,*.flv,*.img,*.xlsx + +" If Vim version is equal to or greater than 7.3 enable undo file. +" This allows you to undo changes to a file even after saving it. +if version >= 703 + set undodir=~/.config/vim/backup + set undofile + set undoreload=10000 +endif + + +" File Browsing settings +let g:netrw_banner=0 +let g:netrw_liststyle=3 +let g:netrw_showhide=1 +let g:netrw_winsize=20 + + +" Auto Completion - Enable Omni complete features +set omnifunc=syntaxcomplete#Complete + + +" Enable Spelling Suggestions for Auto-Completion: +set complete+=k +set completeopt=menu,menuone,noinsert + + +" Minimalist-Tab Complete +inoremap <expr> <Tab> TabComplete() +fun! TabComplete() + if getline('.')[col('.') - 2] =~ '\K' || pumvisible() + return "\<C-N>" + else + return "\<Tab>" + endif +endfun + + +" Minimalist-Autocomplete +inoremap <expr> <CR> pumvisible() ? "\<C-Y>" : "\<CR>" +autocmd InsertCharPre * call AutoComplete() +fun! AutoComplete() + if v:char =~ '\K' + \ && getline('.')[col('.') - 4] !~ '\K' + \ && getline('.')[col('.') - 3] =~ '\K' + \ && getline('.')[col('.') - 2] =~ '\K' " last char + \ && getline('.')[col('.') - 1] !~ '\K' + + call feedkeys("\<C-N>", 'n') + end +endfun + + +" Closing compaction in insert mode +inoremap [ []<Left> +inoremap ( ()<Left> +inoremap { {}<Left> +inoremap /* /**/<Left><Left> + +" }}} + + +" STATUS LINE ------------------------------------------------------------ {{{ + +set laststatus=2 +set statusline= +set statusline+=%2* +set statusline+=%{StatuslineMode()} +set statusline+=%{SpellCheckStatus()} +set statusline+=%1* +set statusline+=%3* +set statusline+=< +set statusline+=- +set statusline+=%f +set statusline+=- +set statusline+=> +set statusline+=%4* +set statusline+=%m +set statusline+=%= +set statusline+=%h +set statusline+=%r +set statusline+=%4* +set statusline+=%c +set statusline+=/ +set statusline+=%l +set statusline+=/ +set statusline+=%L +set statusline+=%1* +set statusline+=| +set statusline+=%y +set statusline+=%4* +set statusline+=%P +set statusline+=%3* +set statusline+=t: +set statusline+=%n + +" }}} + + +" STATUS FUNCTIONS ------------------------------------------------------- {{{ + +" Mode +function! StatuslineMode() + let l:mode=mode() + if l:mode==#"n" + return "NORMAL" + elseif l:mode==#"V" + return "VISUAL LINE" + elseif l:mode==?"v" + return "VISUAL" + elseif l:mode==#"i" + return "INSERT" + elseif l:mode ==# "\<C-V>" + return "V-BLOCK" + elseif l:mode==#"R" + return "REPLACE" + elseif l:mode==?"s" + return "SELECT" + elseif l:mode==#"t" + return "TERMINAL" + elseif l:mode==#"c" + return "COMMAND" + elseif l:mode==#"!" + return "SHELL" + else + return "VIM" + endif +endfunction + +" Spell Check Status +function! SpellCheckStatus() + if &spell + return " [SPELL]" + else + return '' + endif +endfunction +" }}} + + +" VIMSCRIPT -------------------------------------------------------------- {{{ + +" This will enable code folding. +" Use the marker method of folding. +augroup filetype_vim + autocmd! + autocmd FileType vim setlocal foldmethod=marker +augroup END + + + +" INIT VIM --------------------------------------------------------------- {{{ + +if filereadable(expand("~/.config/vim/init.vim")) + source ~/.config/vim/init.vim +endif + +" }}} + + +" SHORTCUTS -------------------------------------------------------------- {{{ + +if filereadable(expand("~/.config/vim/shortcuts.vim")) + silent! source ~/.config/vim/shortcuts.vim +endif + +if filereadable(expand("~/.config/vim/rootshortcuts.vim")) + silent! source ~/.config/vim/rootshortcuts.vim +endif + +" }}} + + +" COLORS ----------------------------------------------------------------- {{{ + +" Terminal color +set t_Co=256 +if exists('+termguicolors') + set termguicolors +else + set notermguicolors +endif + +" Cursor +hi CursorLine cterm=NONE ctermbg=236 ctermfg=NONE gui=NONE guibg=Grey30 guifg=NONE + +" Transparent +hi Normal ctermbg=NONE guibg=NONE +hi NonText ctermbg=NONE guibg=NONE +hi LineNr ctermbg=NONE guibg=NONE +hi Folded ctermbg=NONE guibg=NONE +hi EndOfBuffer ctermfg=Grey guifg=Grey + +hi User1 ctermbg=brown ctermfg=white guibg=NONE guifg=white +hi User2 ctermbg=lightgreen ctermfg=black guibg=lightgreen guifg=black +hi User3 ctermbg=brown ctermfg=lightcyan guibg=NONE guifg=lightblue +hi User4 ctermbg=brown ctermfg=green guibg=NONE guifg=lightgreen + +" }}} diff --git a/fedora/.local/bin/bookmarks b/fedora/.local/bin/bookmarks new file mode 100755 index 0000000..a892a33 --- /dev/null +++ b/fedora/.local/bin/bookmarks @@ -0,0 +1,211 @@ +#!/bin/sh + +usage() { + echo "Open bookmarks, URLs, or browser history in a program." + echo "" + echo "Usage: ${0##*/} [OPTIONS]" + echo "" + echo "Options:" + echo " -h : Show this message" + echo " -b : Open a browser bookmark" + echo " -c : Copy a URL from snippets/urls to the clipboard" + echo " -o : Get a URL from snippets/urls and open it in a new browser window" + echo " -p : Get a URL from snippets/urls and open it in a private browser window" + echo " -s : Open browser history" + echo " -t : Get a URL from snippets/urls and type it using xdotool" + echo " -v : Open a browser bookmark in private browser window" + echo "" + echo "Programs:" + echo " browser : System default browser" + echo " lynx : A text browser for World Wide Web" + echo " w3m : A text WWW browser, similar to lynx" + echo "" + echo "Examples:" + echo " ${0##*/} -b # Opens a browser bookmark in a program" + echo " ${0##*/} -c # Copies a URL from snippets/urls to the clipboard" + echo " ${0##*/} -o # Opens a URL from snippets/urls in a new browser window" + echo " ${0##*/} -p # Opens a URL in a private browser window" + echo " ${0##*/} -s # Opens browser history in a program" + echo " ${0##*/} -v # Opens browser boomark in private browser window" +} + +addurls() { + url=$(echo | dmenu -i -p "Enter a url: ") + [ -z "$url" ] && printf "Error: url must be provided\n\n" && exit 0 + + description=$(echo | dmenu -i -p "Enter a description of the url: ") + [ -z "$description" ] && echo "https://$url" >>~/.local/share/thesiah/snippets + [ -n "$description" ] && echo "$description https://$url" >>~/.local/share/thesiah/snippets +} + +opentool() { + available_tools="" + command -v xdg-open 2>/dev/null | grep -v "alias" -q && available_tools="$available_tools xdg-open" + command -v open 2>/dev/null | grep -v "alias" -q && available_tools="$available_tools open" + command -v lynx 2>/dev/null | grep -v "alias" -q && available_tools="$available_tools lynx" + command -v w3m 2>/dev/null | grep -v "alias" -q && available_tools="$available_tools w3m" + available_tools=$(printf "%s" "$available_tools" | awk '{$1=$1; print}' | tr ' ' '\n') + if [ -z "$available_tools" ]; then + printf "No browser found\n" >&2 + exit 1 + fi + + opentool=$(printf "%s\n" "$available_tools" | dmenu -i -p "Choose an open tool:") + + # Set the selected tool to the variable 'open' + case "$opentool" in + xdg-open) xdg-open "$1" ;; + open) + case "$(uname -s)" in + Darwin) open "$1" ;; + *) xdg-open "$1" ;; + esac + ;; + lynx) setsid -f "$TERMINAL" -e lynx "$1" ;; + w3m) setsid -f "$TERMINAL" -e w3m "$1" ;; + *) echo "Invalid selection" >&2 && exit 1 ;; + esac +} + +openwindow() { + if [ "$1" = "private" ]; then + case "$BROWSER" in + *qutebrowser*) "$BROWSER" --target private-window "$url" ;; + *firefox* | *librewolf*) "$BROWSER" --private-window "$url" ;; + esac + else + case "$BROWSER" in + *qutebrowser*) "$BROWSER" --target window "$url" ;; + *firefox* | *librewolf*) "$BROWSER" --new-window "$url" ;; + esac + fi +} + +openinbrowser() { + # Extract only the default part of the profile name + case $BROWSER in + *firefox*) + profiles_ini_path="$HOME/.mozilla/firefox/profiles.ini" + profile=$(awk '/\[Install/ {found=1} found && /^Default=/ {split($0, arr, "."); print arr[2]; exit}' "$profiles_ini_path") + profile_dir=$(find ~/.mozilla/firefox -type d -name "*.$profile*" | head -n 1) + db_path="$profile_dir/places.sqlite" + ;; + *librewolf*) + profiles_ini_path="$HOME/.librewolf/profiles.ini" + profile=$(awk '/\[Install/ {found=1} found && /^Default=/ {split($0, arr, "."); print arr[2]; exit}' "$profiles_ini_path") + profile_dir=$(find ~/.librewolf -type d -name "*.$profile*" | head -n 1) + db_path="$profile_dir/places.sqlite" + ;; + *qutebrowser*) + profile_dir="${XDG_DATA_HOME:-${HOME}/.local/share}/qutebrowser" + db_path="$profile_dir/history.sqlite" + ;; + *) echo "Default browser path is needed." && exit ;; + esac + + tmp_file="$(mktemp)" + cp -f "$db_path" "$tmp_file" + + type dmenu >/dev/null 2>&1 && + selection="dmenu -i -l 20 -p \"Choose a $1 to open:\"" || + selection="fzf-tmux --reverse --cycle --ansi --delimiter='|' --with-nth=1..-2" + + cols=$((${COLUMNS:-90} / 3)) + case "$1" in + *bookmark*) + case "$BROWSER" in + qutebrowser) bookmarks -o ;; + *firefox* | *librewolf*) + sqlite_query=" + SELECT substr(b.title, 1, $cols) || ' | ' || p.url AS bookmark + FROM moz_bookmarks b + JOIN moz_places p ON b.fk = p.id + WHERE b.type = 1 AND p.url LIKE 'http%' AND b.title NOT NULL + ORDER BY b.title; + " + ;; + *qutebrowser*) geturls && openwindow && exit ;; + esac + ;; + *history*) + case "$BROWSER" in + *qutebrowser*) + sqlite_query=" + SELECT substr(h.title, 1, $cols) || ' | ' || h.url AS bookmark + FROM CompletionHistory h + ORDER BY h.last_atime DESC + LIMIT 100; + " + ;; + *firefox* | *librewolf*) + sqlite_query=" + SELECT substr(p.title, 1, $cols) || ' | ' || p.url + FROM moz_places p + JOIN moz_historyvisits hv ON hv.place_id = p.id + ORDER BY hv.visit_date DESC + LIMIT 100; + " + ;; + esac + ;; + esac + choice=$(sqlite3 "$tmp_file" "$sqlite_query" | eval "$selection" | cut -d'|' -f2 | sed 's|.*\(https://\)|\1|' | xargs) + if [ -n "$choice" ]; then + if echo "$1" | grep -q "private"; then + "$BROWSER" --private-window "$choice" + else + opentool "$choice" + fi + else + exit + fi + rm "$tmp_file" +} + +geturls() { + urls=$(cat ~/.config/qutebrowser/quickmarks ~/.config/qutebrowser/bookmarks/urls ~/.local/share/thesiah/snippets ~/.local/share/thesiah/urls 2>/dev/null) + choice=$(echo "$urls" | grep -v -e '^#' -e '^$' | awk ' + { + if ($1 ~ /^https?:\/\//) { alias = substr($0, index($0, $2)) } # Case 2: URL first + else { alias = substr($0, 1, length($0) - length($NF) - 1) } # Case 1: URL last + print alias + }' | dmenu -i -l 50 -p "Choose an alias $1:") + + [ -z "$choice" ] && exit + url=$(echo "$urls" | grep -v -e '^#' -e '^$' | awk -v choice="$choice" ' + { + if ($1 ~ /^https?:\/\//) { url = $1; alias = substr($0, index($0, $2)) } # Case 2 + else { alias = substr($0, 1, length($0) - length($NF) - 1); url = $NF } # Case 1 + if (alias == choice) print url + }') +} + +copytoclipboard() { + if command -v xclip >/dev/null 2>&1; then + printf "%s" "$url" | xclip -selection clipboard + elif command -v clipcopy >/dev/null 2>&1; then + printf "%s" "$url" | clipcopy + elif command -v xsel >/dev/null 2>&1; then + printf "%s" "$url" | xsel --clipboard --input + else + echo "Clipboard utility not found. Install xclip, clipcopy, or xsel." >&2 + exit 1 + fi + notify-send "'$choice' copied in clipbaord" "$url" +} + +[ $# -eq 0 ] && usage && exit 1 + +while getopts "abchopstv" opt; do + case $opt in + a) addurls ;; + b) openinbrowser "bookmark" ;; + c) geturls "to copy" && copytoclipboard ;; + o) geturls "to open in $BROWSER" && openwindow ;; + p) geturls "to open in private $BROWSER" && openwindow private ;; + s) openinbrowser "history" ;; + t) geturls "to type under cursor" && xdotool type "$url" ;; + v) openinbrowser "private bookmark" ;; + h | *) usage && exit 0 ;; + esac +done diff --git a/fedora/.local/bin/extract b/fedora/.local/bin/extract new file mode 100755 index 0000000..b352a70 --- /dev/null +++ b/fedora/.local/bin/extract @@ -0,0 +1,41 @@ +#!/bin/sh + +# Default behavior: Extract archive into new directory +# Behavior with `-c` option: Extract contents into current directory + +while getopts "hc" o; do case "${o}" in + c) extracthere="True" ;; + *) printf 'Options:\n -c: Extract archive into current directory rather than a new one.\n' && exit ;; + esac done + +if [ -z "$extracthere" ]; then + archive="$(readlink -f "$*")" && + directory=${archive%.*} && + mkdir -p "$directory" && + cd "$directory" || exit +else + archive="$(readlink -f "$(echo "$*" | cut -d' ' -f2)")" +fi + +[ "$archive" = "" ] && printf 'Give archive to extract as argument.\n' && exit + +if [ -f "$archive" ]; then + case "$archive" in + *.tar.bz2 | *.tar.xz | *.tbz2) tar xvjf "$archive" ;; + *.tar.gz | *.tgz) tar xvzf "$archive" ;; + *.lzma) unlzma "$archive" ;; + *.bz2) bunzip2 "$archive" ;; + *.rar) unrar x -ad "$archive" ;; + *.gz) gunzip "$archive" ;; + *.tar) tar xvf "$archive" ;; + *.zip | *.jar | *.war) unzip "$archive" ;; + *.Z) uncompress "$archive" ;; + *.7z) 7z x "$archive" ;; + *.xz) unxz "$archive" ;; + *.exe) cabextract "$archive" ;; + *.ace) unace x "$archive" ;; + *) printf "extract: '%s' - unknown archive method\\n" "$archive" ;; + esac +else + printf 'File "%s" not found.\n' "$archive" +fi diff --git a/fedora/.local/bin/lastnvim b/fedora/.local/bin/lastnvim new file mode 100755 index 0000000..b1ab6c9 --- /dev/null +++ b/fedora/.local/bin/lastnvim @@ -0,0 +1,77 @@ +#!/bin/sh + +# Display help message +usage() { + echo "Open the most recent file or the list of old files in fzf edited by nvim." + echo "" + echo "Usage: ${0##*/} [OPTION]" + echo "" + echo "Options:" + echo " : Open the most recent old file in Neovim." + echo " -h, --help : Show this help message." + echo " -l, --list : Show all recent files in Neovim using fzf." + echo "" + echo "Examples:" + echo " ${0##*/} # Open the most recent file." + echo " ${0##*/} -l # Show all recent files in fzf and select to open." + exit 0 +} + +# List and handle oldfiles +list_oldfiles() { + # Fetch the oldfiles list from Neovim + oldfiles=$(nvim -u NONE --headless +'lua io.write(table.concat(vim.v.oldfiles, "\n") .. "\n")' +qa) + + # Exit if no oldfiles are found + [ -z "$oldfiles" ] && { + echo "No recent files found in Neovim." >&2 + exit 1 + } + + case "$1" in + -h | --help) + usage + ;; + -l | --list) + # Filter valid files + valid_files=$(echo "$oldfiles" | while IFS= read -r file; do + [ -f "$file" ] && printf "%s\n" "$file" + done) + + # Exit if no valid files exist + [ -z "$valid_files" ] && { + echo "No valid files found." >&2 + exit 1 + } + + # Use fzf to select files + selected_files=$(echo "$valid_files" | + fzf-tmux \ + --multi \ + --preview 'bat -n --color=always --line-range=:500 {} 2>/dev/null || echo "Error previewing file"' \ + --height=70% \ + --reverse) + + # Exit if no files were selected + [ -z "$selected_files" ] && exit 1 + + # Open selected files in Neovim + openfiles "$selected_files" + ;; + *) + # Open the most recent file + for file in $oldfiles; do + if [ -f "$file" ]; then + openfiles "$file" + exit 0 + fi + done + + echo "No valid recent files found." >&2 + exit 1 + ;; + esac +} + +# Parse command-line arguments +list_oldfiles "$@" diff --git a/fedora/.local/bin/openfiles b/fedora/.local/bin/openfiles new file mode 100755 index 0000000..5b4f7e2 --- /dev/null +++ b/fedora/.local/bin/openfiles @@ -0,0 +1,34 @@ +#!/bin/sh + +if ! command -v nvim >/dev/null 2>&1; then + echo "Error: 'nvim' is not installed." >&2 + exit 1 +fi + +IFS=' +' + +files=$* + +for file in $files; do + files_list="$files_list \"$(realpath "$file")\"" +done + +eval "set -- $files_list" + +count=$# + +case "$count" in +2) + ${EDITOR:-nvim} -O +'silent! normal g;' "$@" -c 'wincmd t' + ;; +3) + ${EDITOR:-nvim} -O "$1" -c 'wincmd j' -c "silent! vsplit $2" -c "silent! split $3" -c 'wincmd t' + ;; +4) + ${EDITOR:-nvim} -O "$1" -c "silent! vsplit $2" -c "silent! split $3" -c 'wincmd h' -c "silent! split $4" -c 'wincmd t' + ;; +*) + ${EDITOR:-nvim} "$@" + ;; +esac diff --git a/fedora/.local/bin/opensessions b/fedora/.local/bin/opensessions new file mode 100755 index 0000000..6f9f236 --- /dev/null +++ b/fedora/.local/bin/opensessions @@ -0,0 +1,37 @@ +#!/bin/sh + +# split the selected directories into an array +dirs="$*" + +# filter out any empty selections +dirs=$(echo "$dirs" | tr -s ' ' '\n' | sed '/^$/d') +[ -z "$dirs" ] && exit 0 + +# function to clean and create a valid session name +get_session_name() { + basename "$1" | sed 's/[^a-zA-Z0-9]/_/g' +} + +set -- $dirs + +# handle session creation for multiple selected directories +for dir in $dirs; do + if [ -d "$dir" ]; then + session_name=$(get_session_name "$dir") + if ! tmux has-session -t "$session_name" 2>/dev/null; then + tmux new-session -d -s "$session_name" -c "$dir" + if git -C "$dir" rev-parse --is-inside-work-tree >/dev/null 2>&1 && [ -n "$(git -C "$dir" status --porcelain)" ]; then + tmux send-keys -t "$session_name" "git status --porcelain" C-m + fi + fi + fi +done + +if [ "$#" -gt 0 ]; then + first_session=$(get_session_name "$1") + if [ -n "$TMUX" ]; then + tmux switch-client -t "$first_session" + else + tmux attach-session -t "$first_session" + fi +fi diff --git a/fedora/.local/bin/remaps b/fedora/.local/bin/remaps new file mode 100755 index 0000000..93832ea --- /dev/null +++ b/fedora/.local/bin/remaps @@ -0,0 +1,69 @@ +#!/bin/sh + +# This script is called on startup to remap keys. +xset s off -dpms +# Decrease key repeat delay to 200ms and increase key repeat rate to 50 per second. +xset r rate 200 50 +# Map the caps lock key to control, and map the menu key to right super. +xinput list | grep 'id=' | while read -r line; do + keyboard=$(echo "$line" | grep -i 'keyboard.*id.*keyboard' | sed 's/.*id=\([0-9]\+\).*/\1/') + mouse=$(echo "$line" | grep -i '.*id.*pointer' | sed 's/.*id=\([0-9]\+\).*/\1/') + [ -z "$keyboard" ] || { + case "$(echo "$line" | grep -oE '.*id=' | sed 's/ id=.*//')" in + *"Lite-On Tech Lenovo USB Travel Keyboard with Ultra Nav"*) + setxkbmap -device "$keyboard" -option + setxkbmap -device "$keyboard" -option caps:ctrl_modifier,ctrl:swap_lwin_lctl + ;; + *"Lite-On Technology Corp. ThinkPad USB Keyboard with TrackPoint"* | *"AT Translated Set 2 keyboard"*) + setxkbmap -device "$keyboard" -option + setxkbmap -device "$keyboard" -option caps:ctrl_modifier,altwin:menu_win,altwin:swap_lalt_lwin + ;; + *"Magic keyboard"*) + setxkbmap -device "$keyboard" -option + setxkbmap -device "$keyboard" -option caps:ctrl_modifier + ;; + *"HHKB"*) + setxkbmap -device "$keyboard" -option + setxkbmap -device "$keyboard" -option altwin:menu_win + ;; + *"Glove80"*) + setxkbmap -device "$keyboard" -option + ;; + *) + setxkbmap -device "$keyboard" -option + setxkbmap -device "$keyboard" -option caps:ctrl_modifier,altwin:menu_win + ;; + esac + } + [ -z "$mouse" ] || { + case "$(echo "$line" | grep -oE '.*id=' | sed 's/ id=.*//')" in + *"Apple Inc. Magic Trackpad"*) + xinput set-prop "$mouse" "libinput Tapping Enabled" 0 + ;; + *"SynPS/2 Synaptics TouchPad"*) + xinput set-prop "$mouse" "libinput Tapping Enabled" 0 + ;; + *"Lite-On Tech Lenovo USB Travel Keyboard with Ultra Nav Mouse"*) + [ -z "$1" ] && xinput set-prop "$mouse" "Coordinate Transformation Matrix" 5, 0, 0, 0, 5, 0, 0, 0, 1 || xinput set-prop "$mouse" "Coordinate Transformation Matrix" $1, 0, 0, 0, $1, 0, 0, 0, 1 + xinput set-prop "$mouse" "libinput Scroll Method Enabled" 0, 0, 1 + ;; + *"Logitech USB Receiver"*) + [ -z "$1" ] && xinput set-prop "$mouse" "Coordinate Transformation Matrix" 3, 0, 0, 0, 3, 0, 0, 0, 1 || xinput set-prop "$mouse" "Coordinate Transformation Matrix" $1, 0, 0, 0, $1, 0, 0, 0, 1 + ;; + *"TPPS/2 IBM TrackPoint"*) + [ -z "$1" ] && xinput set-prop "$mouse" "Coordinate Transformation Matrix" 1, 0, 0, 0, 1, 0, 0, 0, 1 || xinput set-prop "$mouse" "Coordinate Transformation Matrix" $1, 0, 0, 0, $1, 0, 0, 0, 1 + ;; + *"Lite-On Technology Corp. ThinkPad USB Keyboard with TrackPoint"*) + [ -z "$1" ] && xinput set-prop "$mouse" "Coordinate Transformation Matrix" 3, 0, 0, 0, 3, 0, 0, 0, 1 || xinput set-prop "$mouse" "Coordinate Transformation Matrix" $1, 0, 0, 0, $1, 0, 0, 0, 1 + ;; + *"Glove80 Mouse"*) + [ -z "$1" ] && xinput set-prop "$mouse" "Coordinate Transformation Matrix" 2, 0, 0, 0, 2, 0, 0, 0, 1 || xinput set-prop "$mouse" "Coordinate Transformation Matrix" $1, 0, 0, 0, $1, 0, 0, 0, 1 + ;; + esac + } +done +# When left control, caps lock, or Super_L is pressed only once, treat it as escape. +killall xcape 2>/dev/null +xcape -e 'Caps_Lock=Escape;Control_L=Escape' #;Super_L=Escape' +# Turn off caps lock if on since there is no longer a key for it. +xset -q | grep -q "Caps Lock:\s*on" && xdotool key Caps_Lock diff --git a/fedora/.local/bin/restartnvim b/fedora/.local/bin/restartnvim new file mode 100755 index 0000000..ab040ab --- /dev/null +++ b/fedora/.local/bin/restartnvim @@ -0,0 +1,25 @@ +#!/bin/sh + +set -e + +# Set new line and tab for word splitting +IFS=" + " + +# Check if the script is running inside a tmux session +if [ -z "$TMUX" ]; then + echo "This script must be run from inside a tmux session." + exit 1 +fi + +# Get the current tmux pane ID +tmux_pane=$(tmux display-message -p '#D') + +# Send Escape, :wq, and Enter to Neovim in the tmux pane +tmux send-keys -t "$tmux_pane" Escape C-m ':wq' C-m + +# Wait to ensure Neovim exits +sleep 0.5 + +# Detach the script from Neovim and wait a bit to ensure Neovim exits +(nohup sh -c "sleep 0.5; tmux send-keys -t \"$tmux_pane\" 'nvim -c \"execute \\\"edit \\\" . v:oldfiles[0] | normal '\''0\"' C-m" >/dev/null 2>&1 &) diff --git a/fedora/.local/bin/rgafiles b/fedora/.local/bin/rgafiles new file mode 100755 index 0000000..e8b5e72 --- /dev/null +++ b/fedora/.local/bin/rgafiles @@ -0,0 +1,120 @@ +#!/bin/sh + +# Usage function to display script options +usage() { + echo "Find files using ripgrep and open them in Neovim." + echo "" + echo "Usage: ${0##*/} [-s] [-i] [-l] [-p] [<tag>] <query>" + echo "" + echo "Options:" + echo " -h : Show this message" + echo " -i : Perform a case-insensitive search (default)" + echo " -l : List files associated with the given tag" + echo " -p : Search for files in the specified project directories using the specified tag (default: PROJECT)" + echo " -s : Perform a case-sensitive search" + echo " [<tag>] <query> : Optional tag for project mode, followed by the search query" + echo "" + echo "Examples:" + echo " ${0##*/} -p TODO 'KEYWORD' # Search for 'KEYWORD' in files tagged with 'TODO' in the project directories" + echo " ${0##*/} -l -p 'KEYWORD' # List files associated with the default 'PROJECT' tag and 'KEYWORD'" + echo " ${0##*/} 'KEYWORD' # Open files containing 'KEYWORD' in nvim" + exit 0 +} + +search_term() { + case_flag="$1" + shift + + if ! command -v rga >/dev/null 2>&1; then + echo "Error: 'rga' is not installed." >&2 + exit 1 + fi + if ! command -v xclip >/dev/null 2>&1; then + echo "Error: 'xclip' is not installed." >&2 + exit 1 + fi + + # Construct the preview command + preview_cmd=$(printf "rga %s --pretty --context 10 '%s' {}" "$case_flag" "$*") + rga_output=$(rga --follow --no-ignore --hidden --text --max-count=1 ${case_flag:+$case_flag} --files-with-matches --no-messages --glob '!**/.git/*' "$*") + + # Use fzf to select files + files=$(echo "$rga_output" | fzf-tmux +m --preview="$preview_cmd" --reverse --multi --select-1 --exit-0) || return 1 + + # Check if files are selected + if [ -z "$files" ]; then + echo "No files selected." + return 0 + fi + + # copy target to the clipboard + echo "$@" | xclip -selection clipboard 2>/dev/null + + openfiles "$files" + + # print the file names + echo "$rga_output" +} + +# Function to list and/or open all files associated with a given project tag +list_or_open_project_files() { + # Use the provided tag or default to "PROJECT" + project_tag="${1:-PROJECT}: $2" + + # Define the project paths as a space-separated string + project_paths="$HOME/.dotfiles $HOME/.local/src/suckless $HOME/Public/repos" + + # Use rga to find files containing the project tag across all project paths + rga_output="" + for path in $project_paths; do + if [ -d "$path" ]; then + rga_result=$(rga --follow --no-ignore --hidden --text --max-count=1 --files-with-matches --no-messages --glob '!**/.git/*' "$project_tag" "$path") + rga_output="$rga_output $rga_result" + fi + done + + # Remove leading/trailing whitespace + rga_output=$(echo "$rga_output" | sed 's/^[[:space:]]*//;s/[[:space:]]*$//') + + # Check if any files were found + if [ -z "$rga_output" ]; then + echo "No files found for tag $project_tag." + return 0 + fi + + # If the script was called in list mode, simply print the files + if [ "$list_mode" -eq 1 ]; then + echo "$rga_output" + else + # Otherwise, open the files with nvim + set -- "$(printf "%s\n" "$rga_output")" + openfiles "$@" + fi +} + +# Main function to handle options +case_flag="--ignore-case" # Default to case-insensitive +list_mode=0 +project_mode=0 + +# Parse the options +while getopts "silph" opt; do + case $opt in + s) case_flag="--case-sensitive" ;; # Case-sensitive + i) case_flag="--ignore-case" ;; # Case-insensitive + l) list_mode=1 ;; # List mode + p) project_mode=1 ;; # Project mode + h) usage ;; + *) ;; + esac +done + +shift $((OPTIND - 1)) + +# Handle project mode search +if [ "$project_mode" -eq 1 ]; then + list_or_open_project_files "$1" "$2" +else + # Otherwise, call the common search function + search_term "$case_flag" "$@" +fi diff --git a/fedora/.local/bin/shortcuts b/fedora/.local/bin/shortcuts new file mode 100755 index 0000000..ab5e69d --- /dev/null +++ b/fedora/.local/bin/shortcuts @@ -0,0 +1,87 @@ +#!/bin/sh + +bmdirs="${XDG_CONFIG_HOME:-${HOME}/.config}/shell/bm-dirs" +bmfiles="${XDG_CONFIG_HOME:-${HOME}/.config}/shell/bm-files" + +# Output locations. Unactivated progs should go to /dev/null. +shell_shortcuts="${XDG_CONFIG_HOME:-${HOME}/.config}/shell/shortcutrc" +shell_env_shortcuts="${XDG_CONFIG_HOME:-$HOME/.config}/shell/shortcutenvrc" +zsh_named_dirs="${XDG_CONFIG_HOME:-${HOME}/.config}/shell/zshnameddirrc" +command -v lf && lf_shortcuts="${XDG_CONFIG_HOME:-${HOME}/.config}/lf/shortcutrc" || lf_shortcuts="/dev/null" +command -v vim && vim_shortcuts="${XDG_CONFIG_HOME:-${HOME}/.config}/vim/shortcuts.vim" || vim_shortcuts="/dev/null" +command -v nvim && nvim_shortcuts="${XDG_CONFIG_HOME:-${HOME}/.config}/nvim/shortcuts.lua" || nvim_shortcuts="/dev/null" +command -v yazi && yazi_shortcuts="${XDG_CONFIG_HOME:-${HOME}/.config}/yazi/keymap.toml" || yazi_shortcuts="/dev/null" +command -v ranger && ranger_shortcuts="${XDG_CONFIG_HOME:-${HOME}/.config}/ranger/shortcuts.conf" || ranger_shortcuts="/dev/null" +command -v qutebrowser && qute_shortcuts="${XDG_CONFIG_HOME:-${HOME}/.config}/qutebrowser/shortcuts.py" || qute_shortcuts="/dev/null" +command -v fish && fish_shortcuts="${XDG_CONFIG_HOME:-${HOME}/.config}/fish/shortcuts.fish" || fish_shortcuts="/dev/null" +command -v vifm && vifm_shortcuts="${XDG_CONFIG_HOME:-${HOME}/.config}/vifm/shortcuts.rc" || vifm_shortcuts="/dev/null" + +# Remove, prepare files +rm -f "$lf_shortcuts" "$ranger_shortcuts" "$qute_shortcuts" "$zsh_named_dirs" "$vim_shortcuts" "$nvim_shortcuts" "$yazi_shortcuts" 2>/dev/null +printf "# vim: filetype=sh\\n" >"$fish_shortcuts" +printf "# vim: filetype=sh\\nalias " >"$shell_shortcuts" +printf "# vim: filetype=sh\\n" >"$shell_env_shortcuts" +printf "\" vim: filetype=vim\\n" >"$vifm_shortcuts" +cp "$HOME/.config/yazi/keymap-default.toml" "$yazi_shortcuts" + +# Format the `directories` file in the correct syntax and sent it to all three configs. +eval "echo \"$(cat "$bmdirs")\"" | + awk "!/^\s*#/ && !/^\s*\$/ {gsub(\"\\\s*#.*$\",\"\"); + printf(\"%s=\42cd %s && ls -A\42 \\\\\n\",\$1,\$2) >> \"$shell_shortcuts\" ; + printf(\"[ -n \42%s\42 ] && export %s=\42%s\42 \n\",\$1,\$1,\$2) >> \"$shell_env_shortcuts\" ; + printf(\"hash -d %s=%s \n\",\$1,\$2) >> \"$zsh_named_dirs\" ; + printf(\"abbr %s \42cd %s; and ls -A\42\n\",\$1,\$2) >> \"$fish_shortcuts\" ; + printf(\"map g%s :cd %s<CR>\nmap t%s <tab>:cd %s<CR><tab>\nmap M%s <tab>:cd %s<CR><tab>:mo<CR>\nmap Y%s <tab>:cd %s<CR><tab>:co<CR> \n\",\$1,\$2, \$1, \$2, \$1, \$2, \$1, \$2) >> \"$vifm_shortcuts\" ; + printf(\"config.bind(',,%s', \42set downloads.location.directory %s ;; hint links download\42) \n\",\$1,\$2) >> \"$qute_shortcuts\" ; + printf(\"map g%s cd %s\nmap t%s tab_new %s\nmap m%s shell mv -v %%s %s\nmap Y%s shell cp -rv %%s %s \n\",\$1,\$2,\$1,\$2, \$1, \$2, \$1, \$2) >> \"$ranger_shortcuts\" ; + printf(\"map %s cd \42%s\42 \n\",\$1,\$2) >> \"$lf_shortcuts\" ; + printf(\"cmap ;%s %s\n\",\$1,\$2) >> \"$vim_shortcuts\" ; + printf(\"nmap <localleader><localleader>%s :Explore %s<cr>\n\",\$1,\$2) >> \"$vim_shortcuts\" ; + desc_path = \$2; gsub(\"^/home/$USER/\",\"~/\",desc_path); + printf(\"vim.keymap.set('c', ';%s', '%s<cr>', { noremap = true, silent = true, desc = '%s' })\n\", \$1, \$2, desc_path) >> \"$nvim_shortcuts\" ; + printf(\"vim.keymap.set('n', '<localleader><leader>%s', '<cmd>Explore %s<cr>', { noremap = true, silent = true, desc = '%s' })\n\", \$1, \$2, desc_path) >> \"$nvim_shortcuts\" ; + printf(\"vim.keymap.set('n', '<localleader><localleader>%s', function() require('mini.files').open('%s') end, { noremap = true, silent = true, desc = '%s' })\n\", \$1, \$2, desc_path) >> \"$nvim_shortcuts\" ; + desc_path = \$2; gsub(\"^/home/$USER/\",\"~/\",desc_path); + key_array = \"\"; for(i=1; i<=length(\$1); i++) { if(i==1) key_array = \"\\\"\" substr(\$1,i,1) \"\\\"\"; else key_array = key_array \", \\\"\" substr(\$1,i,1) \"\\\"\" } + printf(\"\\t{ on = [ %s ], run = \\\"cd %s\\\", desc = \\\"Go to %s\\\" },\\n\",key_array,\$2,desc_path) >> \"$yazi_shortcuts.tmp\"}" + +# Format the `files` file in the correct syntax and sent it to both configs. +eval "echo \"$(cat "$bmfiles")\"" | + awk "!/^\s*#/ && !/^\s*\$/ {gsub(\"\\\s*#.*$\",\"\"); + printf(\"%s=\42\$EDITOR %s\42 \\\\\n\",\$1,\$2) >> \"$shell_shortcuts\" ; + printf(\"[ -n \42%s\42 ] && export %s=\42%s\42 \n\",\$1,\$1,\$2) >> \"$shell_env_shortcuts\" ; + printf(\"v%s=\42\$EDITOR2 %s\42 \\\\\n\",\$1,\$2) >> \"$shell_shortcuts\" ; + printf(\"hash -d %s=%s \n\",\$1,\$2) >> \"$zsh_named_dirs\" ; + printf(\"abbr %s \42\$EDITOR %s\42 \n\",\$1,\$2) >> \"$fish_shortcuts\" ; + printf(\"abbr v%s \42\$EDITOR2 %s\42 \n\",\$1,\$2) >> \"$fish_shortcuts\" ; + printf(\"map %s :e %s<CR> \n\",\$1,\$2) >> \"$vifm_shortcuts\" ; + printf(\"map %s shell \$EDITOR %s \n\",\$1,\$2) >> \"$ranger_shortcuts\" ; + printf(\"map v%s shell \$EDITOR2 %s \n\",\$1,\$2) >> \"$ranger_shortcuts\" ; + printf(\"map %s \$\$EDITOR \42%s\42 \n\",\$1,\$2) >> \"$lf_shortcuts\" ; + printf(\"map v%s \$\$EDITOR2 \42%s\42 \n\",\$1,\$2) >> \"$lf_shortcuts\" ; + printf(\"cmap ;%s %s\n\",\$1,\$2) >> \"$vim_shortcuts\" ; + printf(\"nmap <localleader><localleader>%s :e %s<cr>\n\",\$1,\$2) >> \"$vim_shortcuts\" ; + desc_path = \$2; gsub(\"^/home/$USER/\",\"~/\",desc_path); + printf(\"vim.keymap.set('c', ';%s', '%s<cr>', { noremap = true, silent = true, desc = '%s' })\n\", \$1, \$2, desc_path) >> \"$nvim_shortcuts\" ; + printf(\"vim.keymap.set('n', '<localleader><localleader>%s', '<cmd>e %s<cr>', { noremap = true, silent = true, desc = '%s' })\n\", \$1, \$2, desc_path) >> \"$nvim_shortcuts\" ; + desc_path = \$2; gsub(\"^/home/$USER/\",\"~/\",desc_path); + key_array = \"\"; for(i=1; i<=length(\$1); i++) { if(i==1) key_array = \"\\\"\" substr(\$1,i,1) \"\\\"\"; else key_array = key_array \", \\\"\" substr(\$1,i,1) \"\\\"\" } + printf(\"\\t{ on = [ %s ], run = [ 'reveal %s', 'open' ], desc = \\\"Open %s\\\" },\\n\", key_array, \$2, desc_path) >> \"$yazi_shortcuts.tmp\" }" + +# Merge bookmarks into keymap-default.toml +if [ -f "$yazi_shortcuts.tmp" ]; then + # Find the line with the closing bracket in the [mgr] section + line_num=$(grep -n "^]" "$yazi_shortcuts" | head -1 | cut -d: -f1) + + # Create the merged file + head -n $((line_num - 1)) "$yazi_shortcuts" >"$yazi_shortcuts.new" + echo "" >>"$yazi_shortcuts.new" + echo " # Custom bookmarks" >>"$yazi_shortcuts.new" + cat "$yazi_shortcuts.tmp" >>"$yazi_shortcuts.new" + echo "]" >>"$yazi_shortcuts.new" + tail -n +$((line_num + 1)) "$yazi_shortcuts" >>"$yazi_shortcuts.new" + + # Replace the original file + mv "$yazi_shortcuts.new" "$yazi_shortcuts" + rm -f "$yazi_shortcuts.tmp" +fi diff --git a/fedora/.local/bin/tmuxcreate b/fedora/.local/bin/tmuxcreate new file mode 100755 index 0000000..5fb5ef3 --- /dev/null +++ b/fedora/.local/bin/tmuxcreate @@ -0,0 +1,42 @@ +#!/bin/sh + +create_new_session() { + session_name=$1 + session_path=${2:-"$PWD"} # Default to current directory if no path is provided + [ -z "$session_name" ] && { printf "New session name: " && read -r session_name; } + if tmux has-session -t "$session_name" 2>/dev/null; then + tmux switch-client -t "$session_name" + else + if [ -n "$TMUX" ]; then + tmux new-session -d -s "$session_name" -c "$session_path" + tmux switch-client -t "$session_name" + else + tmux new -s "$session_name" -c "$session_path" + fi + fi +} + +if [ $# -gt 0 ]; then + if [ -d "$1" ]; then + create_new_session "$(basename "$1")" "$1" + else + create_new_session "$1" + fi +else + # Capture the output of tmux ls + sessions=$(tmux ls 2>/dev/null) + if [ -z "$sessions" ]; then + create_new_session + else + session=$( ( + echo "$sessions" + echo "[new session]" + ) | fzf-tmux --reverse | cut -d: -f1) + [ -z "$session" ] && exit + if [ "$session" = "[new session]" ]; then + create_new_session + else + tmux attach -t "$session" + fi + fi +fi diff --git a/fedora/.local/bin/tmuxcycleborder b/fedora/.local/bin/tmuxcycleborder new file mode 100755 index 0000000..ad2a430 --- /dev/null +++ b/fedora/.local/bin/tmuxcycleborder @@ -0,0 +1,7 @@ +#!/bin/sh + +case "$(tmux show-option -gqv pane-border-status)" in +"off") tmux set-option -g pane-border-status top ;; +"top") tmux set-option -g pane-border-status bottom ;; +"bottom") tmux set-option -g pane-border-status off ;; +esac diff --git a/fedora/.local/bin/tmuxopen b/fedora/.local/bin/tmuxopen new file mode 100755 index 0000000..5362215 --- /dev/null +++ b/fedora/.local/bin/tmuxopen @@ -0,0 +1,208 @@ +#!/bin/sh + +wrapper() { + usage() { + echo "Search for files and open them in Neovim within tmux panes." + echo "" + echo "Usage: tmuxopen [OPTIONS]" + echo "" + echo "Options:" + echo " -h, --help : Show this help message" + echo "" + echo "Controls:" + echo " Tab Select files" + echo " Ctrl+f Search filenames" + echo " Ctrl+g Search file contents" + echo " Ctrl+d Search directories" + echo "" + echo "Environment Variables:" + echo " NVIM_SEARCH_REGISTRY Set to the search query, allowing Neovim to highlight matches" + echo "" + echo "Example:" + echo " tmuxopen # Run the normal search and open" + } + + get_fzf_output() { + # Create temporary files to store search state + tmp_files="/tmp/search-files-$$" + tmp_content_query="/tmp/search-content-query-$$" + + # Cleanup on exit + trap "rm -f $tmp_files $tmp_content_query" EXIT + + rg_fixed_bind="ctrl-g:transform-query( + echo {q} > $tmp_content_query; + echo {q} + )+reload( + rm -f $tmp_files; + rg --line-number --follow --fixed-strings --hidden --no-heading --color=always --smart-case --glob '!**/.git/**' --glob '!node_modules/**' {q} 2>/dev/null || true + )" + file_bind="ctrl-f:transform-query( + current_query={q}; + if [ ! -s $tmp_content_query ]; then + echo \$current_query > $tmp_content_query; + fi; + rg --hidden --follow --files-with-matches --no-messages --glob '!**/.git/**' --glob '!node_modules/**' -- \$current_query > $tmp_files; + )+reload( + if [ -s $tmp_files ]; then + if [ -n {q} ]; then + grep -i -- {q} $tmp_files || true; + else + cat $tmp_files; + fi | while IFS= read -r file; do + if [ -f \"\$file\" ]; then + echo \"\$file:1\"; + fi; + done; + else + echo 'No matching files found'; + fi + )" + if command -v fd >/dev/null 2>&1; then + dir_bind="ctrl-d:change-prompt(📁 )+reload(fd --follow --type d --hidden --absolute-path --color never --exclude .git --exclude node_modules --search-path \"\$PWD\")" + else + dir_bind="ctrl-d:change-prompt(📁 )+reload(find \"\$PWD\" -L -type d -name node_modules -prune -o -name .git -prune -o -type d -print)" + fi + + rg --line-number --follow --no-heading --color=always --smart-case --glob '!**/.git/**' --glob '!LICENSE' '' 2>/dev/null | + fzf-tmux \ + --ansi --multi --delimiter : \ + --reverse \ + --print-query \ + --preview 'bat --style=numbers --color=always --highlight-line {2} {1} 2>/dev/null || bat --color=always {} 2>/dev/null || ls -la {} 2>/dev/null || echo "Preview is not available."' \ + --preview-window 'right,55%,border-bottom,+{2}+3/3,~3' \ + --bind "$file_bind" \ + --bind "$rg_fixed_bind" \ + --bind "$dir_bind" \ + --bind 'ctrl-c:abort' \ + --header "^f filenames | ^g contents | ^d directories" \ + --prompt "🔎 " + } + + set_nvim_search_variable() { + raw_output="$1" + tmp_content_query="/tmp/search-content-query-$$" + if [ -f "$tmp_content_query" ]; then + saved_query=$(cat "$tmp_content_query" 2>/dev/null) + if [ -n "$saved_query" ]; then + export NVIM_SEARCH_REGISTRY="$saved_query" + return + fi + fi + query=$(echo "$raw_output" | head -n1) + export NVIM_SEARCH_REGISTRY="$query" + } + + open_files_in_nvim() { + pane="$1" + shift + file_indices="$*" + nvim_cmd="nvim" + for index in $file_indices; do + file=$(echo "$files" | awk -v idx="$index" '{print $idx}') + line=$(echo "$lines" | awk -v idx="$index" '{print $idx}') + nvim_cmd="$nvim_cmd +$line $file" + done + nvim_cmd="$nvim_cmd -c 'let @/=\"$NVIM_SEARCH_REGISTRY\"'" + tmux send-keys -t "$pane" "$nvim_cmd" C-m + } + + # Parse command line arguments + while [ "$#" -gt 0 ]; do + case "$1" in + -h | --help) + usage + exit 0 + ;; + *) + echo "Unknown option: $1" >&2 + usage + exit 1 + ;; + esac + done + + raw_output=$(get_fzf_output) + set_nvim_search_variable "$raw_output" + + # Split the newline-delimited output into an array, skipping the first line (query) + selections=$(echo "$raw_output" | sed 1d) + + if [ -z "$selections" ]; then + echo "No selections made" + exit 0 + fi + + files="" + lines="" + count=0 + + # Use a here document to avoid subshell issues + while IFS= read -r selection; do + file=$(echo "$selection" | awk -F: '{print $1}') + line=$(echo "$selection" | awk -F: '{print $2}') + if [ -f "$file" ]; then + files="$files $file" + lines="$lines $line" + count=$((count + 1)) + else + echo "File not found: $file" + fi + done <<EOF +$selections +EOF + + if [ "$count" -eq 0 ]; then + echo "No valid files selected" + exit 0 + fi + + if [ "$count" -eq 1 ]; then + open_files_in_nvim "$(tmux display-message -p '#P')" 1 + else + window_name="$(date +%s)" + tmux new-window -n "$window_name" + case "$count" in + 2) + tmux split-window -t "$window_name" -h -p 50 + open_files_in_nvim "$window_name.1" 1 + open_files_in_nvim "$window_name.2" 2 + tmux select-pane -t "$window_name.1" + ;; + 3) + tmux split-window -t "$window_name" -h -p 50 + tmux split-window -t "$window_name.2" -v -p 50 + open_files_in_nvim "$window_name.1" 1 + open_files_in_nvim "$window_name.2" 2 + open_files_in_nvim "$window_name.3" 3 + ;; + *) + tmux split-window -t "$window_name" -h -p 50 + tmux split-window -t "$window_name.1" -v -p 50 + tmux split-window -t "$window_name.3" -v -p 50 + open_files_in_nvim "$window_name.1" 1 + open_files_in_nvim "$window_name.2" 2 + open_files_in_nvim "$window_name.3" 3 + remaining_indices="" + for i in $(seq 4 "$count"); do + remaining_indices="$remaining_indices $i" + done + open_files_in_nvim "$window_name.4" "$remaining_indices" + ;; + esac + fi +} + +for cmd in rg fzf bat tmux nvim; do + if ! command -v $cmd >/dev/null 2>&1; then + echo "Error: $cmd not found" >&2 + exit 1 + fi +done + +if [ -z "$TMUX" ]; then + echo "Error: Not in a tmux session" >&2 + exit 1 +fi + +wrapper "$@" diff --git a/fedora/.local/bin/tmuxtogglebar b/fedora/.local/bin/tmuxtogglebar new file mode 100755 index 0000000..2ae045e --- /dev/null +++ b/fedora/.local/bin/tmuxtogglebar @@ -0,0 +1,6 @@ +#!/bin/sh + +case "$(tmux show-option -gqv status)" in +on) tmux set-option -g status off ;; +off) tmux set-option -g status on ;; +esac diff --git a/fedora/.local/bin/tmuxtoggleterm b/fedora/.local/bin/tmuxtoggleterm new file mode 100755 index 0000000..f21f833 --- /dev/null +++ b/fedora/.local/bin/tmuxtoggleterm @@ -0,0 +1,11 @@ +#!/bin/sh + +export TMUX_PANE_DIRECTION="bottom" + +if [ "$TMUX_PANE_DIRECTION" = "bottom" ]; then + tmux select-pane -U +elif [ "$TMUX_PANE_DIRECTION" = "right" ]; then + tmux select-pane -L +fi + +tmux resize-pane -Z diff --git a/mac/.gnupg/gpg-agent.conf b/mac/.gnupg/gpg-agent.conf new file mode 100644 index 0000000..be889cc --- /dev/null +++ b/mac/.gnupg/gpg-agent.conf @@ -0,0 +1,5 @@ +allow-preset-passphrase +enable-ssh-support +default-cache-ttl 86400 +max-cache-ttl 86400 +pinentry-program /opt/homebrew/bin/pinentry-mac |
