1
1
Fork 1
mirror of https://github.com/oddlama/nix-config.git synced 2025-10-10 23:00:39 +02:00

refactor: split "real" modules and "config" modules

This commit is contained in:
oddlama 2024-05-25 17:56:30 +02:00
parent 045f15239a
commit cceae6c63c
No known key found for this signature in database
GPG key ID: 14EFE510775FE39A
60 changed files with 126 additions and 113 deletions

View file

@ -0,0 +1,42 @@
{...}: {
imports = [
./starship.nix
./nushell
./zsh
];
programs.zoxide = {
enable = true;
options = ["--cmd p"];
};
# nix-index-database is enabled globally for each user in modules/config/home-manager.nix
programs.nix-index.enable = true;
programs.nix-index.enableZshIntegration = false;
programs.nix-index-database.comma.enable = true;
home.persistence."/state".directories = [
".local/share/zoxide"
];
home.shellAliases = {
l = "ls -lahF --group-directories-first --show-control-chars --quoting-style=escape --color=auto";
t = "tree -F --dirsfirst -L 2";
tt = "tree -F --dirsfirst -L 3 --filelimit 16";
cpr = "rsync -axHAWXS --numeric-ids --info=progress2";
md = "mkdir";
rmd = "rm --one-file-system -d";
cp = "cp -vi";
mv = "mv -vi";
rm = "rm --one-file-system -I";
chmod = "chmod -c --preserve-root";
chown = "chown -c --preserve-root";
nb = "nix build --no-link --print-out-paths";
ip = "ip --color";
tmux = "tmux -2";
rg = "rg -S";
};
}

View file

@ -0,0 +1,39 @@
# TODO only partially isolate, don't live reload history when other shells save
# TODO git status
# TODO fzf fuzzy
# TODO isolation = false -> no session id is even generated... sad
# TODO nix command completion
$env.config = {
show_banner: false
history: {
max_size: 10000000
file_format: "sqlite"
# Not writing history on enter is meh, but I want shells to only have
# access to the history up to the point where it was started.
# XXX: broken with sqlite. https://github.com/nushell/nushell/issues/7915
sync_on_enter: false
# but each shell should have an effective isolated buffer
# XXX: todo this currently isolates completely, so no access to prev history at all.
# instead, this should prevent live reloading history when other shells sync it.
isolation: false
}
completions: {
case_sensitive: false
quick: true
partial: true
algorithm: "prefix"
external: {
enable: true
max_results: 200
completer: null
}
}
cd: {
abbreviations: true
}
shell_integration: true
}

View file

@ -0,0 +1,16 @@
{
lib,
minimal,
...
}:
lib.optionalAttrs (!minimal) {
programs.nushell = {
enable = true;
configFile.source = ./config.nu;
envFile.source = ./env.nu;
};
home.persistence."/persist".directories = [
".config/nushell"
];
}

View file

View file

@ -0,0 +1,154 @@
{
config,
lib,
pkgs,
...
}:
with lib; let
cfg = config.programs.starship;
tomlFormat = pkgs.formats.toml {};
starshipCmd = "${config.home.profileDirectory}/bin/starship";
in {
meta.maintainers = [];
options.programs.starship = {
enable = mkEnableOption "starship";
package = mkOption {
type = types.package;
default = pkgs.starship;
defaultText = literalExpression "pkgs.starship";
description = "The package to use for the starship binary.";
};
settings = mkOption {
type = with types; let
prim = either bool (either int str);
primOrPrimAttrs = either prim (attrsOf prim);
entry = either prim (listOf primOrPrimAttrs);
entryOrAttrsOf = t: either entry (attrsOf t);
entries = entryOrAttrsOf (entryOrAttrsOf (entryOrAttrsOf entry));
in
attrsOf entries // {description = "Starship configuration";};
default = {};
example = literalExpression ''
{
add_newline = false;
format = lib.concatStrings [
"$line_break"
"$package"
"$line_break"
"$character"
];
scan_timeout = 10;
character = {
success_symbol = "";
error_symbol = "";
};
}
'';
description = ''
Configuration written to
{file}`$XDG_CONFIG_HOME/starship.toml`.
See <https://starship.rs/config/> for the full list
of options.
'';
};
enableBashIntegration =
mkEnableOption "Bash integration"
// {
default = true;
};
enableZshIntegration =
mkEnableOption "Zsh integration"
// {
default = true;
};
enableFishIntegration =
mkEnableOption "Fish integration"
// {
default = true;
};
enableIonIntegration =
mkEnableOption "Ion integration"
// {
default = true;
};
enableNushellIntegration =
mkEnableOption "Nushell integration"
// {
default = true;
};
enableTransience = mkOption {
type = types.bool;
default = false;
description = ''
The TransientPrompt feature of Starship replaces previous prompts with a
custom string. This is only a valid option for the Fish shell.
For documentation on how to change the default replacement string and
for more information visit
https://starship.rs/advanced-config/#transientprompt-and-transientrightprompt-in-cmd
'';
};
};
config = mkIf cfg.enable {
home.packages = [cfg.package];
xdg.configFile."starship.toml" = mkIf (cfg.settings != {}) {
source = tomlFormat.generate "starship-config" cfg.settings;
};
programs.bash.initExtra = mkIf cfg.enableBashIntegration ''
if [[ $TERM != "dumb" ]]; then
eval "$(${starshipCmd} init bash --print-full-init)"
fi
'';
programs.zsh.initExtra = mkIf cfg.enableZshIntegration ''
if [[ $TERM != "dumb" ]]; then
eval "$(${starshipCmd} init zsh)"
fi
'';
programs.fish.interactiveShellInit = mkIf cfg.enableFishIntegration ''
if test "$TERM" != "dumb"
eval (${starshipCmd} init fish)
${lib.optionalString cfg.enableTransience "enable_transience"}
end
'';
programs.ion.initExtra = mkIf cfg.enableIonIntegration ''
if test $TERM != "dumb"
eval $(${starshipCmd} init ion)
end
'';
programs.nushell = mkIf cfg.enableNushellIntegration {
# Unfortunately nushell doesn't allow conditionally sourcing nor
# conditionally setting (global) environment variables, which is why the
# check for terminal compatibility (as seen above for the other shells) is
# not done here.
extraEnv = ''
let starship_cache = "${config.xdg.cacheHome}/starship"
if not ($starship_cache | path exists) {
mkdir $starship_cache
}
${starshipCmd} init nu | save --force ${config.xdg.cacheHome}/starship/init.nu
'';
extraConfig = ''
source ${config.xdg.cacheHome}/starship/init.nu
'';
};
};
}

View file

@ -0,0 +1,128 @@
{
lib,
pkgs,
...
}: {
disabledModules = ["programs/starship.nix"];
imports = [./starship-module.nix];
programs.starship = {
enable = true;
package = let
src = pkgs.fetchFromGitHub {
owner = "oddlama";
repo = "starship";
rev = "feat-more-dynamic-username-and-hostname";
hash = "sha256-afZO5WSVy9hWRz8Mki3ayCwdvZDZt9L1yegrjRnqYko=";
};
in
pkgs.starship.overrideAttrs (_finalAttrs: previousAttrs: {
inherit src;
cargoDeps = previousAttrs.cargoDeps.overrideAttrs (_: {
inherit src;
outputHash = "sha256-bmswPBJi2YpnhnS77S++/+SQnlerWWRqFZPCZkBUeFg=";
});
});
settings = {
add_newline = false;
format = lib.concatStrings [
"$username"
"$hostname"
" $directory "
"($git_branch )"
"($git_commit )"
"$git_state"
"$git_status"
"$character"
];
right_format = lib.concatStrings [
"($status )"
"($cmd_duration )"
"($jobs )"
"($python )"
"($rust )"
"$time"
];
command_timeout = 60; # 60ms must be enough. I like a responsive prompt more than additional git information.
username = {
format = "[$user]($style) ";
show_if_root = false;
show_if_ssh = false;
style = "yellow";
};
hostname = {
format = "[$hostname]($style)[$ssh_symbol](green)";
ssh_only = false;
ssh_symbol = " 󰣀";
style = "bold purple";
user_overrides.root.style = "bold red";
};
directory = {
format = "[$path]($style)[$read_only]($read_only_style)";
fish_style_pwd_dir_length = 1;
style = "bold blue";
};
character = {
success_symbol = "\\$";
error_symbol = "\\$";
vimcmd_symbol = "[](bold green)";
vimcmd_replace_one_symbol = "[](bold purple)";
vimcmd_replace_symbol = "[](bold purple)";
vimcmd_visual_symbol = "[](bold yellow)";
};
git_branch = {
format = "[$symbol$branch]($style)";
symbol = " ";
style = "green";
};
git_commit = {
commit_hash_length = 8;
format = "[$hash$tag]($style)";
style = "green";
};
git_status = {
conflicted = "$count";
ahead = "$count";
behind = "$count";
diverged = "$ahead_count$behind_count";
untracked = "?$count";
stashed = "\\$$count";
modified = "!$count";
staged = "+$count";
renamed = "$count";
deleted = "-$count";
format = lib.concatStrings [
"[($conflicted )](red)"
"[($stashed )](magenta)"
"[($staged )](green)"
"[($deleted )](red)"
"[($renamed )](blue)"
"[($modified )](yellow)"
"[($untracked )](blue)"
"[($ahead_behind )](green)"
];
};
status = {
disabled = false;
pipestatus = true;
pipestatus_format = "$pipestatus => [$int( $signal_name)]($style)";
pipestatus_separator = "[|]($style)";
pipestatus_segment_format = "[$status]($style)";
format = "[$status( $signal_name)]($style)";
style = "red";
};
python = {
format = "[$symbol$pyenv_prefix($version )(\($virtualenv\) )]($style)";
};
cmd_duration = {
format = "[ $duration]($style)";
style = "yellow";
};
time = {
format = "[ $time]($style)";
style = "cyan";
disabled = false;
};
};
};
}

View file

@ -0,0 +1,64 @@
{
lib,
pkgs,
...
}: {
# Needed in path for zsh-histdb
home.packages = [pkgs.sqlite];
programs.zsh = {
enable = true;
envExtra = ''
umask 077
'';
dotDir = ".config/zsh";
history = {
path = "\${XDG_DATA_HOME-$HOME/.local/share}/zsh/history";
save = 1000500;
size = 1000000;
};
initExtra = lib.readFile ./zshrc;
initExtraFirst = ''
HISTDB_FILE=''${XDG_DATA_HOME-$HOME/.local/share}/zsh/history.db
# Do this early so fast-syntax-highlighting can wrap and override this
if autoload history-search-end; then
zle -N history-beginning-search-backward-end history-search-end
zle -N history-beginning-search-forward-end history-search-end
fi
'';
plugins = [
{
# Must be before plugins that wrap widgets, such as zsh-autosuggestions or fast-syntax-highlighting
name = "fzf-tab";
src = "${pkgs.zsh-fzf-tab}/share/fzf-tab";
}
{
name = "fast-syntax-highlighting";
src = "${pkgs.zsh-fast-syntax-highlighting}/share/zsh/site-functions";
}
{
name = "zsh-autosuggestions";
file = "zsh-autosuggestions.zsh";
src = "${pkgs.zsh-autosuggestions}/share/zsh-autosuggestions";
}
{
name = "zsh-histdb";
src = pkgs.fetchFromGitHub {
owner = "larkery";
repo = "zsh-histdb";
rev = "30797f0c50c31c8d8de32386970c5d480e5ab35d";
hash = "sha256-PQIFF8kz+baqmZWiSr+wc4EleZ/KD8Y+lxW2NT35/bg=";
};
}
{
name = "zsh-histdb-skim";
src = "${pkgs.zsh-histdb-skim}/share/zsh-histdb-skim";
}
];
};
home.persistence."/persist".directories = [
".local/share/zsh" # History
];
}

View file

@ -0,0 +1,320 @@
autoload -U add-zle-hook-widget
# autosuggests otherwise breaks these widgets.
# See https://github.com/zsh-users/zsh-autosuggestions/issues/619
ZSH_AUTOSUGGEST_CLEAR_WIDGETS+=(history-beginning-search-backward-end history-beginning-search-forward-end)
# --------------------------------------------------------------------------------
# FZF widgets
function __fzf() {
if [[ -n "$TMUX_PANE" && ( "${FZF_TMUX:-0}" != 0 || -n "$FZF_TMUX_OPTS" ) ]]; then
fzf-tmux -d"${FZF_TMUX_HEIGHT:-40%}" -- "$@"
else
fzf "$@"
fi
}
function __fzf_select() {
setopt localoptions pipefail no_aliases 2>/dev/null
local item
FZF_DEFAULT_OPTS="--height ${FZF_TMUX_HEIGHT:-40%} --reverse --bind=ctrl-z:ignore,tab:down,btab:up,change:top,ctrl-space:toggle $FZF_DEFAULT_OPTS" __fzf "$@" | while read item; do
echo -n "${(q)item} "
done
local ret=$?
echo
return $ret
}
function __fzf_find_files() {
local include_hidden=${1:-0}
local types=${2:-fdl}
shift 2
local type_selectors=()
local i
for (( i=0; i<${#types}; i++ )); do
[[ "$i" -gt 0 ]] && type_selectors+=('-o')
type_selectors+=('-type' "${types:$i:1}")
done
local hide_hidden_files=()
if [[ $include_hidden == "0" ]]; then
hide_hidden_files=('-path' '*/\.*' '-o')
fi
setopt localoptions pipefail no_aliases 2>/dev/null
command find -L . -mindepth 1 \
\( "${hide_hidden_files[@]}" -fstype 'sysfs' -o -fstype 'devfs' -o -fstype 'devtmpfs' -o -fstype 'proc' \) -prune \
-o \( "${type_selectors[@]}" \) -print \
| __fzf_select "$@"
}
function __fzf_find_files_widget_helper() {
LBUFFER="${LBUFFER}$(__fzf_find_files "$@")"
local ret=$?
zle reset-prompt
return $ret
}
function fzf-select-file-or-dir() { __fzf_find_files_widget_helper 0 fdl -m; }; zle -N fzf-select-file-or-dir
function fzf-select-file-or-dir-hidden() { __fzf_find_files_widget_helper 1 fdl -m; }; zle -N fzf-select-file-or-dir-hidden
function fzf-select-dir() { __fzf_find_files_widget_helper 0 d -m; }; zle -N fzf-select-dir
function fzf-select-dir-hidden() { __fzf_find_files_widget_helper 1 d -m; }; zle -N fzf-select-dir-hidden
function fzf-cd() {
local dir="$(__fzf_find_files 0 d +m)"
if [[ -z "$dir" ]]; then
zle redisplay
return 0
fi
zle push-line # Clear buffer. Auto-restored on next prompt.
BUFFER="cd -- $dir"
zle accept-line
local ret=$?
unset dir # ensure this doesn't end up appearing in prompt expansion
zle reset-prompt
return $ret
}
zle -N fzf-cd
# --------------------------------------------------------------------------------
# Keybinds
# Reset all keybinds and use "emacs" keybinds
bindkey -d
bindkey -e
function nop() {
true
}; zle -N nop
function bindkeys() {
[[ "$#" -eq 2 ]] || return
local keys="$1"
local key
for key in ${(P)keys}; do
bindkey "$key" "$2"
done
}
function setup_keybinds() {
local keys_Home=( "${terminfo[khome]}" '\eOH' '\e[H')
local keys_End=( "${terminfo[kend]}" '\eOF' '\e[F')
local keys_Insert=( "${terminfo[kich1]}" '\e[2~')
local keys_Tab=( "${terminfo[ht]}" '\t')
local keys_ShiftTab=( "${terminfo[kcbt]}" '\eOZ' '\e[Z')
local keys_Backspace=( "${terminfo[kbs]}" '^?')
local keys_CtrlBackspace=( "${terminfo[cub1]}" '^H')
local keys_AltBackspace=( '\e^?')
local keys_Delete=( "${terminfo[kdch1]}" '\e[3~')
local keys_ShiftDelete=( "${terminfo[kDC]}" '\e[3;2~')
local keys_CtrlDelete=( '\e[3;5~')
local keys_AltDelete=( '\e[3;3~')
local keys_Up=( "${terminfo[kcuu1]}" '\eOA' '\e[A')
local keys_ShiftUp=( "${terminfo[kri]}" '\e[1;2A')
local keys_CtrlUp=( '\e[1;5A')
local keys_AltUp=( '\e[1;3A')
local keys_Down=( "${terminfo[kcud1]}" '\eOB' '\e[B')
local keys_ShiftDown=( "${terminfo[kind]}" '\e[1;2B')
local keys_CtrlDown=( '\e[1;5B')
local keys_AltDown=( '\e[1;3B')
local keys_Right=( "${terminfo[kcuf1]}" '\eOC' '\e[C')
local keys_ShiftRight=( "${terminfo[kRIT]}" '\e[1;2C')
local keys_CtrlRight=( '\e[1;5C')
local keys_AltRight=( '\e[1;3C')
local keys_Left=( "${terminfo[kcub1]}" '\eOD' '\e[D')
local keys_ShiftLeft=( "${terminfo[kLFT]}" '\e[1;2D')
local keys_CtrlLeft=( '\e[1;5D')
local keys_AltLeft=( '\e[1;3D')
local keys_PageUp=( "${terminfo[kpp]}" '\e[5~')
local keys_ShiftPageUp=( "${terminfo[kPRV]}" '\e[5;2~')
local keys_PageDown=( "${terminfo[knp]}" '\e[6~')
local keys_ShiftPageDown=( "${terminfo[kNXT]}" '\e[6;2~')
bindkeys keys_Home beginning-of-line
bindkeys keys_End end-of-line
bindkeys keys_Insert nop
bindkeys keys_Tab fzf-tab-complete
bindkeys keys_ShiftTab nop
bindkeys keys_Backspace backward-delete-char
bindkeys keys_AltBackspace backward-kill-word
bindkeys keys_CtrlBackspace backward-kill-line
bindkeys keys_Delete delete-char
bindkeys keys_ShiftDelete delete-word
bindkeys keys_CtrlDelete kill-line
bindkeys keys_AltDelete delete-word
bindkeys keys_Up history-beginning-search-backward-end
bindkeys keys_ShiftUp up-line
bindkeys keys_CtrlUp nop
bindkeys keys_AltUp nop
bindkeys keys_Down history-beginning-search-forward-end
bindkeys keys_ShiftDown down-line
bindkeys keys_CtrlDown nop
bindkeys keys_AltDown nop
bindkeys keys_Right forward-char
bindkeys keys_ShiftRight forward-word
bindkeys keys_CtrlRight nop
bindkeys keys_AltRight nop
bindkeys keys_Left backward-char
bindkeys keys_ShiftLeft backward-word
bindkeys keys_CtrlLeft nop
bindkeys keys_AltLeft nop
bindkeys keys_PageUp nop
bindkeys keys_ShiftPageUp nop
bindkeys keys_PageDown nop
bindkeys keys_ShiftPageDown nop
# fzf file and directory related expansions and functions
bindkey '\ef' fzf-select-file-or-dir
bindkey '\eF' fzf-select-file-or-dir-hidden
bindkey '\ed' fzf-select-dir
bindkey '\eD' fzf-select-dir-hidden
bindkey '\ec' fzf-cd
# fuzzy history search
bindkey '^R' histdb-skim-widget
# autosuggest Ctrl+space = accept
bindkey '^ ' autosuggest-accept
}
setup_keybinds
unfunction setup_keybinds
unfunction bindkeys
# --------------------------------------------------------------------------------
# Completion
# disable sort when completing `git checkout`
zstyle ':completion:*:git-checkout:*' sort false
# set descriptions format to enable group support
zstyle ':completion:*:descriptions' format '[%d]'
# set list-colors to enable filename colorizing
zstyle ':completion:*' list-colors ${(s.:.)LS_COLORS}
# preview directory's content when completing cd
zstyle ':fzf-tab:complete:cd:*' fzf-preview 'ls -lAhF --group-directories-first --show-control-chars --quoting-style=escape --color=always $realpath'
zstyle ':fzf-tab:complete:cd:*' popup-pad 20 0
# No correction
zstyle ':completion:*' completer _oldlist _expand _complete _files _ignored
# Don't insert tabs when there is no completion (e.g. beginning of line)
zstyle ':completion:*' insert-tab false
# allow one error for every three characters typed in approximate completer
zstyle ':completion:*:approximate:' max-errors 'reply=( $((($#PREFIX+$#SUFFIX)/3 )) numeric )'
# start menu completion only if it could find no unambiguous initial string
zstyle ':completion:*:correct:*' insert-unambiguous true
zstyle ':completion:*:corrections' format $'%{\e[0;31m%}%d (errors: %e)%{\e[0m%}'
zstyle ':completion:*:correct:*' original true
# List directory completions first
zstyle ':completion:*' list-dirs-first true
# Offer the original completion when using expanding / approximate completions
zstyle ':completion:*' original true
# Treat multiple slashes as a single / like UNIX does (instead of as /*/)
zstyle ':completion:*' squeeze-slashes true
# insert all expansions for expand completer
# # ???????????????ßß
zstyle ':completion:*:expand:*' tag-order all-expansions
# match uppercase from lowercase
zstyle ':completion:*' matcher-list 'm:{a-z}={A-Z}'
# separate matches into groups
zstyle ':completion:*:matches' group 'yes'
zstyle ':completion:*' group-name ''
zstyle ':completion:*:messages' format '%d'
zstyle ':completion:*:options' auto-description '%d'
# describe options in full
zstyle ':completion:*:options' description 'yes'
# on processes completion complete all user processes
zstyle ':completion:*:processes' command 'ps -au$USER'
# provide verbose completion information
zstyle ':completion:*' verbose true
# Ignore completion functions for commands you don't have:
zstyle ':completion::(^approximate*):*:functions' ignored-patterns '_*'
# Provide more processes in completion of programs like killall:
zstyle ':completion:*:processes-names' command 'ps c -u ${USER} -o command | uniq'
# complete manual by their section
zstyle ':completion:*:manuals' separate-sections true
zstyle ':completion:*:manuals.*' insert-sections true
zstyle ':completion:*:man:*' menu yes select
# provide .. as a completion
zstyle ':completion:*' special-dirs ..
# --------------------------------------------------------------------------------
# ZSH Options
# Ignore certain commands in history
HISTORY_IGNORE_REGEX='^(.|. |..|.. |rm .*|rmd .*|git fixup.*|git unstash|git stash.*|git checkout -f.*)$'
function zshaddhistory() {
emulate -L zsh
[[ ! $1 =~ "$HISTORY_IGNORE_REGEX" ]]
}
# Emit an error when a glob has no match
setopt nomatch
# Don't use extended globbing
setopt noextendedglob
# * shouldn't match dotfiles. ever.
setopt noglobdots
# Whenever a command completion is attempted, make sure the entire
# command path is hashed first.
setopt hash_list_all
# Change directory by typing the directory name
setopt auto_cd
# Automatically pushd on cd to have a directory stack
setopt auto_pushd
# Don't push the same dir twice
setopt pushd_ignore_dups
# Display PID when suspending processes as well
setopt long_list_jobs
# Don't send SIGHUP to background processes when the shell exits
setopt nohup
# Report the status of background jobs immediately
setopt notify
# Allow comments in interactive shells
setopt interactive_comments
# Don't beep
setopt nobeep
# Don't try to correct inputs
setopt nocorrect
# Allow in-word completion
setopt complete_in_word
# Don't autocorrect commands
setopt no_correct_all
# List choices on ambiguous completions
setopt auto_list
# Use menu completion if requested explicitly
setopt auto_menu
# Move cursor to end of word if there was only one match
setopt always_to_end