🏗️ 我的Nix/NixOS配置详细文档正在施工中,完成进度:46/279 🏗️

为了更好的文档阅读体验,请看GitHub Pages的版本。

目录

Nix/NixOS简介

Nix是一个可重现的(Reproducible)包管理器,也是一门纯函数式的(Pure Functional)编程语言。 理论上讲,Nix包管理器可以安装在任何Linux发行版上(比如Ubuntu、Debian和Arch等),并与这些发行版原有的包管理器(比如snap、apt和pacman等)共存。 而NixOS则是完全由Nix包管理器进行管理的Linux发行版。

Nix/NixOS采用了“包(Package)”的理念,将Linux内核、驱动、函数库、用户程序、配置文件等方方面面抽象出来。 这类似于Linux内核将设备、磁盘文件、管道等都抽象为文件的理念。 这样的抽象使得Nix/NixOS能以一种统一的方式管理所有的包。

为了防止“包”被用户有意或无意地修改(即保证可重现性),Nix/NixOS将所有的包都放在一个只读文件系统中(挂载在/nix/store目录上)。 这个目录中的包仅能通过Nix包管理器和Nix语言编程进行增删改。 为了将/nix/store中的文件放置在它们应该在的地方(比如某个用户使用的包里存在bin/目录,则应当把bin/中所有的文件放入/run/current-system/sw/bin/),Nix/NixOS大量使用符号链接。

上述Nix/NixOS的特点和传统Linux发行版有着极大的区别。 这使得Nix/NixOS的学习曲线十分陡峭。 不过当你适应Nix/NixOS的这些特点后,它可以极大提升工程效率!

xieby1和Nix/NixOS

多年来,Nix/NixOS已成为我学习和工作的重要基础,主要用于以下方面:

  • 学习Linux。 Nix/NixOS采用了“包(Package)”的理念,将Linux内核、驱动、函数库、用户程序、配置文件等方方面面抽象出来。 通过学习Nix语言,我能够以统一的方式了解Linux系统的各个方面,这是其他工具所无法提供的。
  • 管理环境。 通过使用nix-shell管理所有依赖(包括库、环境变量、配置等),可以避免项目环境重现的问题。 类似的工具还有虚拟机和Docker。 相比使用虚拟机,它更轻量。 相比Docker,它支持可复现构建,采用Nix语言更灵活。 详细可见我于2023年为实验室同学们准备的推荐Nix/NixOS的幻灯片。
  • 备份电脑。 Nix/NixOS能够管理系统、软件及其配置。 虽然Nix/NixOS不直接管理数据,但Nix/NixOS可以很好地管理数据同步软件,比如Syncthing。 因此只要保留着Nix/NixOS的配置文件(由Nix语言编写),就能恢复出一个几乎一模一样1的软件环境/操作系统。

xieby1的Nix/NixOS配置

这个仓库Github: xieby1/nix_config里存放着我的Nix/NixOS配置和文档。 该仓库使用nix expression,而非nix flakes; 通过npins固定nixpkgs-unstable、home-manager master和NUR main, 以便使用最新功能。 该仓库的配置在多个平台都可以正常使用:

  • NixOS: QEMU✅,NixOS单系统✅,NixOS+Windows双系统✅
  • Nix: Linux✅,安卓(nix-on-droid)✅,WSL2✅

你可以使用该仓库的配置,配置出完整NixOS操作系统。 也可以使用其中的部分包、模块,扩充自己的Nix/NixOS。 若你不仅只是想安装Nix/NixOS,还想了解更多Nix/NixOS的知识, 欢迎看看这个仓库的文档xieby1.github.io/nix_config。

文件夹结构

  • docs/: 文档
  • scripts/: nix脚本
    • fhs-shell/: 采用FHS的nix-shell脚本
    • shell/: nix-shell脚本
    • pkgs/: 独立的软件包脚本
  • sys/: 系统总体配置(nixos-rebuild的配置)
    • cli/: 系统命令行配置
    • gui/: 系统图形配置
    • modules/: 系统模块
  • usr/: 用户总体配置(home-manager的配置)
    • cli/: 用户命令行配置
    • gui/: 用户图形配置
    • modules/: 用户模块
  • nix-on-droid.nix: 安卓总体配置(nix-on-droid的配置)
  • modules/: nixos/home-manager通用的模块

nix脚本的使用方法

安装Nix不在此赘述,参考nixos.org/download.html。

安装完Nix后,下载所需的nix脚本,然后:

  • fhs-shell/和shell/脚本用nix-shell命令进入shell环境;
  • pkgs/脚本用nix-build命令生成软件包。

nix-shell的例子

# 以xiangshan.nix配置香山开发环境为例
# 进入香山的根目录
cd Xiangshan
# 下载xiangshan.nix脚本,并重命名为shell.nix
wget https://raw.githubusercontent.com/xieby1/nix_config/main/scripts/shell/xiangshan.nix -O shell.nix
# 进入nix shell
nix-shell

nix配置的使用方法

虚拟机/物理机单系统/物理机双系统 安装NixOS 可以参考我两年前的NixOS安装过程。 安装Nix/NixOS不在此赘述,参考nixos.org/download.html。

安装完Nix/NixOS后,首先下载我的配置

git clone https://github.com/xieby1/nix_config.git ~/.config/nixpkgs
# [仅NixOS] 在imports中添加sys/的路径
vim /etc/nixos/configuration.nix

然后设置NIX_PATH环境变量

./scripts/bootstrap/main.sh
  • 注一:nix-channel难以确定性地配置控制NIX_PATH的nixpkgs, home-manager的源, 所以nix-channel已被我弃用。
  • 注二:NIX_PATH的nixpkgs和home-manager源来自于./npins/。 nixpkgs使用nixpkgs-unstable频道归档(nixexprs.tar.xz), home-manager使用master分支;具体版本由./npins/sources.json固定。

最后部署配置

# [仅NixOS]
sudo nixos-rebuild switch
# 安装home-manager
nix-shell '<home-manager>' -A install
# 在home-manager配置中添加usr/的路径
vim ~/.config/home-manager/home.nix
## 例如  imports = [ (lib.modules.importApply ~/.config/nixpkgs/usr {} ];
# 用nix expression而不使用nix flakes
rm ~/.config/home-manager/flake.nix
home-manager switch

引用

1

nix 2.8的impure特性和home-manager等会引入一些你几乎察觉不到的差异。

2

Dolstra, Eelco. “The purely functional software deployment model.” (2006).

3

github.com/t184256/nix-on-droid termux的分支,支持nix。

config.nix

当初始化nixpkgs时,例如pkgs = import <nixpkgs> {}, nixpkgs的初始化代码会读取~/.config/nixpkgs/config.nix作为nixpkgs.config参数。 如果你对nixpkgs的初始化感兴趣,可以去看看这部分的源代码<nixpkgs>/pkgs/top-level/impure.nix。

config.nix文件(即nixpkgs.config)接受的参数可以参考nixpkgs的官方文档的 config Options Reference章节, 或是去看nixpkgs这部分的源码<nixpkgs>/pkgs/top-level/config.nix。

下面是添加了注解的我的config.nix:

{

禁用安装非本地的包,比如禁止x86_64-linux的包被安装到aarch64-linux上。

  allowUnsupportedSystem = false;
  allowUnfree = true;
  packageOverrides = pkgs: let
    # packages pinned by npins
    npinsed = import ./npins;

添加flake-compat,用于在nix expression中使用flake的包 让flake-compat默认使用pkgs.stdenv.system,使得defaultNix.default为pkgs.stdenv.system的包

    flake-compat = { src, system ? pkgs.stdenv.system }: import npinsed.flake-compat {inherit src system;};
  in {
    inherit npinsed flake-compat;

添加nix user repository (NUR)到nixpkgs里。

    nur = import npinsed.nur {};
  };
}

TODO: nix/nix.conf

opt.nix

system.nix

{ config, lib, ...}: {
  imports = [ ../cachix-push.nix ];

  config = lib.mkIf (
    (builtins.pathExists config.cachix_dhall) &&
    (config.cachix_packages != [])
  ) {
    system.activationScripts = {
      cachix_push = config._cachix_push;
    };
  };
}
{ pkgs, ... }: {
  system.activationScripts.ssh_config = let
    # nix-daemon's ssh cannot find nc,
    # so I replace nc with absolute path.
    # The absolute path is recommended way in ssh ProxyCommand,
    # see `man ssh_config`
    ssh_config = pkgs.runCommand "ssh_config" {} ''
      sed 's,\<nc\>,${pkgs.libressl.nc}/bin/nc,g' ${/home/xieby1/Gist/Config/ssh.conf} > $out
    '';
  in ''
    ln -sfn ${ssh_config} /root/.ssh/config
    for user_id_pub in /home/xieby1/Gist/Vault/id_*.pub; do
        user_id=''${user_id_pub%.pub}
        root_id_pub=/root/.ssh/''${user_id_pub##*/}
        root_id=''${root_id_pub%.pub}
      if [[ ! -e $root_id_pub ]]; then
        cp $user_id_pub $root_id_pub
        cp $user_id     $root_id
        chmod 600 $root_id
      fi
    done
  '';
}

sys/cli

本文件是NixOS的CLI配置。 主要包含两部分内容:

  • 系统环境管理(root的环境)
  • 系统配置
{ pkgs, lib, ... }:

{

系统环境管理(root的环境)

  imports = [
    ./build-machines.nix
  ];

  # List packages installed in system profile. To search, run:
  # $ nix search wget
  environment.systemPackages = with pkgs; [
    git
    file
    wget
    fzf
    perf
  ];

  # neovim
  programs.neovim.enable = true;
  programs.neovim.defaultEditor = true;
  programs.neovim.viAlias = true;
  programs.neovim.vimAlias = true;

  # ssh
  services.openssh = {
    enable = true;
    settings = {
      X11Forwarding = true;
      PasswordAuthentication = false;
    };
  };

系统配置

启用NTFS文件系统的支持。 如此就可以在NixOS/Windows双系统的电脑上挂在Windows的分区啦。

  boot.supportedFilesystems = [ "ntfs" ];

配置binfmt,让非本地指令集的用户程序可以正常运行。 比如在x86_64-linux上运行aarch64-linux的用户程序。 注意:不能在配和本地一样的binfmt,比如不能在x86_64-linux的机器上配置x86_64-linux的binfmt。 不然会出现奇怪的嵌套?你执行任何一条命令(x86_64-linux)都需要去调用qemu-x86_64, 但qemu-x86_64本事也是x86_64-linux的,所以会死循环? 我做了个实验:在x86_64-linux的NixOS中启用x86_64-linux的binfmt。 任何程序都执行不了了,连关机都不行,只能强制重启。 不过好在NixOS可以回滚,轻松复原实验前的环境。 下面的filterAttrs就是用来保证不配置本地的binfmt。

  boot.binfmt = {
    emulatedSystems = lib.remove builtins.currentSystem [
      "x86_64-linux"
      "aarch64-linux"
      "riscv64-linux"
    ];
    preferStaticEmulators = true;
  };

启用docdev。 在home-manager中装devdoc似乎有问题,得在NixOS中装才行。 之后有空再来详细研究。

  # Make sure devdoc outputs are installed.
  documentation.dev.enable = true;
  # Make sure legacy path is installed as well.
  environment.pathsToLink = [ "/share/gtk-doc" ];

  nix.settings.trusted-users = ["root" "xieby1"];

  zramSwap.enable = true;

  boot.kernelPackages = pkgs.linuxPackages_xanmod;

  networking.firewall.enable = false;

  # The following are mkDefault when desktopManager.gnome.enable is true
  networking.networkmanager.enable = true;

允许本机活跃用户(wheel组)免密修改NetworkManager连接配置。 否则连接新WiFi或修改密码时会写入system连接,触发polkit的 settings.modify.system 认证(dms自带polkit agent,会弹出密码框; 忽略则连接不会被持久化)。 仅放宽 settings.modify.*,且限定 active && local(本机活跃会话)

  • wheel,与NM默认对扫描/连接给出的 allow_active=yes 信任级别一致。
  security.polkit.extraConfig = ''
    polkit.addRule(function(action, subject) {
      if (subject.active && subject.local && subject.isInGroup("wheel") &&
          action.id.indexOf("org.freedesktop.NetworkManager.settings.modify.") === 0) {
        return polkit.Result.YES;
      }
    });
  '';
  # Podman user Quadlets wait for the system network-online.target via
  # podman-user-wait-network-online.service; pull it in at boot so the user
  # wait service does not time out while polling an inactive passive target.
  systemd.targets.network-online.wantedBy = [ "multi-user.target" ];
  hardware.bluetooth.enable = true;
  services.upower.enable = true;
  # TODO: remove, currently home-manager switch needs
  programs.dconf.enable = true;
}

sys/default.nix

本文件存放喆我的NixOS的配置。 NixOS的配置通过命令sudo nixos-rebuild switch生效。 因为NixOS的配置入口是/etc/nixos/configuration.nix, 所以需要在/etc/nixos/configuration.nix中import本文件,例如

# /etc/nixos/configuration.nix:
{ config, pkgs, ... }: {
  imports = [
    ./hardware-configuration.nix
    # import my sys/ here!
    /home/xieby1/.config/nixpkgs/sys
  ];
  # other configs ...
}

NixOS配置可以使用的参数可参考configuration.nix的manpage,即man configuration.nix。 下面是我的NixOS的配置源码及注解:

# add this file to /etc/nixos/configuration.nix: imports
{ config, pkgs, ... }:

{

让NixOS的nixpkgs使用和home-manager的nixpkgs采用相同的nixpkgs config

  nixpkgs.config = import ../config.nix;

导入我的NixOS的CLI和GUI配置, 详细内容见文档./cli和./gui。

  imports = [
    ./cachix-push.nix
    ./cli
    ./gui
  ];

  nix.settings = {
    substituters = [
      # Tuna often throws 502, so replace it with USTC
      "https://mirrors.ustc.edu.cn/nix-channels/store"
      "https://cache.nixos.org/"
      "https://xieby1.cachix.org"
    ];
    trusted-public-keys = [
      "cache.nixos.org-1:6NCHdD59X431o0gWypbMrAURkbJ16ZPMQFGspcDShjY="
      "xieby1.cachix.org-1:hVhQjWqdV3oGsSnyXSvzPgmDqcKm+EeKFtqsNK+eRew="
    ];
    experimental-features = ["nix-command" "flakes"];
    # make builtins.fetchurl expire in a long time
    # although `man nix.conf` says tarball-ttl default is 4294967295
    # `nix show-config` show default is 3600 (1 hour)
    tarball-ttl = 4294967295; # max 32bit integer
  };

  nix.channel.enable = false;
  # Preserve NIX_PATH for root and wheel
  # https://superuser.com/questions/232231/how-do-i-make-sudo-preserve-my-environment-variables
  security.sudo.extraConfig = ''
    Defaults:root,%wheel env_keep+=NIX_PATH
  '';

设置时区。

  time.timeZone = "Asia/Shanghai";

设置Linux账户信息。

  users.mutableUsers = false;

当然GitHub上当然不能明文存储密码,这里使用hash过的密码。 可以使用命令行工具mkpasswd来生成hash过的密码。 给root用户设置hash过的密码。

  users.users.root.hashedPassword = "$6$wRBpbr4zSTA/nh$XI/KUASw3mELIqyAxN1hUTWizz9ZBzPhP2u4HNDCA49h4KOWkZsyuiextyXkUti7jYsUHE9fTiRjGAoxBg0Gq/";

将 zsh 设为登录 shell。 此前使用 bash-zsh-forward trick(在 ~/.bashrc 中 exec zsh),但遇到两个问题:

  1. 显示管理器会话包装器(如 niri-session)会通过 bash -l 重新执行, 触发 ~/.bashrc 中的 zsh forward,导致桌面环境被劫持而无法启动。
  2. bash -i 命令(如 kitty bash -i fzf-doc)会被立即转发到 zsh, 导致目标命令永远无法执行。 因此直接在 NixOS 系统配置中设置 zsh 为登录 shell。 同时需要 programs.zsh.enable = true 确保 zsh 被安装并出现在 /etc/shells 中。
  programs.zsh.enable = true;
  # Nushell(已验证 0.116.1)会将环境变量名按大小写不敏感的方式合并,
  # 无法同时保留 Unix 程序可能分别使用的 HTTP_PROXY/http_proxy;
  # Nix devShell 经 direnv 导入的 shell 也可能覆盖 SHELL。
  # 默认命令 shell 需要保留这些变量的区别,因此 nushell 不适合作为默认的 shell。
  # 修改补全的 case_sensitive 设置不能解决环境变量合并问题。
  # 上游讨论:
  # - https://github.com/nushell/nushell/issues/17778
  #   - https://github.com/nushell/nushell/issues/14551
  users.users.xieby1 = {
    shell = pkgs.zsh;
    isNormalUser = true;
    createHome = true;

同上,给xieby1用户设置hash过的密码。

    hashedPassword = "$6$Y4KJxhdaJTT$RSolbCpaUKK2UW1cdnuH.8n1Ky9p0Lnx0MP36BxGX9Q2AeVMjCp.bZOsZ11w689je/785TFRQoVgicMiOfA9B.";

给用户xieby1启用sudo。

    extraGroups = [ "wheel" ];

启用linger,让systemd用户管理器(user@1000.service)随开机启动, 无需登录即可拉起用户级systemd服务(syncthing、clash、tailscale等)。 等价于手动执行loginctl enable-linger xieby1。

    linger = true;

ssh授权的公钥。这样设置后,我的所有的NixOS都相当于“自动授权”了。 我的/home/xieby1/Gist/文件夹存放着一些不方便放入Git仓库的文件,比如二进制文件,或是隐私文件。 该文件由syncthing进行多设备同步。 简单的说,我的备份理念是“git备份配置,syncthing备份数据”。 “配置”即指这个nix_config仓库,“数据”指~/Gist/、~/Docs/等文件夹。 有了这些备份就能轻松还原/复现我的整个工作环境。 TODO:单独专门介绍我的备份理念。

    openssh.authorizedKeys.keyFiles = [] ++ (
      if builtins.pathExists /home/xieby1/Gist/Vault/y50_70.pub
      then [/home/xieby1/Gist/Vault/y50_70.pub]
      else []
    ) ++ (
      if builtins.pathExists /home/xieby1/Gist/Vault/yoga14s.pub
      then [/home/xieby1/Gist/Vault/yoga14s.pub]
      else []
    );
  };

用户级systemd服务随开机启动由users.users.xieby1.linger = true保证, 不再需要此前的services.getty.autologinOnce hack(用TTY自动登录触发PAM会话)。 非NixOS(Ubuntu服务器、WSL2、Debian树莓派等)没有该NixOS选项, 需手动执行loginctl enable-linger <user>,见../server/default.nix。 有关systemd用户服务的配置,详细可见参考:

  services.logind.settings.Login = {
    # On battery: closing the lid suspends.
    HandleLidSwitch = "suspend";
    # On AC power: keep running when lid closes.
    HandleLidSwitchExternalPower = "ignore";
    # With external monitor/dock: keep running.
    HandleLidSwitchDocked = "ignore";
  };
}
{ pkgs, ... }: {
  imports = [ ./xingyao-audio ];

  # Enable the X11 windowing system.
  services.xserver.enable = true;
  services.xserver.videoDrivers = [
    # "nvidia"
    # default video drivers
    "radeon" "nouveau" "modesetting" "fbdev"
    "modesetting" "amdgpu"
  ];

  # Cosmic
  # * Cons
  #   * bluetooth cannot disable auto connect,
  #     and no one discussed in comsic-applets/comsic-epoch github issues
  #   * dont have enough key binding settings
  #     * E.g. left/right half screen?
  # services.desktopManager.cosmic.enable = true;
  # services.displayManager.cosmic-greeter.enable = true;
  # services.desktopManager.gnome.enable = true;
  # services.displayManager.gdm.enable = true;
  # greetd delegates its PAM stack to login.
  security.pam.services.login.enableGnomeKeyring = true;
  services.greetd = {
    enable = true;
    settings = {
      default_session = {
        command = toString [
          "${pkgs.tuigreet}/bin/tuigreet"
          "--time" "--asterisks" "--remember"
          # Use niri-session instead of niri --session.
          # niri-session is a NixOS wrapper that properly initializes the systemd user
          # session, including activating graphical-session.target. Without this, portal
          # services like xdg-desktop-portal-gnome fail to start (dependency failed), which
          # causes xdg-desktop-portal to hang during D-Bus auto-start. GTK4 apps query
          # org.freedesktop.portal.Desktop during startup and block for ~25s waiting for a
          # reply that never comes, resulting in ~1 minute startup delays (e.g. gnome-characters).
          "--cmd 'niri-session'"
        ];
      };
    };
  };

  # Configure keymap in X11
  # services.xserver.layout = "us";
  # services.xserver.xkbOptions = "eurosign:e";

  # Enable CUPS to print documents.
  # https://nixos.wiki/wiki/Printing
  services.printing.enable = true;
  services.printing.drivers = [pkgs.hplip];
  services.avahi.enable = true;
  services.avahi.nssmdns4 = true;

  # Enable touchpad support (enabled default in most desktopManager).
  services.libinput.enable = true;

  nixpkgs.config.allowUnfree = true;

  services.gpm.enable = true;

  hardware.xone.enable = true;

  # for x11 gesture
  services.touchegg.enable = true;

  # for DMS to persist user avatar via AccountsService
  services.accounts-daemon.enable = true;
}
{ config, pkgs, lib, ... }: let
  initialize = pkgs.writeShellApplication {
    name = "xingyao-speakers";
    runtimeInputs = [ pkgs.coreutils pkgs.gnugrep pkgs.gawk pkgs.alsa-tools ];
    text = builtins.readFile ./initialize.sh;
  };
in lib.mkIf (config.networking.hostName == "techrevo") {
  systemd.services.xingyao-speakers = {
    description = "Enable Xingyao 14 ALC256 second speaker path";
    enable = lib.mkDefault false;
    wantedBy = [ "multi-user.target" ];
    after = [ "sound.target" "alsa-restore.service" ];
    serviceConfig = {
      Type = "oneshot";
      RemainAfterExit = true;
      ExecStart = "${initialize}/bin/xingyao-speakers on";
      ExecStop = "${initialize}/bin/xingyao-speakers off";
    };
  };
  # Keep the previous userspace workaround available as a fallback boot entry.
  specialisation.xingyao-speakers-workaround.configuration = {
    systemd.services.xingyao-speakers.enable = true;
  };
  boot.kernelPatches = lib.mkIf (!config.systemd.services.xingyao-speakers.enable) [{
    name = "alc256-xingyao-speakers";
    patch = ./alc256-xingyao-speakers.patch;
  }];
  powerManagement.resumeCommands = lib.mkIf config.systemd.services.xingyao-speakers.enable ''
    ${pkgs.systemd}/bin/systemctl restart xingyao-speakers.service
  '';
}
let
  pkgs = import <nixpkgs> {};
  evaluate = hostName: (import <nixpkgs/nixos/lib/eval-config.nix> {
    inherit pkgs;
    modules = [ ../default.nix {
      networking.hostName = hostName;
      system.stateVersion = "25.11";
    } ];
  }).config;
  cfg = evaluate "techrevo";
  audioState = c: {
    workaround = c.systemd.services.xingyao-speakers.enable;
    resumeWorkaround = pkgs.lib.hasInfix "systemctl restart xingyao-speakers.service"
      c.powerManagement.resumeCommands;
    patch = builtins.any (p: p.name == "alc256-xingyao-speakers") c.boot.kernelPatches;
  };
in pkgs.lib.debug.throwTestFailures { failures = pkgs.lib.runTests {
  test-driver-by-default = {
    expr = audioState cfg;
    expected = { workaround = false; resumeWorkaround = false; patch = true; };
  };
  test-workaround-fallback = {
    expr = if cfg.specialisation ? xingyao-speakers-workaround
      then audioState cfg.specialisation.xingyao-speakers-workaround.configuration
      else null;
    expected = { workaround = true; resumeWorkaround = true; patch = false; };
  };
  test-disabled-on-other-hosts = {
    expr = let other = evaluate "another-host"; in {
      service = other.systemd.services ? xingyao-speakers;
      fallback = other.specialisation ? xingyao-speakers-workaround;
      patch = builtins.any (p: p.name == "alc256-xingyao-speakers") other.boot.kernelPatches;
    };
    expected = { service = false; fallback = false; patch = false; };
  };
  test-fallback-boot-and-stop = {
    expr = let service = cfg.systemd.services.xingyao-speakers; in {
      wantedBy = service.wantedBy;
      after = service.after;
      type = service.serviceConfig.Type;
      remain = service.serviceConfig.RemainAfterExit;
      canRestore = service.serviceConfig ? ExecStop;
    };
    expected = {
      wantedBy = [ "multi-user.target" ];
      after = [ "sound.target" "alsa-restore.service" ];
      type = "oneshot";
      remain = true;
      canRestore = true;
    };
  };
}; }

home.nix

{ pkgs, lib, ... }: let
  models-dev-api_json = pkgs.callPackage ./models-dev-api {};
  models-dev-providers = withWorkingContext (builtins.fromJSON (builtins.readFile models-dev-api_json));
  # Conservative Pi budget, not the advertised limit or a measured effective length.
  withWorkingContext = builtins.mapAttrs (_: provider: provider // {
    models = builtins.mapAttrs (_: model: model // {
      workingContext = lib.min
        (model.limit.input or model.limit.context)
        (builtins.div model.limit.context 3);
    }) provider.models;
  });
in {
  cachix_packages = [
    models-dev-api_json
  ];
  _module.args.ai = rec {
    inherit models-dev-providers;
    default_small = {
      provider = jw2-deepseek;
      model = jw2-deepseek.models.deepseek-flash;
    };
    # default_large_model = jw2-openai.models."gpt-6.1-sol";
    deepseek = models-dev-providers.deepseek // {
      api_key = lib.trim (builtins.readFile ~/Gist/Vault/deepseek_api_key_nvim.txt);
    };
    moonshot-cn = models-dev-providers.moonshotai-cn // {
      api_key = lib.trim (builtins.readFile ~/Gist/Vault/AI/moonshot-cn.txt);
    };
    tavily.api_key = lib.trim (builtins.readFile ~/Gist/Vault/AI/tavily.txt);
    jw2-openai = models-dev-providers.openai // {
      id = "jw2-openai";
      name = "JW2 OpenAI";
      api = lib.trim (builtins.readFile ~/Gist/Vault/AI/jw2-url.txt);
      api_key = lib.trim (builtins.readFile ~/Gist/Vault/AI/jw2-openai.txt);
    };
    jw2-sub2api-pi-codex = models-dev-providers.openai // {
      id = "jw2-sub2api-pi-codex";
      name = "JW2 sub2api-pi-codex";
    };
    jw2-deepseek = models-dev-providers.deepseek // {
      id = "jw2-deepseek";
      name = "JW2 DeepSeek";
      api = lib.trim (builtins.readFile ~/Gist/Vault/AI/jw2-url.txt) + "/v1";
      api_key = lib.trim (builtins.readFile ~/Gist/Vault/AI/jw2-deepseek.txt);
    };
    jw2-kimi = models-dev-providers.kimi-code-plan-cn // {
      id = "jw2-kimi";
      name = "JW2 Kimi";
      api = lib.trim (builtins.readFile ~/Gist/Vault/AI/jw2-url.txt);
      api_key = lib.trim (builtins.readFile ~/Gist/Vault/AI/jw2-kimi.txt);
    };
    acc-gpt = models-dev-providers.openai // {
      id = "acc-openai";
      name = "ACC OpenAI";
      api = lib.trim (builtins.readFile ~/Gist/Vault/AI/aacc/url.txt);
      api_key = lib.trim (builtins.readFile ~/Gist/Vault/AI/aacc/gpt.txt);
    };
  };
}

Models.dev API catalog

sources.json pins the upstream Models.dev Git source with npins. default.nix runs upstream's generateCatalog() and default v1 filtering in a Nix sandbox, resolving TOML inheritance and schema translation. Only the generator's runtime packages (remeda and zod) are fetched, using the exact versions and integrity hashes from the pinned bun.lock. No install scripts or network requests run during generation. The generated JSON lives in the Nix store, not this repository.

Reading the catalog during Nix evaluation uses import-from-derivation (IFD). The first evaluation builds it; subsequent evaluations reuse the store result. Pi filters specialized non-chat models at its converter boundary. Prices are USD per million tokens; limit.output is a maximum, not a default generation budget.

Update from the repository root:

npins --lock-file global-args/ai/models-dev-api/sources.json update models-dev
nix-build --no-out-link -E '(import <nixpkgs> {}).callPackage ./global-args/ai/models-dev-api {}'
nix-instantiate --eval --strict global-args/ai/models-dev-api/test.nix
nix-instantiate --eval --strict usr/cli/basic/pi/providers/models-dev-to-custom-provider/test.nix
nix-instantiate --eval --strict usr/cli/basic/pi/extensions/pi-title/test.nix
home-manager build --no-out-link

When updating, compare the generator's dependencies in upstream packages/core/package.json and bun.lock with the package versions/hashes in default.nix. Review generated model IDs, pricing and limits before committing.

{ fetchurl,
  runCommand,
  bun,
  jq,
}: let
  # Only the generator's runtime dependencies, pinned from upstream bun.lock.
  remeda = fetchurl {
    url = "https://registry.npmjs.org/remeda/-/remeda-2.33.7.tgz";
    hash = "sha512-cXlyjevWx5AcslOUEETG4o8XYi9UkoCXcJmj7XhPFVbla+ITuOBxv6ijBrmbeg+ZhzmDThkNdO+iXKUfrJep1w==";
  };
  zod = fetchurl {
    url = "https://registry.npmjs.org/zod/-/zod-3.24.2.tgz";
    hash = "sha512-lY7CDW43ECgW9u1TcT3IoXHflywfVqDYze4waEz812jR/bZ8FHDsl7pFQoSZTz5N+2NqRXs8GBwnAwo3ZNxqhQ==";
  };
  src = (import <npins> { input = ./sources.json; }).models-dev;
in runCommand "models-dev-api.json" {
  nativeBuildInputs = [ bun jq ];
} ''
  cp -r ${src} source
  chmod u+w source
  cd source
  mkdir -p node_modules/{remeda,zod}
  tar -xzf ${remeda} --strip-components=1 -C node_modules/remeda
  tar -xzf ${zod} --strip-components=1 -C node_modules/zod
  bun --eval '
    import { generateCatalog } from "./packages/core/src/generate.ts";
    import { filterProvidersByModelType } from "./packages/core/src/filter.ts";
    const { providers } = await generateCatalog(process.cwd());
    await Bun.write("api.json", JSON.stringify(filterProvidersByModelType(providers, "default")));
  '
  # Filesystem traversal order must not change the output hash.
  jq --sort-keys --compact-output . api.json > "$out"
''
let
  pkgs = import <nixpkgs> {};
  inherit (pkgs) lib;
  providers = builtins.fromJSON (builtins.readFile (pkgs.callPackage ./. {}));
in lib.debug.throwTestFailures { failures = lib.runTests {
  test-openai = {
    expr = providers.openai.models."gpt-6.1-sol".limit.context;
    expected = 1050000;
  };
  test-deepseek-serving-alias = {
    expr = providers.deepseek.models.deepseek-flash.canonical_model_id;
    expected = "deepseek/deepseek-v4.1-flash-1017";
  };
  test-kimi-coding = {
    expr = providers.kimi-code-plan-cn.models."k3.1-pro".canonical_model_id;
    expected = "moonshotai/kimi-k3.1-pro";
  };
}; }
# Run with nix-instantiate --eval --strict --read-write-mode global-args/ai/test.nix.
let
  lib = import <nixpkgs/lib>;
  raw = {
    openai.models.large.limit = { context = 1050000; input = 922000; output = 128000; };
    other.models = {
      capped.limit = { context = 100000; input = 10000; output = 1000; };
      no-input.limit = { context = 100000; output = 1000; };
    };
  };
  api = (import ./. {
    inherit lib;
    pkgs.callPackage = _: _: builtins.toFile "models-dev-api-test.json" (builtins.toJSON raw);
  })._module.args.ai.models-dev-providers;
in lib.debug.throwTestFailures { failures = lib.runTests {
  test-working-contexts-across-providers = {
    expr = builtins.mapAttrs (_: provider:
      builtins.mapAttrs (_: model: model.workingContext) provider.models
    ) api;
    expected = {
      openai.large = 350000;
      other = { capped = 10000; no-input = 33333; };
    };
  };
  test-preserve-upstream-metadata = {
    expr = builtins.mapAttrs (_: provider: provider // {
      models = builtins.mapAttrs (_: model: builtins.removeAttrs model [ "workingContext" ]) provider.models;
    }) api;
    expected = raw;
  };
}; }
{ pkgs, config, lib, ...}: {
  imports = [ ../cachix-push.nix ];

  # ~/Gist is synced on every device, but $HOME differs per device, so never hardcode a home path.
  cachix_dhall = lib.mkDefault "${config.home.homeDirectory}/Gist/Config/cachix.dhall";

  home.activation.cachix_push = lib.mkIf (
    (builtins.pathExists config.cachix_dhall) &&
    (config.cachix_packages != [])
  ) (lib.hm.dag.entryAfter ["writeBoundary"] config._cachix_push);
}
let
  pkgs = import <nixpkgs> {};
  inherit (pkgs) lib;
  hasPushHook = settings: let
    cfg = (import <home-manager/modules> {
      inherit pkgs;
      configuration = {
        imports = [ ./cachix-push.nix ];
        home = { username = "dummy"; homeDirectory = "/tmp/cachix-push-test"; stateVersion = "25.11"; };
        # Only file existence is checked; the activation script is never run.
        cachix_dhall = toString ./cachix-push.nix;
      } // settings;
    }).config;
  in cfg.home.activation ? cachix_push;
in lib.runTests {
  test-existing-config-enables-push = {
    expr = hasPushHook {};
    expected = true;
  };
  test-missing-config-skips-push = {
    expr = hasPushHook { cachix_dhall = "${toString ./cachix-push.nix}.missing"; };
    expected = false;
  };
  test-empty-packages-skips-push = {
    expr = hasPushHook { cachix_packages = lib.mkForce []; };
    expected = false;
  };
}
{ config, pkgs, lib, isNixOnDroid, ... }: {
  imports = [
    ./tui
  ];
  options.proxyPort = lib.mkOption {
    type = lib.types.number;
    default = 8889;
    description = "代理端口号,诸多网络程序需要用,比如clash和tailscale";
  };

  config = {
    home.packages = [
      pkgs.mihomo
    ];
    # mihomo rewrites this bbolt DB at runtime (selected proxies, fake-ip mappings, provider etags);
    # syncing a live, locked DB across devices corrupts it.
    my.syncthing.Gist-stignore = [ "/clash/cache.db" ];
    systemd.user.services.clash = {
      Unit = {
        Description = "Auto start clash";
        After = ["network.target"];
      };
      Install = {
        WantedBy = ["default.target"];
      };
      Service = {
        ExecStart = "${pkgs.mihomo}/bin/mihomo -d ${config.home.homeDirectory}/Gist/clash";
      };
    };
    programs.zsh.envExtra = lib.mkBefore (lib.optionalString (!isNixOnDroid) ''
      # proxy
      ## default
      HTTP_PROXY="http://127.0.0.1:${toString config.proxyPort}"
      ## microsoft wsl
      # if [[ $(uname -r) == *"microsoft"* ]]; then
      #     hostip=$(cat /etc/resolv.conf | grep nameserver | awk '{ print $2 }')
      #     export HTTP_PROXY="http://$hostip:${toString config.proxyPort}"
      # fi
      export HTTPS_PROXY="$HTTP_PROXY"
      export HTTP_PROXY="$HTTP_PROXY"
      export FTP_PROXY="$HTTP_PROXY"
      export http_proxy="$HTTP_PROXY"
      export https_proxy="$HTTP_PROXY"
      export ftp_proxy="$HTTP_PROXY"
    '');

    programs.zsh.initContent = lib.mkBefore (lib.optionalString (!isNixOnDroid) ''
      unset_proxy() {
        unset HTTPS_PROXY
        unset HTTP_PROXY
        unset FTP_PROXY
        unset https_proxy
        unset http_proxy
        unset ftp_proxy
        unset HTTPS_PORT
        unset HTTP_PORT
        unset FTP_PORT
        unset https_port
        unset http_port
        unset ftp_port
        unset ALL_PROXY
        unset all_proxy
        unset NO_PROXY
        unset no_proxy
        unset RSYNC_PROXY
        unset rsync_proxy
      }
    '');
  };
}
let
  pkgs = import <nixpkgs> {};
  inherit (pkgs) lib;
  evaluate = settings: import <home-manager/modules> {
    inherit pkgs;
    configuration = {
      imports = [
        ../../../cachix-push.nix
        ../../../yq-merge
        ../../../syncthing-gist-ignore.nix
        ./.
        settings
      ];
      _module.args.isNixOnDroid = false;
      home = { username = "test"; homeDirectory = "/tmp/mihomo-test"; stateVersion = "25.05"; };
    };
  };
  basic = evaluate {};
  overridden = evaluate { proxyPort = 19090; };
in lib.debug.throwTestFailures { failures = lib.runTests {
  test-default-port = {
    expr = basic.config.proxyPort;
    expected = 8889;
  };
  test-overridden-port = {
    expr = overridden.config.proxyPort;
    expected = 19090;
  };
  test-string-port-is-rejected = {
    expr = basic.options.proxyPort.type.check "8889";
    expected = false;
  };
  test-overridden-port-reaches-client-environment = {
    expr = lib.hasInfix ''HTTP_PROXY="http://127.0.0.1:19090"'' overridden.config.programs.zsh.envExtra;
    expected = true;
  };
}; }
{ pkgs, ... }: let
  mihomo-tui = pkgs.callPackage ./package.nix {};
in {
  home.packages = [
    pkgs.mihomo
    mihomo-tui
    (let
      class = "cn.xieby1.mihomo-tui";
    in pkgs.makeDesktopItem {
      name = "mihomo-tui";
      desktopName = "Mihomo TUI";
      keywords = ["mihomo" "clash" "tui"];
      exec = "ghostty --class=${class} -e mihomo-tui";
      icon = pkgs.mihomo.src + /Meta.png;
      startupWMClass = class;
    })
  ];
  cachix_packages = [
    mihomo-tui
  ];
  yq-merge.".config/mihomo-tui/config.yaml" = {
    generator = builtins.toJSON;
    expr = let
      clash-config-base = builtins.fromJSON (builtins.readFile ~/Gist/clash/base.json);
    in {
      mihomo-api = "http://${clash-config-base.external-controller}";
      mihomo-secret = clash-config-base.secret;
      log-file = "/tmp/mihomo-tui.log";
    };
  };
}
{
  lib,
  rustPlatform,
  fetchFromGitHub,
}:

# mihomo-tui: lean MetaCubeXD-like API dashboard for an already-running core.
# clashtui: profile/template/config/service manager; useful, but much broader.
# Prefer mihomo-tui when the core is managed elsewhere and only TUI control is needed.
rustPlatform.buildRustPackage rec {
  pname = "mihomo-tui";
  version = "0.4.4";

  src = fetchFromGitHub {
    owner = "potoo0";
    repo = "mihomo-tui";
    rev = "v${version}";
    hash = "sha256-LdNjSibwfR0aTjspwVTl91msZ+UwdQfM+C0d2Aytldc=";
  };

  cargoLock.lockFile = "${src}/Cargo.lock";

  # Upstream .cargo/config.toml sets this; Nix's cargo hook does not keep it.
  RUSTFLAGS = "--cfg tokio_unstable";

  VERGEN_GIT_DESCRIBE = "v${version}";
  VERGEN_BUILD_DATE = "2026-06-26";

  postPatch = ''
    echo 'fn main() {}' > build.rs
    substituteInPlace Cargo.toml \
      --replace-fail 'vergen-gitcl = { version = "10.0.0", features = ["build", "cargo"] }' ""
  '';

  meta = {
    description = "Terminal UI for Mihomo/Clash.Meta";
    homepage = "https://github.com/potoo0/mihomo-tui";
    license = lib.licenses.mit;
    mainProgram = "mihomo-tui";
    platforms = lib.platforms.linux;
  };
}
{
  enableExtendedCLI
}: # local args
{ lib, ... }: {
  imports = [
    ./starship.nix
    ./zsh
    ./git
    ./clash
    ./tailscale
    ./ssh.nix
    (lib.modules.importApply ./nvim {inherit enableExtendedCLI;})
    (lib.modules.importApply ./pi {inherit enableExtendedCLI;})
    ./syncthing.nix
  ];
  home.stateVersion = "25.05";

  news.display = "silent";

  programs.zsh.envExtra = /*bash*/ ''
    . ${toString ../../../scripts/bootstrap/main.sh}
  '';
}
{ pkgs, config, ... }: {
  programs.git.package = pkgs.gitFull.overrideAttrs (old: {
    patches = (old.patches or []) ++ [ ./main.patch ];
    postInstallCheck = (old.postInstallCheck or "") + ''
      ${pkgs.python3}/bin/python3 ${./test.py} "$out/bin/git"
    '';
  });

  cachix_packages = [
    config.programs.git.package
  ];
}
{ pkgs, ... }: let
  # TODO: update to support untracked files
  git-wip = builtins.derivation {
    name = "git-wip";
    system = builtins.currentSystem;
    src = pkgs.fetchurl {
      url = "https://raw.githubusercontent.com/bartman/git-wip/1c095e93539261370ae811ebf47b8d3fe9166869/git-wip";
      sha256 = "00gq5bwwhjy68ig26a62307pww2i81y3zcx9yqr8fa36fsqaw37h";
    };
    builder = pkgs.writeShellScript "git-wip-builder" ''
      source ${pkgs.stdenv}/setup
      mkdir -p $out/bin
      dst=$out/bin/git-wip
      cp $src $dst
      chmod +w $dst
      sed -i 's/#!\/bin\/bash/#!\/usr\/bin\/env bash/g' $dst
      chmod -w $dst
      chmod a+x $dst
    '';
  };
in {
  imports = [
    ./compact-graph
    ./gh.nix
    ./lazygit
  ];
  home.packages = with pkgs; [
    mr
    git-wip
    git-quick-stats
  ];
  programs.git = {
    enable = true;
    settings = {
      core = {
        editor = "vim";
      };
      commit.verbose = true;
      credential.helper = "store";
      init.defaultBranch = "main";
      alias = {
        # The original "log --decorate --oneline" does not contain date and author.
        # Append time and author to `--decorate --oneline` style by a customized the format
        viz = toString [
          "log"
          ''--format="%Cblue%ad %Cgreen%<(8,trunc)%an %C(auto)%h %(graph)%d %s"''
          ''--date=format:"%Y.%m.%d"''
        ];
      };
      user = {
        email = "xieby1@outlook.com";
        name = "xieby1";
      };
      protocol.file.allow = "always";
      # Used when this account serves Git repos over SSH, e.g. Nix/npins
      # fetching a pinned commit that is not advertised by any branch or tag.
      uploadpack.allowAnySHA1InWant = true;
    };
    lfs.enable = true;
  };
  systemd.user.tmpfiles.rules = [
    "L? %h/.mrconfig - - - - %h/Gist/Config/mrconfig"
  ];
  # mr status not work in non-home dir
  home.shellAliases.mr = "mr -d ~";
}
{ pkgs, config, ... }: let
  gh-user = user: {
    home.packages = [(
      pkgs.runCommand "gh-${user}" {
        nativeBuildInputs = [pkgs.makeWrapper];
      } ''
        mkdir -p $out/bin
        makeWrapper ${pkgs.gh}/bin/gh $out/bin/gh-${user} --set GH_CONFIG_DIR ${config.home.homeDirectory}/.config/gh/${user}
      ''
    )];
    yq-merge.".config/gh/${user}/config.yml" = {
      generator = builtins.toJSON;
      expr = {
        git_protocol = "ssh";
      };
    };
    yq-merge.".config/gh/${user}/hosts.yml" = {
      generator = builtins.toJSON;
      expr = {
        "github.com" = {
          user = "${user}";
          oauth_token = pkgs.lib.trim (builtins.readFile ~/Gist/Vault/AI/github-${user}.txt);
        };
      };
    };
  };
in {
  imports = [
    (gh-user "xieby1")
    (gh-user "nanhu")
  ];
  home.packages = [
    pkgs.gh
  ];
}

Co-author display

main.patch adds gui.commitCoAuthorLongLength to LazyGit. The default is 0 (disabled); this module enables it with the width configured in default.nix, measured in terminal cells.

  • Normal commits view: append & directly to the author when co-authors exist, or one blank cell otherwise.
  • Expanded commits view: show names without emails in a fixed-width column after the author. Multiple names are comma-separated and overflow uses LazyGit's existing truncation.
  • Disabled: preserve the original rendering and Git log format.

Git extracts case-insensitive Co-authored-by trailers in the existing log/show calls. The separate Reflog list is unchanged.

The module extends pkgs.lazygit through an overlay, preserving earlier patches and check hooks. Home Manager uses that package by default; additional patch modules can append their own overlays without redefining programs.lazygit.package.

Verify or update

Build the package and run the included loader/rendering tests without activating Home Manager:

nix-build --no-out-link -E '(import <nixpkgs> { overlays = (import ./usr/cli/basic/git/lazygit/co-author {}).nixpkgs.overlays; }).lazygit'

When updating LazyGit, rebase the patch against pkgs.lazygit.src if needed, then repeat this build. Check normal and expanded TUI views, including a viewport containing only commits without co-authors.

{ ... }: {
  nixpkgs.overlays = [
    (self: super: {
      lazygit = super.lazygit.overrideAttrs (old: {
        patches = (old.patches or []) ++ [ ./main.patch ];
        nativeCheckInputs = (old.nativeCheckInputs or []) ++ [ self.git ];
        postCheck = (old.postCheck or "") + "\n" + ''
          go test ./pkg/commands/git_commands ./pkg/commands/models ./pkg/config ./pkg/gui/presentation ./pkg/gui/presentation/authors
        '';
      });
    })
  ];
  programs.lazygit.settings.gui.commitCoAuthorLongLength = 4;
}
{ config, ... }: {
  imports = [ ./co-author ];
  cachix_packages = [ config.programs.lazygit.package ];
  programs.lazygit = {
    enable = true;
    settings = {
      gui = {
        # screenMode = "half";
        mainPanelSplitMode = "horizontal";
        expandFocusedSidePanel = true;
        expandedSidePanelWeight = 4;
        commitAuthorLongLength = builtins.stringLength "xieby1";

        # https://pkg.go.dev/time#Time.Format
        # Year: "2006" "06"
        # Month: "Jan" "January" "01" "1"
        # Day of the week: "Mon" "Monday"
        # Day of the month: "2" "_2" "02"
        # Day of the year: "__2" "002"
        # Hour: "15" "3" "03" (PM or AM)
        # Minute: "4" "04"
        # Second: "5" "05"
        # AM/PM mark: "PM"
        timeFormat = "2006.01.02";
        shortTimeFormat = "15:04";
      };
      keybinding = {
        universal = {
          rangeSelectDown = "";
          rangeSelectUp = "";
          scrollUpMain-alt1 = "<s-up>";
          scrollDownMain-alt1 = "<s-down>";
        };
      };
      promptToReturnFromSubprocess = false;
      git = {
        autoFetch = false;
        ignoreWhitespaceInDiffView = true;
      };
    };
  };
}

📑neovim

xieby1's neovim config!

See default.nix

auto sessions management

auto-session vs persisted.nvim vs persistence-nvim

  • auto-session support multiple sessions per path (customized session name), while other two not support
  • persisted-nvim support customized pickers, while persistence-nvim not
{ pkgs, ... }: { programs.neovim.plugins = [{
  plugin = pkgs.vimPlugins.auto-session;
  type = "lua";
  config = /*lua*/ ''
    require("auto-session").setup({
      -- auto_save will not update existing tag
      -- e.g.:
      -- * restore a session tag is (time1 win1┇win2)
      -- * ... some vim operations ...
      -- * when leave vim, there are only win1, the tag is expected to become (time2 win1)
      -- * However the tag is not updated, which is still (time1 win1┇win2)
      -- So I disable the original auto_save,
      -- and manually execute save when VimLeavePre,
      -- see VimLeavePre below.
      auto_save = false,
      auto_restore = false,
      args_allow_files_auto_save = true,
      -- auto purge session after 30 days
      purge_after_minutes = 60*24*30,
    })
    vim.keymap.set('n', '<space>S', '<cmd>AutoSession search<CR>')
    vim.api.nvim_create_autocmd("VimLeavePre", { callback = function()
      -- close unnecessary buffers
      for _, win in ipairs(vim.api.nvim_list_wins()) do
        local buf = vim.api.nvim_win_get_buf(win)
        local ft = vim.api.nvim_buf_get_option(buf, 'filetype')
        if ft == "Outline" then
          vim.api.nvim_buf_delete(buf, {})
        end
      end

      local buffers = {}
      for _, win in ipairs(vim.api.nvim_list_wins()) do
        local buf = vim.api.nvim_win_get_buf(win)
        local buf_name = vim.api.nvim_buf_get_name(buf)
        if buf_name ~= "" then
          -- Extract just the filename from the full path
          local filename = vim.fn.fnamemodify(buf_name, ":~:.")
          table.insert(buffers, filename)
        end
      end

      local buffers_occurrences = {}
      for _, buf in ipairs(buffers) do
        if buffers_occurrences[buf] then
          buffers_occurrences[buf] = buffers_occurrences[buf] + 1
        else
          buffers_occurrences[buf] = 1
        end
      end

      local buffers_strs = {}
      for buf, occurrence in pairs(buffers_occurrences) do
        if occurrence == 1 then
          table.insert(buffers_strs, buf)
        else --[[occurrence > 1]]
          table.insert(buffers_strs, string.format("%s[%d]", buf, occurrence))
        end
      end

      table.sort(buffers_strs)
      local buffers_string = table.concat(buffers_strs, ", ")

      -- save session iff buffers_string is not empty
      if buffers_string ~= "" then
        require("auto-session").SaveSession(string.format("%s %s: %s",
          os.date("%d日"),
          vim.fn.fnamemodify(vim.fn.getcwd(), ":~"),
          buffers_string
        ))
      end
    end})
  '';
}];}

completion

blink-cmp vs nvim-cmp

* as the config looks too hacking and too many issues remaining unsolved in github

* and nvim-cmp last maintain is 5 months ago, blink-cmp is 5 days ago.

* and minuet-ai-nvim delay in nvim-cmp and not solved, blink-cmp is async

# TODO: split providers into separate files
{ pkgs, ... }: { programs.neovim = {
  plugins = [
  pkgs.vimPlugins.blink-cmp-dictionary
  {
    # match unicode characters => match alphabet characters instead.
    # E.g. I don't want to completion a long CJK sentence.
    # E.g. I want alphabet next to CJK can be completed: "例子example"
    #      In original blink-fuzzy-lib, "example" cannot be completed.
    # (Due to the libblink_cmp_fuzzy being not easy to be patched,
    # the nix patch code becomes a large chunk as below.)
    plugin = pkgs.vimPlugins.blink-cmp.overrideAttrs (old: let
      postPatch = ''
        ## This is where texts being collected
        sed -i 's/\\p{L}/a-zA-Z/g' lua/blink/cmp/fuzzy/rust/lib.rs
        ## This is where trigger range is decided
        ## This change will break blink-fuzzy-lib check, so doCheck=false
        sed -i 's/\\p{L}/a-zA-Z/g' lua/blink/cmp/fuzzy/rust/keyword.rs
      '';
    in {
      # Here, postPatch does not effect blink-fuzzy-lib,
      # however, for consistency between source code and libblink_cmp_fuzzy.so,
      # I patch the source code as well.
      inherit postPatch;

      preInstall = let
        ext = pkgs.stdenv.hostPlatform.extensions.sharedLibrary;
        blink-fuzzy-lib = old.passthru.blink-fuzzy-lib.overrideAttrs { inherit postPatch; doCheck=false; };
      in ''
        mkdir -p target/release
        ln -s ${blink-fuzzy-lib}/lib/libblink_cmp_fuzzy${ext} target/release/libblink_cmp_fuzzy${ext}
      '';
    });
    type = "lua";
    config = /*lua*/ ''
      require("blink.cmp").setup({
        keymap = { preset = 'none',
          ['<Tab>']   = { 'select_next', 'fallback' },
          ['<S-Tab>'] = { 'select_prev', 'fallback' },
          ['<Up>']   = { function(cmp) return cmp.select_prev({ auto_insert = false }) end, 'fallback' },
          ['<Down>'] = { function(cmp) return cmp.select_next({ auto_insert = false }) end, 'fallback' },
          ['<CR>'] = { 'accept', 'fallback' },
          ['<A-1>'] = { function(cmp) cmp.accept({ index = 1 }) end },
          ['<A-2>'] = { function(cmp) cmp.accept({ index = 2 }) end },
          ['<A-3>'] = { function(cmp) cmp.accept({ index = 3 }) end },
          ['<A-4>'] = { function(cmp) cmp.accept({ index = 4 }) end },
          ['<A-5>'] = { function(cmp) cmp.accept({ index = 5 }) end },
          ['<A-6>'] = { function(cmp) cmp.accept({ index = 6 }) end },
          ['<A-7>'] = { function(cmp) cmp.accept({ index = 7 }) end },
          ['<A-8>'] = { function(cmp) cmp.accept({ index = 8 }) end },
          ['<A-9>'] = { function(cmp) cmp.accept({ index = 9 }) end },
          ['<A-0>'] = { function(cmp) cmp.accept({ index = 10 }) end },
          ['<A-a>'] = require('minuet').make_blink_map(),
        },
        completion = {
          documentation = { auto_show = true },
          menu = {
            draw = {
              columns = {
                {'item_idx'},
                {'kind_icon'}, {'label', 'label_description', gap = 1},
                {'source_name'},
              },
              components = {
                item_idx = {
                  text = function(ctx) return ctx.idx == 10 and '0' or ctx.idx >= 10 and ' ' or tostring(ctx.idx) end,
                  highlight = 'BlinkCmpSource' -- optional, only if you want to change its color
                },
              },
            },
          },
          list = { selection = { preselect = false }, },
        },
        sources = {
          default = {
            'lsp', 'path', 'cwd_path', 'buffer', 'snippets',
            'minuet',
            "dictionary"
          },
          providers = {
            -- > By default, the buffer source will only show when the LSP source returns no items
            -- Always show buffer completion, defaults to `{ 'buffer' }`
            lsp = { fallbacks = {}, },
            cwd_path = {
              name = 'CwdPath',
              module = 'blink.cmp.sources.path',
              -- same priority as the default path source
              score_offset = 3,
              -- Disable CwdPath according to following conditions:
              enabled = function()
                local buf_dir = vim.fn.expand(('#%d:p:h'):format(vim.api.nvim_get_current_buf()))
                -- Condition 1: Same dir → Path source already covers it.
                if vim.fn.resolve(buf_dir) == vim.fn.resolve(vim.fn.getcwd()) then
                  return false
                end
                -- Condition 2: Absolute path (~/ or /) → doesn't depend on cwd.
                do
                  local col = vim.api.nvim_win_get_cursor(0)[2]
                  local line = vim.api.nvim_get_current_line()
                  local prefix = line:sub(1, col):match("[^%s'\"`{}%[%]()<>,;:]*$") or ""
                  if prefix:match("^[~/]") ~= nil then
                    return false
                  end
                end
                return true
              end,
              opts = {
                get_cwd = function(_)
                  return vim.fn.getcwd()
                end,
              },
            },
            buffer = {
              opts = {
                -- copy from the default get_bufnrs (all visible buffers).
                get_bufnrs = function()
                  return vim
                    .iter(vim.api.nvim_list_wins())
                    :map(function(win) return vim.api.nvim_win_get_buf(win) end)
                    -- The default get_bufnrs filter out nofile buffers (vim help, ...).
                    -- Here, we remove the filter.
                    -- :filter(function(buf) return vim.bo[buf].buftype ~= 'nofile' end)
                    :totable()
                end,
              },
            },
            minuet = {
              name = 'minuet',
              module = 'minuet.blink',
              async = true,
              -- Should match minuet.config.request_timeout * 1000,
              -- since minuet.config.request_timeout is in seconds
              timeout_ms = 3000,
              score_offset = -1,
            },
            -- blink-cmp-dictionary vs blink-cmp-dat-word
            -- former can handle capitalization proper, while latter cannot
            dictionary = {
              name = 'dict',
              module = 'blink-cmp-dictionary',
              min_keyword_length = 3,
              score_offset = -4, -- lower priority than buffer's -3
              opts = {
                -- TODO: clean this words list:
                -- - remove word < 3 characters
                dictionary_files = { "${pkgs.fetchurl {
                  url = "https://github.com/dwyl/english-words/raw/8179fe68775df3f553ef19520db065228e65d1d3/words_alpha.txt";
                  sha256 = "sha256-PtDJRhDYvPfBG7tJxWqknHI00ytmgk35H1VBaeVy2kg=";
                }}" },
                dictionary_directories = { vim.fn.expand('~/Gist/dicts/blink-cmp') },
              },
            },
          },
        },
        cmdline = {
          -- TODO: blink-cmp cmdline cannot complete `'`,
          -- for example: `:h statusline` cannot complete to `:h 'statusline'`
          -- thus disable it currently
          enabled = false,
          keymap = { preset = 'inherit',
            ['<Tab>'] = { 'show_and_insert', 'select_next' },
            ['<CR>'] = { 'accept_and_enter', 'fallback' },
          },
          completion = { list = { selection = { preselect = false }, }, },
        },
      })
      vim.lsp.config('*', {
        capabilities = require('blink.cmp').get_lsp_capabilities(),
      })
    '';
  }];
};
}

key bindings of closing windows

{ ... }: { programs.neovim.initLua = /*lua*/ ''
  for Dir, cmd in pairs({Left="h", Down="j", Up="k", Right="l"}) do
    local f = function()
      local beg = vim.api.nvim_get_current_win()
      local cur
      while true do
        vim.api.nvim_set_current_win(beg)
        vim.cmd(string.format("wincmd %s", cmd))
        cur = vim.api.nvim_get_current_win()
        if cur == beg then break end
        vim.cmd("q")
      end
    end
    vim.keymap.set('n', string.format("Z<%s>", Dir), f)
    vim.keymap.set('n', string.format("Z<S-%s>", Dir), f)
  end
  vim.keymap.set('n', "ZA", "<CMD>qa!<CR>")
'';}
# TODO: sonokai does not support light theme.
#       Replace it with other colorscheme that both support dark and light theme.
#       https://github.com/catppuccin may be a good choice, as it support tons of software.

🎨My nvim color scheme

{ config, pkgs, stdenv, lib, ... }:
let
  my-color-scheme = {
    plugin = pkgs.vimPlugins.sonokai;
    type = "viml";
    config = ''
      set termguicolors

      let g:sonokai_transparent_background = 1

      let g:sonokai_colors_override = {
      \ 'black':    ['#111215', '237'],
      \ 'bg0':      ['#22232a', '235'],
      \ 'bg1':      ['#33353f', '236'],
      \ 'bg2':      ['#444754', '236'],
      \ 'bg3':      ['#555869', '237'],
      \ 'bg4':      ['#666a7e', '237'],
      \ 'grey':     ['#a5a5a6', '246'],
      \ 'grey_dim': ['#787879', '240'],
      \}

      " custom sonokai,
      " see section "How to use custom colors" of `:h sonokai.vim`
      function! s:sonokai_custom() abort
        let l:palette = sonokai#get_palette('default', {})
        call sonokai#highlight('StatusLine', l:palette.black, l:palette.fg, 'bold')
        call sonokai#highlight('StatusLineNC', l:palette.black, l:palette.grey, 'bold')
      endfunction
      augroup SonokaiCustom
        autocmd!
        autocmd ColorScheme sonokai call s:sonokai_custom()
      augroup END

      colorscheme sonokai
    '';
  };
in {
  programs.neovim = {
    plugins = [
      my-color-scheme
    ];
  };
}

conform-nvim: formatter

{ pkgs, ... }: {
  programs.neovim = {
    plugins = [{
      plugin = pkgs.vimPlugins.conform-nvim;
      type = "lua";
      config = ''
        require("conform").setup({
          formatters_by_ft = {
            json = { "js_beautify" },
            javascript = { "js_beautify" },
          },
        })

        -- refer to https://github.com/stevearc/conform.nvim/blob/master/doc/recipes.md#format-command
        vim.api.nvim_create_user_command("TrimWhitespace", function(args)
          local range = nil
          if args.count ~= -1 then
            local end_line = vim.api.nvim_buf_get_lines(0, args.line2 - 1, args.line2, true)[1]
            range = {
              start = { args.line1, 0 },
              ["end"] = { args.line2, end_line:len() },
            }
          end
          require("conform").format({ formatters = {"trim_whitespace"}, range = range })
        end, { range = true })

        vim.api.nvim_create_user_command("Format", function(args)
          local range = nil
          if args.count ~= -1 then
            local end_line = vim.api.nvim_buf_get_lines(0, args.line2 - 1, args.line2, true)[1]
            range = {
              start = { args.line1, 0 },
              ["end"] = { args.line2, end_line:len() },
            }
          end
          require("conform").format({ async = true, lsp_fallback = true, range = range })
        end, { range = true })
      '';
    }];
    extraPackages = [
      pkgs.js-beautify
    ];
  };
}
{ enableExtendedCLI }: # local args
# TODO: niri like buffer width/height adjust
{ pkgs, config, lib, ... }:let
  npinsed = import <npins> {input=./sources.json;};
  my-neovim-unwrapped = pkgs.neovim-unwrapped.overrideAttrs (old: {
    patches = old.patches ++ [
      # [:terminal - enable folding #5682](https://github.com/neovim/neovim/issues/5682)
      ./enable-folding-in-terminal.patch
    ];
  });
in {
  cachix_packages = [ my-neovim-unwrapped ];

Plugins with customizations:

  imports = [
    ./fold.nix
    ./blink-cmp.nix
    (lib.modules.importApply ./vim-mark {
      mark-src = npinsed.vim-mark;
      ingo-src = npinsed.vim-ingo-library;
    })
    (lib.modules.importApply ./nvim-treesitter.nix {
      d2-src = npinsed.tree-sitter-d2;
      veryl-src = npinsed.tree-sitter-veryl;
      merman-src = npinsed.merman;
    })
    ./nvim-config-local.nix
    ./leap-nvim.nix
    ./git-wip.nix
    ./rich-paste.nix
    (lib.modules.importApply ./outline-nvim.nix {src = npinsed.outline-treesitter-provider;})
    (lib.modules.importApply ./gitsigns {src = npinsed.gitsigns;})
    ./color-scheme.nix
    (lib.modules.importApply ./hbac-nvim.nix {src = npinsed.hbac;})
    ./winshift-nvim.nix
    ./smartyank-nvim.nix
    ./mini-nvim.nix
    ./vim-easy-align.nix
    ./close-windows.nix
    ./nvim-window-picker.nix
    # TODO: remove/replace vim-matchup, which make nvim very laggy when edit/view large markdown (1k sloc)
    # ./vim-matchup.nix
    ./nvim-nav.nix
    ./venn-nvim.nix
    ./snacks
    ./minuet-ai-nvim.nix
    ./auto-session.nix
    ./nvim-treesitter-context.nix
    ./treesitter-injections
    ./lz-n
    ./todo-comments.nix
    ./lualine.nix
    ./conform.nix
  ] ++ lib.optionals enableExtendedCLI [
    ./markdown-preview.nix
    ./lspconfig
    ./rustowl.nix
  ];

  home.shellAliases.view = "nvim -R";

Set nvim as manpager. see nvim :h :Man. nvim manpage huge mange is SLOW! E.g. man configuration.nix.

  home.shellAliases.nman = "env MANPAGER='nvim +Man!' man";

  programs.neovim = {
    enable = true;
    withPython3 = false;
    withRuby = false;
    # Set environment variable EDITOR to nvim.
    # Per zshzle(1), when EDITOR or VISUAL contains "vi" at shell startup,
    # zsh links "main" to "viins" instead of "emacs".
    # This prevents a keymap race with zsh-vi-mode:
    # that plugin defers initialization to the first precmd hook,
    # then switches main→viins and resets all vi bindings — overwriting Forge's '^M' → 'forge-accept-line'.
    # With EDITOR=nvim, main is viins from startup,
    # so Forge's bindkey targets the right keymap immediately and survives.
    defaultEditor = true;
    package = my-neovim-unwrapped;
    viAlias = true;
    vimAlias = true;
    vimdiffAlias = true;

Plugins without customizations:

    plugins = with pkgs.vimPlugins; [
      vim-fugitive
      vim-nix
      vim-markdown-toc
      vim-commentary
      vim-surround
      otter-nvim
    ];

Vim config

    extraConfig = /*vim*/ ''
      " vim
      nnoremap <F3> :nohlsearch<CR>
      "" Show line number
      set number
      "" Always show the signcolumn, otherwise it would shift the text each time
      "" diagnostics appear/become resolved
      set signcolumn=number
      "" indent
      """ On pressing tab, insert spaces
      set expandtab
      set tabstop=2
      set shiftwidth=2
      """ no markdown recommended indent style (recommended shiftwidth=4)
      let g:markdown_recommended_style = 0
      """ line wrap with ident
      set breakindent

      """ mouse support " select by pressing shift key!
      set mouse=a
      "" Preview
      nnoremap <leader>[ :pc<CR>
      "" highlight unwanted whitespace
      set list
      set listchars=tab:>-,trail:-
      "" wrap line
      """ https://stackoverflow.com/questions/248102/is-there-any-command-to-toggle-enable-auto-text-wrapping
      :function ToggleWrap()
      : if (&wrap == 1)
      :   set nowrap
      : else
      :   set wrap
      : endif
      :endfunction
      nnoremap <F9> :call ToggleWrap()<CR>
      set updatetime=400
      "" highlight current line
      set cursorlineopt=number
      augroup CursorLine
        au!
        au VimEnter,WinEnter,BufWinEnter * setlocal cursorline
        au WinLeave * setlocal nocursorline
      augroup END

      " filetype
      augroup filetype
          " detect LLVM IR file
          au! BufRead,BufNewFile *.ll     set filetype=llvm
          " cpp " from gem5
          au! BufRead,BufNewFile *.hh.inc,*.cc.inc set filetype=cpp
          " d2
          au! BufRead,BufNewFile *.d2 set filetype=d2
          au! FileType d2 setlocal commentstring=#\ %s
      augroup END

      " set terminal title
      "" https://stackoverflow.com/questions/15123477/tmux-tabs-with-name-of-file-open-in-vim
      autocmd BufEnter * let &titlestring = expand("%:p:h:t") . "/" . expand("%:t")
      set title

      nnoremap <F10> :echo "hi<" . synIDattr(synID(line("."),col("."),1),"name") . '> trans<'
      \ . synIDattr(synID(line("."),col("."),0),"name") . "> lo<"
      \ . synIDattr(synIDtrans(synID(line("."),col("."),1)),"name") . ">"<CR>

      " TODO: replace wildmenu with blink-cmp cmdline
      " wildmenu
      " see: https://github.com/neovim/neovim/pull/11001
      cnoremap <expr> <Up>    pumvisible() ? "\<Left>"  : "\<Up>"
      cnoremap <expr> <Down>  pumvisible() ? "\<Right>" : "\<Down>"
      cnoremap <expr> <Left>  pumvisible() ? "\<Up>"    : "\<Left>"
      cnoremap <expr> <Right> pumvisible() ? "\<Down>"  : "\<Right>"

      " prevent resizing other windows when splitting/closing a window
      set noequalalways
      nnoremap <C-W><C-Left>  <C-W><Left>
      nnoremap <C-W><C-Right> <C-W><Right>
      nnoremap <C-W><C-Up>    <C-W><Up>
      nnoremap <C-W><C-Down>  <C-W><Down>

      " Browsers reserve Ctrl-W (closes the tab) in web terminals/SSH-in-browser,
      " so window commands are unreachable there. Add a parallel prefix whose keys
      " the browser does not grab; it expands to <C-w>.
      " MUST be `nmap` (recursive), not `nnoremap`: with noremap the key typed after
      " the expansion skips mapping lookup, so it reaches only built-in <C-w>v/s but
      " NOT plugin/user <C-w>x maps (nvim-window-picker <C-w>j, winshift <C-W>m).
      nmap <leader>w <C-w>
    '';
  };

  home.file.vim-pack-dir = {
    target = ".config/nvim/pack-dir";
    # The `finalPackdir` variable is defined inside a `let ... in` expression,
    # within `config.programs.neovim.finalPackage`, making it inaccessible from outside.
    # To obtain the pack directory path, we replicate the logic that generates `finalPackdir`.
    # See <nixpkgs>/pkgs/applications/editors/neovim/wrapper.nix.
    source = pkgs.neovimUtils.packDir config.programs.neovim.finalPackage.packpathDirs;
  };
}

fold

{ ... }: {
  programs.neovim = {
    # TODO: rewrite in lua
    extraConfig = ''
      "" Fold
      """ fold text to be the first and last line
      """ refer to sbernheim4's reply at
      """ https://github.com/nvim-treesitter/nvim-treesitter/pull/390
      function! GetSpaces(foldLevel)
          if &expandtab == 1
              " Indenting with spaces
              let str = repeat(" ", a:foldLevel / (&shiftwidth + 1) - 1)
              return str
          elseif &expandtab == 0
              " Indenting with tabs
              return repeat(" ", indent(v:foldstart) - (indent(v:foldstart) / &shiftwidth))
          endif
      endfunction
      function! MyFoldText()
          let startLineText = getline(v:foldstart)
          let endLineText = trim(getline(v:foldend))
          let indentation = GetSpaces(foldlevel("."))
          let spaces = repeat(" ", 200)
          let str = indentation . startLineText . " …… " . endLineText . spaces
          return str
      endfunction
      "" toggle foldmethod between manual and indent
      set foldmethod=indent
      :function ToggleFoldmethod()
      : if (&foldmethod == "manual")
      :   set foldmethod=indent
      : else
      :   set foldmethod=manual
      : endif
      :endfunction
      nnoremap <Leader>z :call ToggleFoldmethod()<CR>:echo &foldmethod<CR>
      "" Custom display for text when folding
      set foldtext=MyFoldText()
      """ Set the foldlevel to a high setting,
      """ files are always loaded with opened folds.
      set foldlevel=20
    '';
    initLua = /*lua*/''
      -- Decrease foldcolumn
      vim.keymap.set('n', 'z-', function()
        local value = tonumber(vim.o.foldcolumn) or 0
        if value > 0 then
          vim.o.foldcolumn = tostring(value - 1)
        end
      end, { desc = 'Decrease foldcolumn' })
      -- Increase foldcolumn
      vim.keymap.set('n', 'z=', function()
        local value = tonumber(vim.o.foldcolumn) or 0
        vim.o.foldcolumn = tostring(value + 1)
      end, { desc = 'Increase foldcolumn' })
    '';
  };
}

git-wip: auto wip branch

{ config, pkgs, stdenv, lib, ... }:
let
  git-wip = pkgs.vimUtils.buildVimPlugin {
    name = "git-wip";
    src = pkgs.fetchFromGitHub {
      owner = "bartman";
      repo = "git-wip";
      rev = "1c095e93539261370ae811ebf47b8d3fe9166869";
      hash = "sha256-rjvg6sTOuUM3ltD3DuJqgBEDImLrsfdnK52qxCbu8vo=";
    };
    preInstall = "cd vim";
  };
in {
  programs.neovim = {
    plugins = [
      git-wip
    ];
  };
}

Replacing lazygit with Snacks git pickers + gitsigns

Coverage notes for deciding whether Snacks pickers (snacks.nvim 2.31.0), gitsigns and vim-fugitive can replace lazygit. Verified against the installed plugin sources: lua/snacks/picker/config/sources.lua, lua/snacks/picker/actions.lua, lua/snacks/picker/source/git.lua, and the gitsigns mappings in the generated init.lua.

Short answer: for status → diff → stage → log → blame, yes, and mostly better. For rebase/squash, conflict resolution, stash juggling and undo, no — Snacks has no such actions at all.

Coverage

TaskToolVerdict
All changes incl. staged/untracked, per-file stage/unstagegit_status <Tab>, <c-r> discards (see snacks/picker/default.nix)parity
Hunk-level stage/unstage/restore, staged vs unstagedgit_diff (staged = true for the index side)better than lazygit
Line-level staginggitsigns visual stage_hunk (<leader>hs)better
Commit history, branch/tag decorationsgit_log + git_show previewparity
File history, per-line history, pickaxe search (-S)git_log_file, git_log_line, git_log promptlazygit has no equivalent
Branches: list/checkout/create/deletegit_branches (git_checkout, git_branch_add, git_branch_del)parity
Stash: list + applygit_stash, confirm = git_stash_applypartial
Committing, amend, push/pull/fetch, drag-to-commit—absent (use fugitive :Git commit, :Git push)
Interactive rebase / squash / fixup / drop / cherry-pick / revert / reset—absent (use fugitive :Git rebase -i)
Merge-conflict panel, per-side picks—absent (use fugitive :Gdiffsplit)
Stash drop/pop, reflog, bisect, worktree, submodule—absent

Exactly six git actions exist in this Snacks version: git_stage, git_restore, git_stash_apply, git_checkout, git_branch_add, git_branch_del.

git_log ships with confirm = "git_checkout", so Enter checks out the commit (detached HEAD) instead of opening it the way lazygit does. Rebind that before using the picker daily.

Co-author display

All three git_log* pickers read the compact %(graph) row, ref decorations and Co-authored-by trailers from the configured Git package. The shared formatter places the graph after the eight-character hash and before refs. Full names and refs are searchable.

Recommendation

Demote lazygit rather than replace it. Use git_status, git_diff and git_log* with gitsigns as the default for daily triage and staging, since they are better at the most frequent work: hunk/line staging with previews, and file/line history. Keep lazygit for the flows Snacks has nothing for: guided interactive rebase/squash, conflict resolution, stash and undo (its reflog-based undo is the hard-to-replace part).

A full replacement is feasible if drop maintenance of the lazygit package matters more than those flows: add a commit action (:Git commit), keys for push/pull, use :Git rebase -i <base> (the todo file opens in the editor) and :Gdiffsplit for conflicts. That is roughly 30-60 lines of keymaps plus habits, and it trades the lazygit co-author patch for a Snacks one.

gitsigns-nvim: git support

{src}: # local-args
{ config, pkgs, stdenv, lib, ... }:
let
  # TODO: npins tracks gitsigns.nvim main only for the unified diff view
  # (`:Gitsigns diffthis unified=true`), which no released version has yet. Switch back to
  # pkgs.vimPlugins.gitsigns-nvim once nixpkgs ships something newer than this pin.
  my-gitsigns-nvim = {
    plugin = pkgs.vimUtils.buildVimPlugin {
      name = "gitsigns.nvim";
      inherit src;
      patches = [ ./unified/main.patch ];
      doCheck = false;
      # Use hl_group+hl_eol instead of line_hl_group so that higher-priority
      # character-level extmarks (e.g. todo-comments) can override the line
      # background. Workaround for neovim/neovim#31151.
      postPatch = ''
        substituteInPlace lua/gitsigns/signs.lua \
          --replace-fail "line_hl_group = self:hl(ty, 'linehl')," \
                         "hl_group = self:hl(ty, 'linehl'), hl_eol = true, end_row = lnum, end_col = 0,"
      '';
    };
    type = "lua";
    config = /*lua*/ ''
      require('gitsigns').setup {
        numhl      = true,
        linehl     = true,

        current_line_blame = true,
        current_line_blame_formatter = '🖂 <author> 🖃 <author_time:%R> 🖆 <summary>',

        -- keymaps
        on_attach = function(bufnr)
          local gs = package.loaded.gitsigns

          local function map(mode, l, r, opts)
            opts = opts or {}
            opts.buffer = bufnr
            vim.keymap.set(mode, l, r, opts)
          end

          -- Navigation
          map('n', ']c', function()
            if vim.wo.diff then return ']c' end
            vim.schedule(function() gs.next_hunk() end)
            return '<Ignore>'
          end, {expr=true})

          map('n', ']C', function()
            if vim.wo.diff then return ']c' end
            vim.schedule(function() gs.next_hunk({target="all"}) end)
            return '<Ignore>'
          end, {expr=true})

          map('n', '[c', function()
            if vim.wo.diff then return '[c' end
            vim.schedule(function() gs.prev_hunk() end)
            return '<Ignore>'
          end, {expr=true})

          map('n', '[C', function()
            if vim.wo.diff then return '[c' end
            vim.schedule(function() gs.prev_hunk({target="all"}) end)
            return '<Ignore>'
          end, {expr=true})

          -- Actions
          map({'n', 'v'}, '<leader>hs', ':Gitsigns stage_hunk<CR>')
          map({'n', 'v'}, '<leader>hr', ':Gitsigns reset_hunk<CR>')
          map('n', '<leader>hS', gs.stage_buffer)
          map('n', '<leader>hu', gs.undo_stage_hunk)
          map('n', '<leader>hR', gs.reset_buffer)
          map('n', '<leader>hp', gs.preview_hunk)
          map('n', '<leader>hb', gs.blame)
          -- map('n', '<leader>tb', gs.toggle_current_line_blame)
          map('n', '<leader>hd', function() gs.diffthis(nil, { unified = true }) end)
          map('n', '<leader>hD', function() gs.diffthis(nil, { unified = false }) end)
          -- map('n', '<leader>td', gs.toggle_deleted)

          -- Text object
          map({'o', 'x'}, 'ih', ':<C-U>Gitsigns select_hunk<CR>')
        end
      }
      -- By default, staged hunks share the same background color as unstaged hunks.
      -- Clear GitSignsStagedXXXLn highlight groups to remove background from staged hunks.
      for _, ty in ipairs({'Add', 'Change', 'Delete', 'Topdelete', 'Changedelete'}) do
        local hl_name = 'GitSignsStaged' .. ty .. "Ln"
        vim.api.nvim_set_hl(0, hl_name, {})
      end
      -- The inline word-diff groups derive from TermCursor, which is a white background in
      -- sonokai: the text becomes unreadable in the unified diff view (it always word-diffs
      -- the deleted lines). Use the highlight diff mode shows in the split view instead.
      -- Gitsigns re-derives its defaults on ColorScheme, so reapply there as well.
      local function use_diff_text_inline()
        for _, hl_name in ipairs({'GitSignsAddInline', 'GitSignsChangeInline', 'GitSignsDeleteVirtLnInLine'}) do
          vim.api.nvim_set_hl(0, hl_name, {link = 'DiffText'})
        end
      end
      use_diff_text_inline()
      vim.api.nvim_create_autocmd('ColorScheme', {callback = use_diff_text_inline})
    '';
  };
in {
  programs.neovim = {
    plugins = [
      my-gitsigns-nvim
    ];
  };
}
{src}: # local-args

hbac-nvim: auto close buffer

{ pkgs, ... }: {
  programs.neovim = {
    plugins = [{
      plugin = pkgs.vimUtils.buildVimPlugin {
        name = "hbac.nvim";
        inherit src;
        doCheck = false;
      };
      type = "lua";
      config = /*lua*/ ''
        require("hbac").setup({
          autoclose     = true, -- set autoclose to false if you want to close manually
          threshold     = 20, -- hbac will start closing unedited buffers once that number is reached
          close_command = function(bufnr)
            vim.api.nvim_buf_delete(bufnr, {})
          end,
          close_buffers_with_windows = false, -- hbac will close buffers with associated windows if this option is `true`
        })
      '';
    }];
  };
}
{ pkgs, ... }: {
  programs.neovim = {
    plugins = [{
      plugin = pkgs.vimPlugins.leap-nvim;
      type = "lua";
      config = /*lua*/ ''
        vim.keymap.set({'n', 'x', 'o'}, 's', '<Plug>(leap)')
        vim.keymap.set('n',             'S', '<Plug>(leap-from-window)')
        '';
    }];
  };
}

lspconfig for C/C++ language

{ pkgs, ...}: {
  programs.neovim = {

C/C++

Why use clangd instead of ccls?

I encountered the problem below, when view https://github.com/xieby1/openc910 smart_run/logical/tb/sim_main1.cpp

LSP[ccls]: Error NO_RESULT_CALLBACK_FOUND: {
  error = {
    code = -32603,
    message = "failed to index /home/xieby1/Codes/openc910/smart_run/work/fputc.c"
  },
  id = 1,
  jsonrpc = "2.0"
}

After some searching, I found

GitHub: neovim: issue: lsp: NO_RESULT_CALLBACK_FOUND with ccls, rust-analyzer #15844

sapphire-arches found:

Something is causing the r-a LSP to send two replies with the same ID, see the attached log: lsp_debug.log

It would be nice for the neovim LSP to handle this more gracefully (not filling my screen with garbage and taking focus), but I do think the bug is in R-A here? The problem seems to be related to editor.action.triggerParameterHints?

GitHub: ccls: issue: I'm very confused about this question, it's about ccls or neovim built in LSP? #836

No one try to fix the two-replies problem in ccls. However, nimaipatel recommanded clangd_extensions.

    initLua = ''
      vim.lsp.config('clangd', {
        filetypes = { "c", "cc", "cpp", "c++", "objc", "objcpp", "cuda", "proto" }
      })
      vim.lsp.enable("clangd")
    '';
    plugins = [
      pkgs.vimPlugins.clangd_extensions-nvim
    ];
    extraPackages = with pkgs; [
      clang-tools
    ];
  };
}
{ pkgs, ... }: {
  home.packages = with pkgs; [
    universal-ctags
  ];
  home.file.exclude_ctags = {
    text = ''
      # exclude ccls generated directories
      --exclude=.ccls*
    '';
    target = ".config/ctags/exclude.ctags";
  };
  home.file.scala_ctags = {
    target = ".config/ctags/scala.ctags";
    text = ''
      --langdef=Scala
      --langmap=Scala:.scala
      --regex-Scala=/^[ \t]*class[ \t]*([a-zA-Z0-9_]+)/\1/c,classes/
      --regex-Scala=/^[ \t]*object[ \t]*([a-zA-Z0-9_]+)/\1/o,objects/
      --regex-Scala=/^[ \t]*trait[ \t]*([a-zA-Z0-9_]+)/\1/t,traits/
      --regex-Scala=/^[ \t]*case[ \t]*class[ \t]*([a-zA-Z0-9_]+)/\1/r,cclasses/
      --regex-Scala=/^[ \t]*abstract[ \t]*class[ \t]*([a-zA-Z0-9_]+)/\1/a,aclasses/
      --regex-Scala=/^[ \t]*def[ \t]*([a-zA-Z0-9_=]+)[ \t]*.*[:=]/\1/m,methods/
      --regex-Scala=/[ \t]*val[ \t]*([a-zA-Z0-9_]+)[ \t]*[:=]/\1/V,values/
      --regex-Scala=/[ \t]*var[ \t]*([a-zA-Z0-9_]+)[ \t]*[:=]/\1/v,variables/
      --regex-Scala=/^[ \t]*type[ \t]*([a-zA-Z0-9_]+)[ \t]*[\[<>=]/\1/T,types/
      --regex-Scala=/^[ \t]*import[ \t]*([a-zA-Z0-9_{}., \t=>]+$)/\1/i,includes/
      --regex-Scala=/^[ \t]*package[ \t]*([a-zA-Z0-9_.]+$)/\1/p,packages/
    '';
  };
  programs.neovim = {
    extraConfig = ''
      "" tags support, ';' means upward search, referring to http://vimdoc.sourceforge.net/htmldoc/editing.html#file-searching
      set tags=./tags;
    '';
    initLua = /*lua*/''
      local function ctags_definition()
        Snacks.picker.tags({
          search = vim.fn.expand("<cword>"),
          auto_confirm = true,
          jump = { tagstack = true, reuse_win = true },
        })
      end

      vim.keymap.set("n", "g]", ctags_definition)

      vim.keymap.set("n", "gd", function()
        local clients = vim.lsp.get_clients({
          bufnr = 0,
          method = "textDocument/definition",
        })

        -- No LSP supporting definitions: use ctags immediately.
        if #clients == 0 then
          return ctags_definition()
        end

        Snacks.picker.lsp_definitions({
          on_close = function(picker)
            -- LSP returned no definitions: fall back to ctags.
            if picker:empty() then
              vim.schedule(ctags_definition)
            end
          end,
        })
      end)
    '';
  };
}

nvim-lspconfig

{ pkgs, ... }: {
  imports = [
    ./c.nix
    ./ctags.nix
    # bash
    {programs.neovim={initLua="vim.lsp.enable('bashls')\n";extraPackages=[pkgs.bash-language-server];};}
    # html
    {programs.neovim={initLua="vim.lsp.enable('html')\n";extraPackages=[pkgs.vscode-langservers-extracted];};}
    {programs.neovim={initLua = "vim.lsp.enable('nixd')\n"; extraPackages=[pkgs.nixd];};}
    # python
    # TODO: maybe replace pyright (python) with ty (rust)? https://news.ycombinator.com/item?id=50717444
    {programs.neovim={initLua="vim.lsp.enable('pyright')\n";extraPackages=[pkgs.pyright];};}
    # typos
    {programs.neovim={initLua="vim.lsp.enable('typos_lsp')\n";extraPackages=[pkgs.typos-lsp];};}
    # xml
    {programs.neovim={initLua="vim.lsp.enable('lemminx')\n";extraPackages=[pkgs.lemminx];};}
    # markdown
    {programs.neovim={initLua="vim.lsp.enable('marksman')\n";extraPackages=[pkgs.marksman];};
      # index .mdx files
      # https://github.com/artempyanykh/marksman/issues/114
      xdg.configFile."marksman/config.toml".text = ''
        [core]
        markdown.file_extensions = ["md", "markdown", "mdx"]
      '';
    }
    # language checker
    {programs.neovim={initLua="vim.lsp.enable('harper_ls')\n";extraPackages=[pkgs.harper];};}
    ./rust
    ./scala.nix
    ./typst.nix
    ./lua.nix
    ./vue.nix
    # zig
    {programs.neovim={initLua="vim.lsp.enable('zls')\n";extraPackages=[pkgs.zls pkgs.zig];};}
    # veryl
    {programs.neovim = {initLua = "vim.lsp.enable('veryl_ls')\n";extraPackages = [pkgs.veryl];};}
  ];
  programs.neovim = {
    plugins = [{
      plugin = pkgs.vimPlugins.nvim-lspconfig;
      type = "lua";

Global mappings.

      config = /*lua*/ ''
        vim.lsp.log.set_level("OFF")

        -- See `:help vim.diagnostic.*` for documentation on any of the below functions
        vim.keymap.set('n', '<leader>d', vim.diagnostic.open_float)
        vim.keymap.set('n', '[d', function() vim.diagnostic.jump({ count=-1, float=true, severity = { min = vim.diagnostic.severity.WARN } }) end)
        vim.keymap.set('n', ']d', function() vim.diagnostic.jump({ count= 1, float=true, severity = { min = vim.diagnostic.severity.WARN } }) end)
        vim.keymap.set('n', '[D', function() vim.diagnostic.jump({ count=-1, float=true, severity = { min = vim.diagnostic.severity.INFO } }) end)
        vim.keymap.set('n', ']D', function() vim.diagnostic.jump({ count= 1, float=true, severity = { min = vim.diagnostic.severity.INFO } }) end)
        vim.keymap.set('n', '<space>d', function() Snacks.picker.diagnostics_buffer() end)
        vim.keymap.set('n', '<space>D', function() Snacks.picker.diagnostics() end)
        vim.diagnostic.config({
          float = {
            source = true,  -- Show the source (LSP server name)
          },
          signs = {
            text = {
              -- Do not show 'H' in the sign/number column.
              -- The main reason is harper_ls throws many hint diagnostics
              [vim.diagnostic.severity.HINT] = "",
            },
          },
        })

        -- Use LspAttach autocommand to only map the following keys
        -- after the language server attaches to the current buffer
        vim.api.nvim_create_autocmd('LspAttach', {
          group = vim.api.nvim_create_augroup('UserLspConfig', {}),
          callback = function(_args)
            vim.lsp.inlay_hint.enable(true, { bufnr = _args.buf })
            -- gd is defined in ./ctags.nix; it tries LSP definitions, then falls back to ctags.
            vim.keymap.set('n', 'gD', Snacks.picker.lsp_declarations)
            vim.keymap.set('n', 'gt', Snacks.picker.lsp_type_definitions)
            vim.keymap.set('n', 'gr', Snacks.picker.lsp_references)
            vim.keymap.set('n', 'gi', Snacks.picker.lsp_implementations)
            vim.keymap.set('n', 'K', vim.lsp.buf.hover)
            vim.keymap.set('n', '<space>rn', vim.lsp.buf.rename)

            -- make sure lsp/vim native indent(share/nvim/runtime/indent/python.vim)
            -- don't override my setting
            vim.opt.tabstop = 2
            vim.opt.shiftwidth = 2
          end,
        })
      '';
    }];
  };
}
{ pkgs, ... }: {
  programs.neovim={
    initLua = /*lua*/''
      -- ~/.local/share/emmylua_ls/logs/ is huge, over 13GB now, so disable logs completely.
      vim.lsp.config('emmylua_ls', {
        cmd = { 'emmylua_ls', '--log-path', 'none' },
      })
      vim.lsp.enable('emmylua_ls')
    '';
    extraPackages = [ pkgs.emmylua-ls ];
  };
  home.packages = [ pkgs.emmylua-check ];
  cachix_packages = [ pkgs.emmylua-ls pkgs.emmylua-check ];
}
{ pkgs, ... }: {
  programs.neovim={
    initLua = /*lua*/ ''
      vim.lsp.config("rust_analyzer", {
        settings = {
          ["rust-analyzer"] = {
            cargo = {
              -- goto definition of rust's lib needs this
              sysrootSrc = "${pkgs.rustPlatform.rustLibSrc}",
            },
          }
        },
      })
      vim.lsp.enable("rust_analyzer")
    '';
    extraPackages = [ pkgs.rust-analyzer ];
  };
  home.packages = [
    pkgs.cargo
    # prevent rust_analyzer throw error: `rust-analyzer: no sysroot [macro-error]`
    pkgs.rustc
  ];
}

Rust-Analyzer Go-to-Definition Quirks with Operators

Summary

When using gd (go-to-definition) in Neovim with rust-analyzer, you may find that placing the cursor on certain operators (e.g. [ in v["name"]) jumps to the definition of an adjacent identifier instead of the operator's trait implementation.

Root Cause: pick_best_token Scoring

In crates/ide/src/goto_definition.rs, rust-analyzer uses pick_best_token to select which syntax token at the cursor position should be resolved:

#![allow(unused)]
fn main() {
let original_token = pick_best_token(file.token_at_offset(offset), |kind| match kind {
    IDENT | INT_NUMBER | LIFETIME_IDENT | T![self] | T![super] | T![crate] | T![Self] | COMMENT => 4,
    // index and prefix ops
    T!['['] | T![']'] | T![?] | T![*] | T![-] | T![!] => 3,
    kind if kind.is_keyword(edition) => 2,
    T!['('] | T![')'] => 2,
    kind if kind.is_trivia() => 0,
    _ => 1,
})?;
}

The problem: LSP positions are zero-based character offsets. When your cursor is on a single-character operator (e.g. [), the sent position is technically the boundary before that character. At this boundary, token_at_offset returns both the preceding identifier and the operator. Since IDENT scores 4 and [ scores only 3, pick_best_token chooses the identifier — so rust-analyzer resolves the variable instead of the IndexExpr.

This only affects single-character tokens that share a boundary with higher-scored tokens. Multi-character operators like !=, .., += are usually safe because the cursor falls inside the token, not at a boundary.


Token Score Reference

Token KindScoreExamples
Identifiers, numbers, self, super, crate, Self, comments4foo, 123, // comment
Brackets [ ], ?, *, -, !3v[idx], *ptr, -x, foo!()
Keywords, ( )2fn, let, await, (, )
Other operators1+, /, %, =, ., >
Whitespace / trivia0spaces, newlines, tabs

Practical Tricks and Examples

Index Operator []

Problem: Cursor on [ in v["name"] goes to definition of v.

Cursor PositionWhat HappensWhy
On [Goes to vBoundary after v (4) vs [ (3)
On "Goes to Index::indexBoundary after [ (3) vs " (1)
On ]Goes to Index::indexBoundary after " (1) vs ] (3)

Trick: Use ] or the opening " of the index expression instead of [.

#![allow(unused)]
fn main() {
let x = v["name"];
//        ^ put cursor here (on `]`) for Index trait
//         ^ or here (on `"`) also works
}

For v[idx] where idx is an identifier:

  • Cursor on idx -> boundary after [ (3) vs idx (4) -> goes to idx
  • Cursor on ] -> goes to Index::index

Binary Operators (+, -, *, /, %)

Problem: Cursor on + in a + b goes to definition of a.

Cursor PositionWhat HappensWhy
On aGoes to aIt's an identifier (4)
On +Goes to aBoundary after a (4) vs + (1)
On space after +Goes to Add::addBoundary after + (1) vs space (0)
On bGoes to bIt's an identifier (4)

Trick: Place the cursor on the whitespace immediately after the operator.

#![allow(unused)]
fn main() {
let sum = a + b;
//            ^ cursor on this space -> goes to Add trait
}

Note: This requires spaces around the operator (which rustfmt enforces). For a+b without spaces, there is no cursor position that selects + over the operands.


Comparison Operators (>, <, ==, !=)

Rust-analyzer has special handling (find_definition_for_comparison_operators) for !=, <, <=, >, >=, but pick_best_token can still steal the token.

OperatorCursor OnResult
>> itselfBoundary after left operand -> left operand wins (4 vs 1)
>Space after >Goes to PartialOrd::partial_cmp (1 vs 0)
!=! inside tokenUsually safe (multi-char token, inside !=)

Trick: Same as binary operators — use the whitespace after the operator.

#![allow(unused)]
fn main() {
if a > b {
//      ^ cursor on this space -> goes to PartialOrd
}
}

Prefix Operators (-, *, !)

OperatorCursor OnResult
-xOn -Boundary before - (start of expr) -> usually only - is returned, so this often works
!xOn !Similar to -, usually works
*ptrOn *Usually works

Prefix operators are generally safer because there is no high-scoring identifier to the left inside the same expression. However, in contexts like a * b (binary), the same rules as binary operators apply.


Try Operator ?

Cursor PositionResult
On ?Usually works (score 3, often no higher-scored neighbor to the left at the same boundary)
On space after ?Goes to From::from (if applicable)
#![allow(unused)]
fn main() {
let x = maybe_value?;
//                    ^ cursor on this space -> goes to From trait
}

Macro Invocation !

For foo!(), cursor on ! sits at the boundary between foo and !. foo (4) beats ! (3), so pick_best_token selects foo. This is actually fine because both tokens resolve to the same macro definition.


General Rule

When go-to-definition on a single-character operator sends you to the wrong place:

  1. Move one character to the right (onto whitespace or the next token). If the operator scores higher than what you land on, rust-analyzer will "fall back" to the operator.
  2. For [], prefer ] over [.
  3. For binary operators, prefer the whitespace immediately after the operator.

Limitations

  • Compact code without spaces (e.g. a+b) offers no reliable cursor position for binary operators, because every boundary has the operator (score 1) competing with an identifier (score 4).
  • This behavior is inherent to rust-analyzer's goto_definition token selection. The ideal fix is upstream in rust-analyzer: pick_best_token should consider whether the offset unambiguously belongs to a lower-scored token when the user is clearly targeting it.
# If metals throw errors, check <workspace>/.metals/metals.log
# Try following steps:
# * rm -rf .metals/ ~/.bloop/* ~/.cache/mill/ ~/.cache/coursier/
# * check all dependent libs have been downloaded to workspace, e.g. update git submodule
{ config, pkgs, ... }: let
  jre-with-proxy = pkgs.runCommand "jre-with-proxy" {
    nativeBuildInputs = [pkgs.makeWrapper];
    meta.platforms = pkgs.jre.meta.platforms;
    passthru = {
      inherit (pkgs.jre) version;
      home = "${jre-with-proxy}";
    };
  } ''
    mkdir -p $out
    ${pkgs.lndir}/bin/lndir -silent ${pkgs.jre} $out
    wrapProgram $out/bin/java --add-flag -Dhttp.proxyHost=127.0.0.1 \
                              --add-flag -Dhttp.proxyPort=${toString config.proxyPort} \
                              --add-flag -Dhttps.proxyHost=127.0.0.1 \
                              --add-flag -Dhttps.proxyPort=${toString config.proxyPort}
    # Metals will check the `release` in java home.
    # If not exist, it will throw "release file missing JAVA_VERSION property - using Bloop's JVM version"
    # The `release file is located in lib/openjdk/release`
    ln -s $out/lib/openjdk/release $out/
  '';
in {
  programs.neovim = {
    initLua = /*lua*/ ''
      vim.lsp.config("metals", {
        init_options = {
          statusBarProvider = "off",
        },
      })
      vim.lsp.enable("metals")
    '';
    extraPackages = [
      (pkgs.metals.override {
        jre = jre-with-proxy;
        extraJavaOpts = toString [
          # Preserve the defaults in the pinned Nixpkgs Metals package.
          "-XX:+UseG1GC -XX:+UseStringDeduplication -Xss4m -Xms100m"
          /*
            User configuration options can optionally be provided via server properties using the -Dmetals. prefix.
            For more user configuration, see: https://scalameta.org/metals/docs/integrations/new-editor/#metals-user-configuration
          */
          # [Note1]: use mill in system, preventing the situation where I can compile but I cannot use metals
          "-Dmetals.millScript=mill"

          # If mill command (specified by millScript) is not found,
          # then metals will use java to run mill.contrib.bloop.Bloop/install
          "-Dmetals.javaHome=${jre-with-proxy}"

          # Cannot go-to-definition in build.sc.
          # The problem can be solved by using mill-bsp as bsp, instead of using bloop,
          # for more details see: https://github.com/com-lihaoyi/mill/discussions/2688
          # According metals doc:
          #   "Using Mill with Bloop is the current preferred way by Metals."
          # I have tried defaultBspToBuildTool=true, which does not work!
          #
          # I learned from nvim-metals the following code to send `bsp-switch` command to metals.
          # vim.lsp.get_client_by_id(1):request("workspace/executeCommand", {command="metals.bsp-switch"})
          #
          # NOTED: If using mill-bsp, make sure run `mill -i mill.bsp.BSP/install` before using.
          "-Dmetals.defaultBspToBuildTool=true"
        ];
      })
      (pkgs.coursier.override { jre = jre-with-proxy; })
    ];
    # extraWrapperArgs = [
    #   "--set-default" "JAVA_HOME" "${jre-with-proxy}"
    # ];
  };
  # [Paired with above Note1]:
  # If system does not have mill, then metals will use a 0.5.0 mill script to run:
  # Optional absolute path to a mill executable to use for running
  # `mill mill.contrib.bloop.Bloop/install`.
  # This mill needs JAVA_HOME.
  programs.zsh.envExtra = /*bash*/''
    # make .metals/mill happy.
    export JAVA_HOME=${jre-with-proxy};
  '';

  # nvim-metals proxy for bloop
  home.file.jvmopts = {
    text = ''
      -Dhttps.proxyHost=127.0.0.1
      -Dhttps.proxyPort=${toString config.proxyPort}
      -Dhttp.proxyHost=127.0.0.1
      -Dhttp.proxyPort=${toString config.proxyPort}
    '';
    target = ".bloop/.jvmopts";
  };
}
{ pkgs, ... }: {
  programs.neovim = {
    plugins = [{
      # TODO: slow on huge pdf? Remove it, use TypstExportPdfOnSaveEnable?
      plugin = pkgs.vimPlugins.typst-preview-nvim;
      type = "lua";
      config = /*lua*/ ''
        require ('typst-preview').setup({
          open_cmd = "single-tab %s",
        })
      '';
    }];
    initLua = /*lua*/ ''
      -- https://www.reddit.com/r/neovim/comments/1iiqwb1/treesitter_injection_and_priority_issues/
      -- The `@lsp.type.comment.typst` can be obtained by hovering on the text, then `:Inspect`
      -- TLDR: I want to use typst injections.scm,
      --       while treesitter default highlight priority is 100,
      --       typst lsp highlight priority is 125.
      -- My failed attempts:
      -- * (#set! priority ): it only works in highlights.scm, does not work in injections.scm
      --   * See: https://github.com/nvim-treesitter/nvim-treesitter/issues/3110
      -- * Turn of tinymist lsp highlight:
      --   * `semanticTokens = "disable"` does not turn off tinymist lsp syntax highlight.
      -- So current my approach is keeping tinymist lsp highlight,
      -- only clear @lsp.type.comment.typst group.
      vim.api.nvim_set_hl(0, "@lsp.type.comment.typst", {})
      vim.lsp.enable('tinymist')
      vim.api.nvim_create_user_command("TypstExportPdfOnSaveEnable", function(args)
        -- more settings see https://github.com/Myriad-Dreamin/tinymist/editors/neovim/Configuration.md
        vim.lsp.config("tinymist", {settings = {exportPdf = "onSave"}})
        -- compile and open pdf in evince
        local file_typ = vim.fn.expand('%:p')
        local file_pdf = vim.fn.expand('%:p:r') .. '.pdf'
        vim.system({'bash', '-c',
          'typst compile ' .. file_typ .. ' ' .. file_pdf .. ';' ..
          'evince ' .. file_pdf
        }, { text = true }, function()end)
        print("exportPdf = onSave")
        -- restart tinymist lsp, see `:h vim.lsp.enable`
        vim.lsp.enable("tinymist", false)
        vim.lsp.enable("tinymist", true)
      end, {})
      -- Why called TypstExportPdfOnSaveXDisable instead of TypstExportPdfOnSaveDisable:
      -- to make TypstExportPdfOnSaveXDisable rank after TypstExportPdfOnSaveEnable
      vim.api.nvim_create_user_command("TypstExportPdfOnSaveXDisable", function(args)
        vim.lsp.config("tinymist", {settings = {exportPdf = "never"}})
        print("exportPdf = never")
        -- restart tinymist lsp, see `:h vim.lsp.enable`
        vim.lsp.enable("tinymist", false)
        vim.lsp.enable("tinymist", true)
      end, {})
    '';
    extraPackages = [ pkgs.tinymist ];
  };
  home.packages = [
    # TODO: use pkgs.typst, once stable nixpkgs reaches typst 0.15.0.
    # NOTE: Why I need typst 0.15.0?
    #  It adds a `path` type (the old `path()` drawing fn was renamed to `curve()`, freeing the name).
    #  A path is resolved relative to the file where it's written, so it can be passed
    #  to 3rd-party libs and still point at my document's files.
    #  Without it, a lib receiving a relative path string would resolve it against the lib's
    #  own location; the workaround is passing `read("./relative_path")`'s result instead.
    pkgs.typst
  ];
}
{ pkgs, ... }: {
  programs.neovim = {
    initLua = /*lua*/ ''
      local vue_language_server_path = '${pkgs.vue-language-server}/lib/language-tools/packages/language-server'
      vim.lsp.config('vtsls', {
        settings = {
          vtsls = {
            tsserver = {
              globalPlugins = {
                {
                  name = '@vue/typescript-plugin',
                  location = vue_language_server_path,
                  languages = { 'vue' },
                  configNamespace = 'typescript',
                },
              },
            },
          },
        },
        filetypes = { 'javascript', 'javascriptreact', 'typescript', 'typescriptreact', 'vue' },
      })
      vim.lsp.enable('vtsls')
      vim.lsp.enable('vue_ls')
    '';
    extraPackages = [ pkgs.vue-language-server pkgs.vtsls ];
  };
}
{ pkgs, ... }: {
  programs.neovim = {
    plugins = [{
      plugin = pkgs.vimPlugins.lualine-nvim.overrideAttrs (old: {
        patches = (old.patches or []) ++ [
          ./lualine-show-identical-bg-section-separators.patch
        ];
      });
      type = "lua";
      config = /*lua*/ ''
        local inactive_sections = {
          lualine_a = { {'filename', path = 1 --[[relative path]],}, },
          lualine_b = {
            'branch',
            { 'diagnostics', sections = { 'error', 'warn', 'info', --[['hint']] }, },
          },
          lualine_c = {},
          lualine_x = {},
          lualine_y = { { 'filetype', icons_enabled = false } },
          lualine_z = {
            'location',
            { 'progress', padding = {left = 1, right = 0 }, },
          },
        }

        local sections = vim.tbl_extend('force', inactive_sections, {
          lualine_c = {
            function() return require('nvim-navic').get_location() end,
          },
        })

        require("lualine").setup({
          options = {
            padding = 0,
            theme = (function()
              local function hl(name)
                local highlight = vim.api.nvim_get_hl(0, { name = name })
                return {
                  fg = highlight.fg and string.format("#%06x", highlight.fg) or nil,
                  bg = highlight.bg and string.format("#%06x", highlight.bg) or nil,
                  gui = highlight.bold and "bold" or nil,
                }
              end

              local active = hl("StatusLine")
              local inactive = hl("StatusLineNC")

              return {
                normal =   { a =   active, b =   active, c =   active },
                insert =   { a =   active, b =   active, c =   active },
                visual =   { a =   active, b =   active, c =   active },
                replace =  { a =   active, b =   active, c =   active },
                command =  { a =   active, b =   active, c =   active },
                inactive = { a = inactive, b = inactive, c = inactive },
              }
            end)(),
            component_separators = { left = "", right = ""},
            section_separators = { left = '┇', right = '┇'},
          },
          inactive_sections = inactive_sections,
          sections = sections,
        })
      '';
    }];
  };
}
# # lz.n vs lazy.nvim:
# - lazy.nvim contains too many unnecessary features (unrelated to lazy)!
{ pkgs, ... }: {
  programs.neovim.plugins = [
    pkgs.vimPlugins.lz-n
  ];

  imports = [
    ./module
  ];
  my.neovim.lz-n = [];
}
{ config, lib, ... }:
let
  cfg = config.my.neovim.lz-n;
in {
  options.my.neovim.lz-n = lib.mkOption {
    type = lib.types.listOf lib.types.attrs;
    default = [];
    description = ''
      List of lz.n plugin specs.

      Each element is an attribute set with the following keys:
        - plugin:  The Nix package of the Neovim plugin (required).
        - spec:    Additional lz.n spec attributes (optional).
                   Common attributes include:
                     - event:   Lazy-load on event(s) (e.g. "BufRead").
                     - cmd:     Lazy-load on command(s) (e.g. "Snacks").
                     - keys:    Lazy-load on keymap(s). Each entry is a Nix list
                                that serializes to a Lua array. Examples:
                                  keys = [ "<leader>ff" ];
                                  keys = [ [ "<leader>ff" "<cmd>lua Snacks.picker.files()<cr>" ] ];
                                  keys = [ [ "<leader>ff" "<cmd>lua Snacks.picker.files()<cr>" { desc = "Find files"; } ] ];
                     - ft:      Lazy-load on filetype(s).
                     - before:  Lua function to run before loading.
                                Must be a Lua function, not a plain string. Use:
                                  before = lib.generators.mkLuaInline "function(self) ... end";
                     - after:   Lua function to run after loading. Same as before.
                                This is where plugin setup() calls belong:
                                  after = lib.generators.mkLuaInline '''function(self) require("plugin").setup({}) end''';
                     - colorscheme: Lazy-load on colorscheme(s).
                                Set to the colorscheme name(s) (string or list of strings).
                   See https://github.com/nvim-neorocks/lz.n for full spec.

      Example:
        {
          plugin = pkgs.vimPlugins.snacks-nvim;
          spec = {
            cmd = [ "Snacks" ];
            keys = [
              [ "<leader>ff" "<cmd>lua Snacks.picker.files()<cr>" { desc = "Find files"; } ]
            ];
          };
        }
    '';
  };

  config = lib.mkIf (cfg != []) {
    programs.neovim.plugins = map (entry: {
      plugin = entry.plugin;
      type = "lua";
      config = let
        _1_spec = entry.spec // {"1" = entry.plugin.pname;};

        /*_1_spec_lua_str = {
          ["1"] = <pname>,
          ...
        }*/
        _1_spec_lua_str = lib.generators.toLua {} _1_spec;

        /*spec_lua_str = {
          <pname>,
          ...
        }*/
        # HACK: replaceString replaces ALL occurrences — corrupts output if any spec
        # value contains the literal ["1"] =  (e.g. in a before/after inline Lua string).
        spec_lua_str = lib.replaceString ''["1"] = '' "" _1_spec_lua_str;
      in ''
        require("lz.n").load(${spec_lua_str})
      '';
      optional = true;
    }) cfg;
  };
}
let
  pkgs = import <nixpkgs> {};
  hm = import <home-manager/modules> {
    inherit pkgs;
    configuration = {
      imports = [./.];
      home = { stateVersion = "25.11"; username = "dummy"; homeDirectory = "/dummy"; };
      my.neovim.lz-n = [{
        plugin = pkgs.vimPlugins.copilot-lua;
        spec = {
          cmd = "Copilot";
          after = pkgs.lib.generators.mkLuaInline ''function() require("copilot").setup() end'';
        };
      }];
    };
  };
  pluginEntry = builtins.elemAt (builtins.filter (p: p ? optional && p.optional) hm.config.programs.neovim.plugins) 0;
in pkgs.lib.debug.throwTestFailures { failures = pkgs.lib.runTests {
  test-plugin = {
    expr = pluginEntry.plugin.pname;
    expected = "copilot.lua";
  };
  test-type = {
    expr = pluginEntry.type;
    expected = "lua";
  };
  test-optional = {
    expr = pluginEntry.optional;
    expected = true;
  };
  test-config-does-not-have-plugin = {
    expr = pkgs.lib.hasInfix ''["plugin"] ='' pluginEntry.config;
    expected = false;
  };
  test-config-has-load = {
    expr = pkgs.lib.hasInfix ''require("lz.n").load'' pluginEntry.config;
    expected = true;
  };
  test-config-has-pname = {
    expr = pkgs.lib.hasInfix ''"copilot.lua"'' pluginEntry.config;
    expected = true;
  };
  test-config-has-cmd = {
    expr = pkgs.lib.hasInfix ''["cmd"] = "Copilot"'' pluginEntry.config;
    expected = true;
  };
  test-config-has-after = {
    expr = pkgs.lib.hasInfix ''require("copilot").setup()'' pluginEntry.config;
    expected = true;
  };
}; }
{ pkgs, ... }: {
  programs.neovim = {
    plugins = [{
      plugin = pkgs.vimPlugins.markdown-preview-nvim.overrideAttrs (old: {
        postPatch = toString [
        # use cjk2ch.js
        (let
          cjk2ch_js = pkgs.fetchurl {
            url = "https://github.com/xieby1/markdown_revealjs/raw/c9c91257d06b63adcf67d3464efbc392f55677ff/share/markdown_revealjs/cjk2ch.js";
            sha256 = "0d2xjy8g89zq8677ggklfpr3f9jd8lny37lbcdqr0asvmiqjgx9x";
          };
        # 添加cjk2ch.js
        # 给混淆过的index.js打补丁(这生成代码居然直接放git,😼😼😼啧啧啧,源码是index.jsx)
        # 通过code:not(:has(span))来识别哪些code可能是ascii art
        # 在refreshContent最后,即renderDot的后面调用cjk2ch(...)
        in ''
          cp ${cjk2ch_js} app/_static/cjk2ch.js
          sed -i 's,<head>,&<script src="/_static/cjk2ch.js"></script>,' app/out/index.html
          sed -i 's,}var e;G(),;cjk2ch("code:not(:has(span))");&,' app/out/_next/static/s7O4q0ISzv1r8jtwIkXLb/pages/index.js
        '')
        # set port to 7700~7799
        ''
          sed -i 's/port = port ||.*/port = port || (7700 + Number(`''${Date.now()}`.slice(-2)))/' app/server.js
        ''
        # set line-height of <pre></pre>
        ''
          sed -i 's/line-height: 1.45;/line-height: 1em;/' app/_static/markdown.css
        ''
        # upgrade mermaid
        (let
          mermaid_js = pkgs.fetchurl {
            url = "https://cdn.jsdelivr.net/npm/mermaid@11.9.0/dist/mermaid.min.js";
            sha256 = "1658hsyxrg9sh3nmafsisiylsw7z436dznpgv8akhdhp84vx8ghb";
          };
        in ''
          cp ${mermaid_js} app/_static/mermaid.min.js
        '')];
      });
      type = "viml";
      config = ''
        " allow LAN
        let g:mkdp_open_to_the_world = 1
        let g:mkdp_theme = 'light'

        " Use chromium-like browser to open rendered markdown instead of firefox,
        " because firefox only copy css in selected region, causing lost of styles!
        " See same bug report here:
        " https://discourse.mozilla.org/t/copy-rich-text-from-firefox-does-not-capture-style/97862/3
        function OpenMarkdownPreview (url)
          " run chromium in app mode in background
          execute "silent ! chromium --app='" . a:url . "' &"
        endfunction
        let g:mkdp_browserfunc = 'OpenMarkdownPreview'
      '';
    }];
  };
}

mini-nvim: a nvim distro

mini-nvim is wonderful nvim plugin! I found it due to below link: indent-blankline.nvim is too complex. However, it does not support basic functionality like highlight current indentation See: https://github.com/lukas-reineke/indent-blankline.nvim/issues/649

{ config, pkgs, stdenv, lib, ... }:
let
  my-mini-nvim = {
    plugin = pkgs.vimPlugins.mini-nvim;
    type = "lua";
    config = ''
      require('mini.indentscope').setup{
        options = {
          try_as_border = true,
        },
      }

      -- mini.animate looks promising, and can totally replace vim-smoothie
      -- However, bugs seem exist:
      -- * touchpad scroll become slow
      -- * background color blinks when create window
      -- * background color broken after q::q
      -- require('mini.animate').setup()

      require('mini.icons').setup()
    '';
  };
in {
  programs.neovim = {
    plugins = [
      my-mini-nvim
    ];
  };
}
{ config, pkgs, lib, ai, ... }: {
  # mkAfter makes sure statusline setting is after nvim-nav.nix
  programs.neovim.plugins = lib.mkAfter [pkgs.vimPlugins.plenary-nvim {
    plugin = pkgs.vimPlugins.minuet-ai-nvim;
    type = "lua";
    config = /*lua*/ ''
      require('minuet').setup {
        -- Disable auto complete, only trigger minuet manually
        blink = { enable_auto_complete = false },
        -- FIM is usually better for completion;
        -- use Claude here because MiniMax's Anthropic API works better.
        provider = 'openai_fim_compatible',
        provider_options = {
          openai_fim_compatible = {
            api_key = function() return '${ai.deepseek.api_key}' end,
            api_key = 'DEEPSEEK_API_KEY',
            name = 'deepseek',
            optional = {
              max_tokens = 256,
              top_p = 0.9,
            },
          },
        },
      }

      function update_minuet_statusline()
        local minuet = require("minuet")
        vim.o.statusline = string.gsub(vim.o.statusline, "[ᯤ]*$",
          minuet.config.blink.enable_auto_complete and "ᯤ" or "")
      end
      vim.keymap.set({'n','i'}, '<S-A-a>', function()
        local minuet = require("minuet")
        minuet.config.blink.enable_auto_complete = not minuet.config.blink.enable_auto_complete
        update_minuet_statusline()
      end)
      update_minuet_statusline()
    '';
  }];
}

nvim-config-local: secure load local vim config

{ pkgs, ... }:
let
  my-nvim-config-local = {
    plugin = pkgs.vimPlugins.nvim-config-local;
    type = "lua";
    config = ''
      require('config-local').setup {
        config_files = { ".nvim.lua", ".nvimrc", ".exrc", ".vimrc" },
        lookup_parents = true,
        silent = true,
      }
    '';
  };
in {
  programs.neovim = {
    plugins = [
      my-nvim-config-local
    ];
  };
}
{ pkgs, ... }: {
  programs.neovim = {
    plugins = [{
      plugin = pkgs.vimPlugins.nvim-navic;
      type = "lua";
      config = ''
        require("nvim-navic").setup {
          lsp = {
            auto_attach = true,
            -- vue_ls forwards TypeScript requests to vtsls, so .vue buffers attach both.
            -- nvim-navic can use only one LSP per buffer; prefer vtsls to avoid warnings.
            preference = { "vtsls", "vue_ls" },
          },
        }
      '';
    }{
      plugin = pkgs.vimPlugins.nvim-navbuddy;
      type = "lua";
      config = ''
        require("nvim-navbuddy").setup {
          lsp = {
            auto_attach = true,
          },
          mappings = {
            ["<S-Tab>"] = require("nvim-navbuddy.actions").parent(),
            ["<Tab>"]   = require("nvim-navbuddy.actions").children(),
          },
        }
      '';
    }];
  };
}
{ pkgs, ... }: {
  programs.neovim = {
    plugins = [{
      plugin = pkgs.vimPlugins.nvim-treesitter-context;
      type = "lua";
      config = /*lua*/ ''
        require'treesitter-context'.setup({
          multiwindow = true,
          max_lines = "20%",
        })
        vim.cmd("hi TreesitterContextBottom gui=underline guisp=Grey")
        vim.cmd("hi link TreesitterContext NONE")
        vim.keymap.set("n", "<leader>c", "<Cmd>TSContext toggle<CR>")
      '';
    }];
  };
}
{ d2-src, veryl-src, merman-src }: # local-args

nvim-treesitter: languages parsing

{ pkgs, ... }: let
  mermaid-src = merman-src + "/distribution/tree-sitter-mermaid";
in {
  programs.neovim = {
    plugins = [{
      # Available languages see:
      #   https://github.com/nvim-treesitter/nvim-treesitter
      # see `pkgs.tree-sitter.builtGrammars.`
      # with `tree-sitter-` prefix and `-grammar` suffix removed
      plugin = (pkgs.vimPlugins.nvim-treesitter.withPlugins (_:
      (builtins.filter (grammar: grammar.language != "mermaid")
        pkgs.vimPlugins.nvim-treesitter.allGrammars) ++ [
        # The monaqa grammar is unmaintained and misparses continued flowchart edges.
        (pkgs.tree-sitter.buildGrammar {
          language = "mermaid";
          version = "0.3.5";
          src = mermaid-src;
        })

When edit a large d2 file using d2-vim, the cursor movement becomes lag. However, tree-sitter-d2 works fluently. So I replace the d2-vim with tree-sitter-d2.

        (pkgs.tree-sitter.buildGrammar {
          language = "d2";
          version = pkgs.lib.removePrefix "v" d2-src.version;
          src = d2-src;
        })
        (pkgs.tree-sitter.buildGrammar {
          language = "veryl";
          # Only checked against tree-sitter.json metadata, no functional impact
          version = "0.1.0";
          src = veryl-src;
        })
      ])).overrideAttrs (old: {
        # Merman's CST requires its own queries rather than monaqa's.
        postInstall = (old.postInstall or "") + ''
          mkdir -p $out/queries/mermaid
          cat ${mermaid-src}/queries/portable/highlights.scm \
            ${mermaid-src}/queries/neovim/highlights.scm \
            > $out/queries/mermaid/highlights.scm
          for query in folds indents injections; do
            cp ${mermaid-src}/queries/neovim/$query.scm \
              $out/queries/mermaid/$query.scm
          done
        '';
      });
      type = "lua";
      config = /*lua*/''
        vim.filetype.add({ extension = { mdx = "markdown", veryl = "veryl" } })
        vim.api.nvim_create_autocmd('FileType', {
          callback = function(ev)
            local lang = vim.treesitter.language.get_lang(vim.bo[ev.buf].filetype)
            if lang and vim.treesitter.language.add(lang) then
              vim.treesitter.start(ev.buf, lang)
            end
          end,
        })
      '';
    }];
  };
}

nvim-window-picker

{ pkgs, ... }: {
  programs.neovim = {
    plugins = [{
      plugin = pkgs.vimPlugins.nvim-window-picker;
      type = "lua";
      config = ''
        require 'window-picker'.setup({
          selection_chars = 'abcdefghijklmnopqrstuvwxyz',
          picker_config = {
            statusline_winbar_picker = {
              selection_display = function(char, windowid)
                return '[' .. char .. ']' .. vim.o.statusline
              end,
            },
          },
          show_prompt = false,
          highlights = {
            statusline = {
              unfocused = {
                fg = '#2c2e34',
                bg = '#7f8490',
                bold = true,
              },
            },
          },
        })
        vim.keymap.set('n', '<C-j>', function()
          vim.api.nvim_set_current_win( require('window-picker').pick_window() )
        end)
        vim.keymap.set('n', '<C-w>j', function()
          vim.api.nvim_set_current_win( require('window-picker').pick_window() )
        end)
      '';
    }];
  };
}
{src}: # local-args
{ pkgs, ... }: {
  programs.neovim = {
    plugins = [{
      plugin = pkgs.vimPlugins.outline-nvim;
      type = "lua";
      config = /*lua*/ ''
        require("outline").setup({
          -- Outline.nvim seems not support setup multiple times
          -- So I merge outline-treesitter-provider's config here
          providers = {
            -- append "treesitter" to original priority
            priority = (function() -- start of a local scope
              local original = require("outline.config").defaults.providers.priority
              table.insert(original, "treesitter")
              return original
            end)(), -- end of a local scope
          },
          outline_window = {
            relative_width = false,
          },
          guides = {
            enabled = false, -- I already have mini indentscope
          },
          symbol_folding = {
            autofold_depth = 99,
          },
          keymaps = {
            close = {}, -- disable close key
          },
        })
        vim.keymap.set('n', '<leader>o', require('outline').toggle)
      '';
    }(
      pkgs.vimUtils.buildVimPlugin {
        name = "outline-treesitter-provider.nvim";
        inherit src;
        doCheck = false;
      }
    )];
  };
}
{ ... }: {
  # Ctrl+Shift+V keeps plain-text paste, including text selected in a terminal.
  # :PasteMd explicitly converts clipboard HTML to Markdown.
  programs.neovim.initLua = /*lua*/ ''
    vim.api.nvim_create_user_command("PasteMd", function()
      local html = vim.system(
        { "wl-paste", "-n", "-t", "text/html" }, { text = true }
      ):wait()
      if html.code ~= 0 or html.stdout == "" then
        error("PasteMd: clipboard has no text/html", 0)
      end

      local md = vim.system(
        {
          "pandoc", "-f", "html-native_divs-native_spans",
          "-t", "gfm-raw_attribute-raw_html", "--wrap=none",
        },
        { stdin = html.stdout, text = true }
      ):wait()
      if md.code ~= 0 or md.stdout == "" then
        error("PasteMd: pandoc could not convert the clipboard HTML", 0)
      end

      -- Drop embedded toolbar icons; keep ordinary image URLs.
      local text = md.stdout:gsub("!%[([^%]]*)%]%(data:image/[^)]*%)", "")
      local lines = vim.split(text:gsub("\n$", ""), "\n", { plain = true })
      vim.api.nvim_put(lines, "c", true, true)
    end, { desc = "Paste clipboard HTML as Markdown" })
  '';
}
{ pkgs, ... }: let
  rustowl-pkgs = (pkgs.flake-compat {
    src = pkgs.fetchFromGitHub {
      owner = "nix-community";
      repo = "rustowl-flake";
      rev = "a84881d43ecd4914b6e2791f7777c6133f489bf9";
      hash = "sha256-ejraI1mCGebB98mH/cIR+GG1UwDTVnZojrHPLFErCxE=";
    };
  }).defaultNix.packages."${pkgs.stdenv.system}";
  rustowl = rustowl-pkgs.rustowl;
  rustowl-nvim = rustowl-pkgs.rustowl-nvim.overrideAttrs (old: {
    # This patch because:
    # The ftplugin/*.lua, is loaded before init.lua, see `:h init.lua`
    # As a result the user config does not work.
    # (It is this commit cause it: https://github.com/cordx56/rustowl/pull/48)
    # So we move ftplugin/rust.lua to lua/rustowl/autosetup.lua,
    # and call require("rustowl/autosetup") after require("rustowl").setup
    postPatch = ''
      mv ftplugin/rust.lua lua/rustowl/autosetup.lua
    '';
  });
in {
  programs.neovim = {
    plugins = [{
      plugin = rustowl-nvim;
      type = "lua";
      config = /*lua*/ ''
        require("rustowl").setup({
          auto_enable = true,
          highlight_style = 'underline',
          -- drawio preset border colors
          colors = {
            lifetime = '#82B366',
            imm_borrow = '#6C8EBF',
            mut_borrow = '#9673A6',
            move = '#D79B00',
            call = '#D6B656',
            outlive = '#B85450',
          },
        })
        vim.api.nvim_create_autocmd("FileType", {
          pattern = {"rust"},
          callback = function() require("rustowl.autosetup") end
        })
      '';
    }];
    extraPackages = [ rustowl ];
  };

  cachix_packages = [ rustowl rustowl-nvim ];

  # Set the rustowl toolchain, which is a nightly toolchain.
  home.file.rustowl_sysroot = {
    source = rustowl.RUSTOWL_SYSROOTS;
    target = ".rustowl/sysroot/${rustowl.RUSTUP_TOOLCHAIN}";
  };
}

smartyank-nvim: smart yank to clipboard

{ config, pkgs, stdenv, lib, ... }:
let
  my-smartyank-nvim = {
    plugin = pkgs.vimPlugins.smartyank-nvim;
    type = "lua";
    config = ''
      require('smartyank').setup {
        highlight = {
          enabled = false, -- not enable highlight yanked text
        },
        validate_yank = function() return vim.v.operator == '"+y' end,
      }
    '';
  };
in {
  programs.neovim = {
    plugins = [
      my-smartyank-nvim
    ];
  };
}
{ pkgs, lib, config, ... }: {
  imports = [
    ./image
    ./picker
    ./scroll.nix
    ./terminal.nix
  ];
  options = {
    my.nvim.snacks.setupArgs = lib.mkOption {
      default = {};
      type = lib.types.attrsOf lib.types.anything;
    };
    my.nvim.snacks.extraLuaConfig = lib.mkOption {
      default = "";
      type = lib.types.lines;
    };
  };
  config.programs.neovim = {
    plugins = [{
      plugin = pkgs.vimPlugins.snacks-nvim;
      type = "lua";
      config = /*lua*/ ''
        require("snacks").setup(${lib.generators.toLua {} config.my.nvim.snacks.setupArgs})
      '' + config.my.nvim.snacks.extraLuaConfig;
    }];
  };
}

Why Snacks image rendering uses Chromium

Some draw.io SVGs use HTML for their labels. Firefox displays those labels correctly, but the usual ImageMagick SVG renderers can display a shortened fallback instead. We use headless Chromium to render the existing SVGs faithfully while keeping Snacks' ImageMagick conversion pipeline.

The original failure

In the Nanhu architecture diagram, Instruction and Uncache should appear on separate lines. Snacks showed Instruction... instead, with different text sizing. The intended RGB color negation was unrelated to the missing text.

Draw.io can export a label in this form:

<switch>
  <foreignObject requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility"
                 width="160" height="100">
    <div xmlns="http://www.w3.org/1999/xhtml">Instruction<br/>Uncache</div>
  </foreignObject>
  <text x="80" y="50">Instruction...</text>
</switch>

A browser renders the HTML inside foreignObject, including its line breaks and formatting. A renderer that does not support that content selects the fallback text element. The ellipsis is literally present in the SVG; changing resolution cannot restore the missing label.

The local reproduction confirmed this with ImageMagick using Inkscape, and with ImageMagick explicitly using librsvg: both displayed Instruction.... Headless Chromium displayed both complete lines. Draw.io documents the same issue in Why text in exported SVG images may not display correctly.

Why this integration

Snacks converts non-PNG images with ImageMagick. Its convert.magick settings configure arguments; they do not select an arbitrary converter executable. ImageMagick already has an external SVG decoder hook, svg:decode, normally used to invoke Inkscape. Replacing that delegate keeps the integration at the existing renderer boundary.

The resulting flow is:

Snacks conversion and cache
  → ImageMagick reads the SVG
    → svg:decode invokes the Chromium helper
    ← Chromium writes a PNG directly to the delegate output
  → ImageMagick applies the configured RGB negation and writes metadata
  → Snacks displays the cached PNG using the Kitty Graphics Protocol

config.nix packages the helper and delegate file with explicit Nix paths to Python, Chromium, and ImageMagick. It adds the delegate directory to MAGICK_CONFIGURE_PATH in the Neovim wrapper. This affects Neovim and its child processes; it does not change the desktop's global ImageMagick configuration. The configuration continues to use the packaged Snacks plugin without a source patch or a browser automation library.

lua.nix retains the existing density and dark-background RGB negation settings. It uses the snacks/image-chromium cache directory so PNGs produced by the old renderer are not reused. The old cache is left intact.

What the helper preserves

svg/main.py asks ImageMagick's explicit RSVG: reader for the canvas dimensions at 96 DPI. This reader measures the SVG without recursively calling our custom delegate. Chromium uses those dimensions and a device scale factor of the requested density divided by 96. The delegate's background color and opacity are passed through to Chromium as well.

The helper resolves ImageMagick's temporary symlink and opens the original .svg file whenever possible. This preserves relative image references without changing the source document. Snacks downloads remote images to .data cache files rather than preserving a .svg extension, so those inputs need a temporary .svg copy. For that case, the helper resolves href, xlink:href, and HTML src attributes against the original file location, including inherited xml:base values. It does not rewrite relative CSS url(...) references or recover the original remote URL from a downloaded cache file.

Each conversion uses a temporary Chromium profile, keeps the browser sandbox enabled, and checks subprocess failures with timeouts. Temporary files and the profile are removed when the helper exits. Chromium writes directly to ImageMagick's requested output path. An additional crop and PNG rewrite was removed after the regression checks and a pixel comparison showed it was unnecessary.

Alternatives and costs

For diagrams we author, draw.io's Text → Advanced → Convert Labels to SVG is the most portable solution. Disabling Formatted Text and Word Wrap, or exporting through PDF, are other documented options. Those approaches require re-exporting source diagrams; the delegate also works with existing diagrams from other repositories.

Installing Inkscape or increasing -density did not fix this HTML-label failure. Using Chromium adds a browser dependency and startup cost on a cache miss; the initial Nanhu conversion took approximately two seconds on the tested machine. Snacks reuses the resulting cached PNG on subsequent conversions. The displayed image is still rasterized, so sharpness depends on the configured density. Ordinary raster and PDF conversion continue through ImageMagick.

Verification

From the repository root, build the delegate and run its integration checks:

svg_delegates=$(nix-build --no-out-link -E '
  let
    pkgs = import <nixpkgs> {};
    module = import ./usr/cli/basic/nvim/snacks/image/config.nix { inherit pkgs; };
  in pkgs.runCommand "snacks-image-delegates" {
    delegatePath = builtins.elemAt module.programs.neovim.extraWrapperArgs 3;
  } "ln -s $delegatePath $out"
')
MAGICK_CONFIGURE_PATH="$svg_delegates" \
  python usr/cli/basic/nvim/snacks/image/svg/test.py

svg/test.py checks multiline HTML labels, RGB negation, DPI, small and viewBox-only canvases, physical units, transparency, background color, relative images, downloaded .data inputs, and ordinary raster conversion. These checks use real Chromium and ImageMagick output. The simplified helper also produced a pixel-identical 6972×7446 negated Nanhu image, and conversion through Snacks itself passed using the built Home Manager Neovim wrapper.

Build and activate the Home Manager configuration normally, then restart Neovim to load the new wrapper and image cache setting.

Upstream references

# image-nvim vs snacks-nvim问题
# * image-nvim: 2026.11.24 更新
#   * 错位,大小太小
#   * (幻灯片里)图片多了非常卡,会显示不出来
#   * 排版有问题,总有错位,issues说解决了,我这里用的最新版,仍然部分有问题
#   * 结论,不如用MarkdownPreview或snacks-nvim/image
{ pkgs, lib, ... }:
let
  # Chromium renders draw.io HTML labels that Inkscape/librsvg replace with fallback text; see README.md.
  svgDecoder = pkgs.writeShellScript "snacks-svg-decode" ''
    exec ${pkgs.python3}/bin/python3 ${./svg/main.py} \
      ${pkgs.chromium}/bin/chromium ${pkgs.imagemagick}/bin/magick "$@"
  '';
  delegates = pkgs.writeTextDir "delegates.xml" ''
    <?xml version="1.0" encoding="UTF-8"?>
    <delegatemap>
      <delegate decode="svg:decode" stealth="True"
        command="${svgDecoder} '%s' '%s' '%s' '%s' '%s'"/>
    </delegatemap>
  '';
in {
  nixpkgs.overlays = [(final: prev: {
    vimPlugins = prev.vimPlugins // {
      snacks-nvim = prev.vimPlugins.snacks-nvim.overrideAttrs (old: {
        patches = (old.patches or [ ]) ++ [
          ./native-pixels.patch
          ./inline-detach.patch
          ./inline-defer-edit.patch
          ./mermaid-pixel-size.patch
        ];
      });
    };
  })];
  my.nvim.snacks.setupArgs = {
    image = lib.generators.mkLuaInline /*lua*/''{
      enabled = true,
      -- Ghostty at reset zoom: CSI 16 t reports 43 px tall × 22 px wide (14 pt, 2× display).
      reset_cell = { width = 22, height = 43 },
      cache = vim.fn.stdpath("cache") .. "/snacks/image-chromium-native",
      convert = {
        mermaid = function()
          local theme = vim.o.background == "light" and "redux-color" or "redux-dark-color"
          return { "-i", "{src}", "-o", "{file}", "-b", "transparent", "-t", theme, "-s", "{scale}" }
        end,
        ---@type table<string,snacks.image.args>
        magick = (function() -- start of a local scope
          original = {
            default = { "{src}[0]" }, -- preserve the raster's pixel dimensions
            vector = { "-density", 192, "{src}[0]" }, -- used by vector images like svg
            -- math = { "-density", 192, "{src}[0]", "-trim" },
            pdf = { "-density", 192, "{src}[0]", "-background", "white", "-alpha", "remove", "-trim" },
          }
          -- if vim background is dark then negate the image color
          for _, opts in pairs(original) do
            if vim.o.background == "dark" then
              table.insert(opts, "-channel")
              table.insert(opts, "RGB")
              table.insert(opts, "-negate")
            end
          end
          return original
        end)(), -- end of a local scope
      },
    }'';
  };
  my.nvim.snacks.extraLuaConfig = /*lua*/ ''
    -- by hermes + claude opus 4.6
    vim.api.nvim_create_user_command("SnacksImageToggle", function(opts)
      local cfg = Snacks.image.config
      cfg.enabled = not cfg.enabled
      if not cfg.enabled then
        Snacks.image.placement.clean()
        -- Remove doc autocmds and invalidate the inline attachment.
        for _, buf in ipairs(vim.api.nvim_list_bufs()) do
          if vim.b[buf].snacks_image_attached then
            pcall(vim.api.nvim_del_augroup_by_name, "snacks.image.inline." .. buf)
            pcall(vim.api.nvim_del_augroup_by_name, "snacks.image.doc." .. buf)
            vim.b[buf].snacks_image_attached = nil
          end
        end
      else
        -- Re-attach doc images for current buffer
        Snacks.image.doc.attach(vim.api.nvim_get_current_buf())
      end
      if not opts.bang then
        vim.notify("snacks.image: " .. (cfg.enabled and "enabled" or "disabled"))
      end
    end, { bang = true })

    vim.api.nvim_create_user_command("SnacksImageRefresh", function()
      if Snacks.image.config.enabled then
        vim.cmd("SnacksImageToggle!")
      end
      vim.cmd("SnacksImageToggle!")
    end, {})

    vim.api.nvim_create_user_command("SnacksImageFitToggle", function()
      local buf = vim.api.nvim_get_current_buf()
      local fit = not vim.b[buf].snacks_image_fit
      vim.b[buf].snacks_image_fit = fit
      Snacks.image.placement.update_inline(buf)
      local pending = vim.bo[buf].modified and " (after :write)" or ""
      vim.notify("snacks.image: " .. (fit and "fit" or "native") .. pending)
    end, { desc = "Toggle fit-to-window for inline images in this buffer" })

    vim.api.nvim_create_autocmd({ "WinResized", "BufWinEnter", "WinClosed", "TabEnter" }, {
      group = vim.api.nvim_create_augroup("snacks_image_fit", { clear = true }),
      callback = vim.schedule_wrap(function()
        local updated = {}
        for _, win in ipairs(vim.api.nvim_tabpage_list_wins(0)) do
          local buf = vim.api.nvim_win_get_buf(win)
          if vim.b[buf].snacks_image_fit and not updated[buf] then
            updated[buf] = true
            Snacks.image.placement.update_inline(buf)
          end
        end
      end),
    })
  '';
  programs.neovim = {
    extraWrapperArgs = [ "--prefix" "MAGICK_CONFIGURE_PATH" ":" "${delegates}" ];
    extraPackages = [
      pkgs.imagemagick
      pkgs.mermaid-cli
      # for drawing math.tex as images
      # TODO: Is math disabled?
      (pkgs.texliveBasic.withPackages (p: [
        p.standalone
        p.varwidth
        p.preview
        p.mathtools
        p.xcolor
      ]))
      pkgs.ghostscript
    ];
  };
}

Telescope Alternatives Comparison

Brief notes from debugging Telescope find_files, live_grep_args, symlink following, and runtime backend args.

Telescope

  • find_files uses external file listing commands (rg --files, fd, or find) and Telescope/fzf-native only sorts/filter results.
  • find_files supports launch-time options such as follow, hidden, no_ignore, no_ignore_parent, and find_command.
  • live_grep_args.nvim supports prompt-time args for grep/content search, but not file search.
  • No mature general Telescope solution was found for prompt-time backend args across both file search and grep.
  • In-picker toggles for follow/hidden/ignored are not native; use separate keymaps or write a custom picker.

Snacks picker

  • Best match for a unified modern picker with runtime behavior.
  • Docs say files and grep support adding backend options in the prompt, e.g. foo -- -e=lua.
  • Has built-in interactive toggles:
    • <C-f>: follow symlinks
    • <C-h>: hidden files
    • <C-i>: ignored files
    • <C-r>: regex
    • <C-l>: live mode
  • Strong candidate if interactive file/grep args and toggles matter more than staying on Telescope.

fzf-lua

  • Strong Telescope replacement if real fzf behavior is desired.
  • Has file and grep pickers with configurable fd/rg options.
  • File picker supports interactive toggles such as:
    • alt-f: follow
    • alt-h: hidden
    • alt-i: ignore
  • Less directly a unified prompt-args abstraction than Snacks, but very capable.

Recommendation

  • Stay on Telescope for minimal disruption; add launch-time keymap variants for common modes.
  • Try Snacks picker first if the goal is unified file/grep runtime args plus in-picker toggles.
  • Try fzf-lua if the goal is a fast fzf-centered Telescope replacement.
{ ... }: {
  nixpkgs.overlays = [(final: prev: {
    vimPlugins = prev.vimPlugins // {
      snacks-nvim = prev.vimPlugins.snacks-nvim.overrideAttrs (old: {
        patches = (old.patches or []) ++ [ ./main.patch ];
      });
    };
  })];
}
{ lib, ... }: let
  inherit (lib.generators) mkLuaInline;
in {
  imports = [
    ./commit-message
    ./git
    ./insert_file_path.nix
  ];
  nixpkgs.overlays = [(final: prev: {
    vimPlugins = prev.vimPlugins // {
      snacks-nvim = prev.vimPlugins.snacks-nvim.overrideAttrs (old: {
        patches = (old.patches or [ ]) ++ [
          # Upstream fix: https://github.com/folke/snacks.nvim/pull/2999
          ./tags-nomagic.patch
        ];
      });
    };
  })];
  my.nvim.snacks.setupArgs = {
    picker = {
      # Always open results in the invoking window. The default main.file = true
      # skips help and other non-file buffers, unexpectedly using another window.
      main.current = true;
      previewers.diff.style = "syntax";
      actions = {
        # Snacks ships toggle_input and toggle_preview but no toggle_list, though
        # Picker:toggle accepts "input"|"list"|"preview".
        toggle_list = mkLuaInline /*lua*/''function(picker)
          if picker.resolved_layout.preset == "my_vertical" then
            local layout = picker.layout
            -- Release the preview's fixed share while the list is hidden.
            layout.opts.layout[1].height = layout:is_hidden("list") and picker.resolved_layout.layout[1].height or nil
          end
          return picker:toggle("list")
        end'';
      } // (let
        gen_preview_scroll_line = down: mkLuaInline /*lua*/ ''function(picker)
          local win = picker.preview.win
          if win:valid() then
            vim.api.nvim_win_call(win.win, function()
              vim.cmd("normal! " .. vim.keycode("${if down then "<C-e>" else "<C-y>"}"))
            end)
          end
        end'';
      in {
        # Snacks' preview_scroll_up/down step by the preview's 'scroll' option (half a page).
        # These move a single line, so the Shift+Up/Down keys stay fine-grained and
        # <c-f>/<c-b> keep their half-page step.
        preview_scroll_line_up = gen_preview_scroll_line false;
        preview_scroll_line_down = gen_preview_scroll_line true;
      }) // (let
        # Both my_vertical and select declare their panes in top-to-bottom order.
        gen_focus_vertical = dir: mkLuaInline /*lua*/ ''function(picker)
          local layout = picker.resolved_layout.layout
          local current = picker:current_win()
          for i, child in ipairs(layout) do
            if child.win == current then
              for j = i + ${dir}, ${if dir == "1" then "#layout" else "1"}, ${dir} do
                local name = layout[j].win
                local win = picker.layout.wins[name]
                if win and win:valid() and not picker.layout:is_hidden(name) then
                  return win:focus()
                end
              end
              return
            end
          end
        end'';
      in {
        focus_up = gen_focus_vertical "-1";
        focus_down = gen_focus_vertical "1";
      });
      win = {
        input = {
          keys = {
            # Scroll the preview without leaving the prompt.
            "<S-Up>" = mkLuaInline ''{ "preview_scroll_line_up", mode = { "n", "i" } }'';
            "<S-Down>" = mkLuaInline ''{ "preview_scroll_line_down", mode = { "n", "i" } }'';
            "<a-up>" = mkLuaInline ''{ "focus_up", mode = { "n", "i" } }'';
            "<a-down>" = mkLuaInline ''{ "focus_down", mode = { "n", "i" } }'';
            "<a-l>" = mkLuaInline ''{ "toggle_list", mode = { "n", "i" } }'';
          };
        };
        list = {
          keys = {
            "<S-Up>" = "list_scroll_up";
            "<S-Down>" = "list_scroll_down";
            "<a-up>" = "focus_up";
            "<a-down>" = "focus_down";
            "<a-l>" = "toggle_list";
          };
          wo = {
            # Global list window config: show ">" on cursor line as current-item indicator
            # for all picker layouts, not only the custom my_vertical preset.
            statuscolumn = "%#SnacksPickerListCursorLine#%{v:relnum==0?\">\":\" \"}%*";
          };
        };
        # The preview is a normal buffer, so these keys are normal mode only.
        preview = {
          keys = {
            "<a-up>" = "focus_up";
            "<a-down>" = "focus_down";
            "<a-l>" = "toggle_list";
          };
        };
      };
      config = mkLuaInline /*lua*/''function(opts)
        -- The source declares which input keys to advertise; the merged config says what they do.
        local keys = opts.source and vim.tbl_get(opts.sources, opts.source, "win", "input", "keys") or {}
        local hints = {}
        for lhs, declared in pairs(keys) do
          local spec = opts.win.input.keys[lhs]
          if declared and spec and lhs ~= "?" then
            local label = type(spec) == "table" and (spec.desc or spec[2] or spec[1]) or spec
            if type(label) == "table" then
              label = table.concat(vim.tbl_filter(function(v) return type(v) == "string" end, label), ", ")
            end
            hints[#hints + 1] = type(label) == "string" and label ~= "" and (lhs .. " " .. label) or lhs
          end
        end
        table.sort(hints)
        hints[#hints + 1] = "? All keys"
        opts.layouts.my_vertical.layout.footer = { { table.concat(hints, "  "), "NonText" } }
      end'';
      layouts = {
        # custom presets
        my_vertical = {
          layout = mkLuaInline /*lua*/''{
            backdrop = false,
            box = "vertical",
            border = true,
            title = "{title} {live} {flags}",
            title_pos = "center",
            -- Top to bottom: preview, input, list. Without `reverse`, list items run
            -- downwards, so list_down matches the screen now that the list sits at the bottom.
            { win = "preview", title = "{preview}", border = "bottom", height = 0.7 },
            { win = "input", height = 1 },
            { win = "list", border = "top" },
          }'';
          fullscreen = true;
        };
      };
      # Global Config
      # Keep the global layout behind a named preset instead of defining the
      # full layout table here. Per-source layouts (e.g. ui.select) are
      # deep-merged with the global layout; if the global value contains layout
      # children directly, source presets inherit those children and may not
      # resolve cleanly. A preset reference lets sources override with their own
      # preset, such as the built-in "select" layout.
      layout = { preset = "my_vertical"; cycle = false; };
      # Per-source Config
      sources = {
        # Snacks' LSP sources opt in to jump.reuse_win = true, which moves focus to
        # a window that already shows the target file instead of replacing the
        # current buffer. Keep jumps in the current window.
        lsp_definitions.jump.reuse_win = false;
        lsp_declarations.jump.reuse_win = false;
        lsp_type_definitions.jump.reuse_win = false;
        lsp_implementations.jump.reuse_win = false;
        lsp_references.jump.reuse_win = false;
      };
    };
  };
  my.nvim.snacks.extraLuaConfig = /*lua*/ ''
    do
      function get_buffer_dir()
        local file = vim.api.nvim_buf_get_name(0)
        return file ~= "" and vim.fs.dirname(file) or nil
      end

      -- f
      vim.keymap.set('n', "<space>f", function() Snacks.picker.files({ cwd = get_buffer_dir() }) end)
      vim.keymap.set('n', "<space>F", function() Snacks.picker.files() end)
      vim.keymap.set('n', "<space>b", function() Snacks.picker.buffers() end)
      -- s
      vim.keymap.set('n', "<space>g", function() Snacks.picker.grep({ cwd = get_buffer_dir() }) end)
      vim.keymap.set('n', "<space>G", function() Snacks.picker.grep() end)
      vim.keymap.set('n', "<space>h", function() Snacks.picker.help() end)

      vim.keymap.set('n', '<space>c', function() Snacks.picker.command_history() end)
      vim.keymap.set('n', '<space>C', function() Snacks.picker.commands() end)

      vim.keymap.set('n', '<space>s', function() Snacks.picker.git_status() end)
      vim.keymap.set('n', '<space>l', function() Snacks.picker.git_log() end)
      vim.keymap.set('n', '<space>p', function() Snacks.picker.pickers() end)
    end
  '';
}
{ lib, ... }: {
  imports = [
    ./log
    ./restore.nix
    ./status.nix
  ];
  my.nvim.snacks.setupArgs.picker = {
    actions = let
      fugitive = command: lib.generators.mkLuaInline /*lua*/ ''
        function(picker, item)
          local dir = vim.fn.FugitiveExtractGitDir(item and item.cwd or picker:cwd())
          if dir == "" then return Snacks.notify.warn("Not in a Git repository") end
          picker:close()
          -- :Git rejects -C; pass the picker's Git dir to its command handler instead.
          vim.cmd(vim.fn["fugitive#Command"](-1, -1, 0, 0, "", "${command}", dir))
        end
      '';
    in {
      git_commit = fugitive "commit";
      git_push = fugitive "push";
      git_pull_ff = fugitive "pull --ff-only";
    };
  };
}
{ config, lib, ... }: {
  nixpkgs.overlays = [(final: prev: {
    vimPlugins = prev.vimPlugins // {
      snacks-nvim = prev.vimPlugins.snacks-nvim.overrideAttrs (old: {
        patches = (old.patches or []) ++ [ ./main.patch ];
      });
    };
  })];

  my.nvim.snacks.setupArgs = {
    picker = {
      sources = {
        git_log = {
          # Normal mode as the default mode
          on_show = lib.generators.mkLuaInline ''function() vim.cmd.stopinsert() end'';
          win.input.keys = {
            P = lib.generators.mkLuaInline ''{ "git_push", desc = "Push" }'';
            p = lib.generators.mkLuaInline ''{ "git_pull_ff", desc = "Pull (ff-only)" }'';
          };
        };
      };
    };
  };

  my.nvim.snacks.extraLuaConfig = /*lua*/ ''
    do
      local author_width = 6
      local coauthor_width = 4
      local palette = { "String", "Function", "Identifier", "Type", "Statement", "Special" }

      local function author_colors()
        local normal = vim.api.nvim_get_hl(0, { name = "Normal", link = false })
        for i, name in ipairs(palette) do
          local hl = vim.api.nvim_get_hl(0, { name = name, link = false })
          vim.api.nvim_set_hl(0, "SnacksGitLogAuthor" .. i, {
            fg = hl.fg or normal.fg,
            ctermfg = hl.ctermfg or normal.ctermfg,
          })
        end
      end
      author_colors()
      vim.api.nvim_create_autocmd("ColorScheme", {
        group = vim.api.nvim_create_augroup("SnacksGitLogAuthors", { clear = true }),
        callback = author_colors,
      })

      local function author_hl(name)
        -- Hash the full text, so truncation and column placement never change its colour.
        local hash = tonumber(vim.fn.sha256(name):sub(1, 8), 16)
        return "SnacksGitLogAuthor" .. (hash % #palette + 1)
      end

      -- Snacks' truncating align counts characters, which can overflow with wide names.
      local function column(text, width)
        if vim.fn.strdisplaywidth(text) > width then
          text = vim.fn.printf("%.*S", width - 1, text) .. "…"
        end
        return vim.fn.printf("%-*S", width, text)
      end

      local function format(item, picker)
        local date = item.date
        if date:sub(1, 10) == os.date("%Y.%m.%d") then
          date = string.rep(" ", 11) .. date:sub(12)
        end
        local coauthors = table.concat(item.coauthors or {}, ", ")
        local ret = {
          { item.commit:sub(1, 8), item.pushed == true and "DiagnosticWarn"
            or item.pushed == false and "DiagnosticError" or "SnacksPickerGitCommit"
          },
          { " " },
          { Snacks.picker.util.align(date, 16), "SnacksPickerGitDate" },
          { " " },
          { column(item.author, author_width), author_hl(item.author) },
          { " " },
          { column(coauthors, coauthor_width), author_hl(coauthors) },
          { " " },
          { item.graph, author_hl(item.author) },
          { item.refs, "GreenSign" },
          { " " },
        }
        Snacks.picker.highlight.extend(ret, require("snacks.picker.format").commit_message(item, picker))
        return ret
      end

      for _, source in ipairs({ "git_log", "git_log_file", "git_log_line" }) do
        local opts = Snacks.config.picker.sources[source] or {}
        opts.cmd = "${config.programs.git.package}/bin/git"
        opts.format = format
        Snacks.config.picker.sources[source] = opts
      end
    end
  '';
}
{ lib, ... }: {
  my.nvim.snacks.setupArgs = {
    picker = {
      actions = {
        # Upstream git_restore only runs `git restore <file>`, which resets just the
        # worktree: staged changes survive in the index and untracked entries are never
        # restored, so <c-r> silently does nothing for them. Discard both sides from HEAD
        # instead, and delete untracked entries. Hunk items from git_diff keep upstream.
        git_restore = lib.generators.mkLuaInline /*lua*/ ''function(picker)
          local upstream = require("snacks.picker.actions").git_restore
          local items = picker:selected({ fallback = true })
          local first = items[1]
          if not first or not first.status then
            return upstream(picker)
          end
          local msg = ("Discard changes to %d files?"):format(#items)
          if #items == 1 then
            local what = first.status == "??" and "Delete untracked file `%s`?" or "Discard changes to `%s`?"
            msg = what:format(Snacks.picker.util.path(first))
          end
          Snacks.picker.util.confirm(msg, function()
            -- A repo without commits has no HEAD to restore from, and there every index
            -- entry is a fresh add, so discarding it means removing the file.
            local has_head = vim.system({ "git", "rev-parse", "--verify", "--quiet", "HEAD" }, { cwd = first.cwd }):wait().code == 0
            local function run(i)
              local item = items[i]
              if not item then
                vim.schedule(function()
                  picker:refresh()
                  vim.cmd.startinsert()
                  vim.cmd.checktime()
                end)
                return
              end
              -- A rename is shown by its target, so its source path has to be restored too.
              local paths = item.rename and { item.file, item.rename } or { item.file }
              local cmd
              if item.status:sub(1, 2) == "??" then
                cmd = { "git", "--literal-pathspecs", "clean", "-fd", "--" }
              elseif not has_head then
                cmd = { "git", "--literal-pathspecs", "rm", "-f", "--" }
              else
                cmd = { "git", "--literal-pathspecs", "restore", "--source=HEAD", "--staged", "--worktree", "--" }
              end
              vim.list_extend(cmd, paths)
              -- Sequential: parallel `git` calls in one repo fight over index.lock.
              vim.system(cmd, { cwd = item.cwd, text = true }, function(res)
                if res.code ~= 0 then
                  Snacks.notify.error(vim.trim(res.stderr or ""), { title = "Git" })
                end
                run(i + 1)
              end)
            end
            run(1)
          end)
        end'';
      };
    };
  };
}
{ lib, ... }: {
  my.nvim.snacks.setupArgs = {
    picker = {
      sources = {
        git_status = {
          # Normal mode as the default mode
          on_show = lib.generators.mkLuaInline ''function() vim.cmd.stopinsert() end'';
          matcher.sort_empty = true;
          sort.fields = [ "file" "idx" ];
          win.input.keys = {
            C = lib.generators.mkLuaInline ''{ "git_commit", desc = "Commit" }'';
          };
        };
      };
    };
  };
}
{ ... }: {
  my.nvim.snacks.extraLuaConfig = /*lua*/ ''
    do
      -- By pi + gpt-5.5
      -- Fuzzy recursive file insertion via Snacks picker.
      -- Alternatives not chosen:
      -- - builtin <C-x><C-f>: only completes files in the current path level.
      -- - blink.cmp path source: also current-level path completion, not recursive fuzzy pick.
      -- - fzf-lua complete_path: works, but duplicates Snacks picker functionality.
      -- - plain Snacks put action: pastes a file but does not use/replace typed prefixes.
      local function insert_file_path(base_dir)
        -- Hide blink.cmp so its path menu does not overlap the Snacks picker.
        pcall(function() require("blink.cmp").hide() end)

        local win = vim.api.nvim_get_current_win()
        local buf = vim.api.nvim_get_current_buf()
        local row, col = unpack(vim.api.nvim_win_get_cursor(win))
        local line = vim.api.nvim_get_current_line()

        -- Path-like token before the cursor, e.g. `./foo/ba`.
        local prefix = line:sub(1, col):match("[^%s'\"`{}%[%]()<>,;:]*$") or ""
        -- Directory part is preserved in inserted text; cwd resolves from the chosen base_dir.
        local dir_prefix = prefix:match("^(.*/)") or ""
        local is_absolute = dir_prefix:match("^[~/]") ~= nil
        local picker_cwd = dir_prefix ~= "" and (is_absolute and vim.fn.resolve(dir_prefix) or vim.fn.resolve(base_dir .. "/" .. dir_prefix)) or base_dir

        Snacks.picker.files({
          cwd = picker_cwd,
          confirm = function(picker, item)
            picker:close()
            if not item then
              return
            end

            -- Replace the typed prefix with the selected file path.
            local file = dir_prefix .. (item.file or item.text)
            if prefix ~= "" then
              vim.api.nvim_buf_set_text(buf, row - 1, col - #prefix, row - 1, col, {})
            end
            vim.api.nvim_win_set_cursor(win, { row, col - #prefix })
            vim.api.nvim_paste(file, true, -1)
            vim.schedule(function()
              vim.cmd.startinsert({ bang = true })
            end)
          end,
        })
      end

      vim.keymap.set("i", "<C-x><C-f>", function()
        insert_file_path(vim.fn.expand(("#%d:p:h"):format(vim.api.nvim_get_current_buf())))
      end, { desc = "Insert file path from buffer dir" })
      vim.keymap.set("i", "<C-x><C-w>", function()
        insert_file_path(vim.fn.getcwd())
      end, { desc = "Insert file path from cwd" })
    end
  '';
}
# Comparisons:
# - neoscroll.nvim: only support few scroll motion, does not support gg, G, S-up, S-down,
#                   see: https://github.com/karb94/neoscroll.nvim/issues/23
{ lib, ... }: {
  my.nvim.snacks.setupArgs = {
    scroll = lib.generators.mkLuaInline /*lua*/''{
      enabled = true,
      filter = function(buf)
        -- default filter does not allow in terminal, remove this limit!
        -- return vim.g.snacks_scroll ~= false and vim.b[buf].snacks_scroll ~= false and vim.bo[buf].buftype ~= "terminal"
        return vim.g.snacks_scroll ~= false and vim.b[buf].snacks_scroll ~= false
      end,
    }'';
  };
}
{ ... }: {
  my.nvim.snacks.setupArgs = {
    styles = {
      terminal = {
        # Ordinary terminal windows match ordinary buffers.
        wo.winhighlight = "Normal:Normal,NormalNC:Normal";
      };
      terminal_current = {
        position = "current";
        wo.winbar = "";
      };
      terminal_float = {
        position = "float";
        width = 0; # full
        height = 0; # full
        border = "rounded";
        # Match Sonokai's native Snacks picker appearance.
        wo.winhighlight = "Normal:SnacksPicker,NormalNC:SnacksPicker,FloatBorder:SnacksPickerBorder,FloatTitle:SnacksPickerTitle,FloatFooter:SnacksPickerFooter";
      };
    };
  };
  my.nvim.snacks.extraLuaConfig = /*lua*/ ''
    local function current_file_dir()
      if vim.bo.buftype == "terminal" then
        return nil
      end
      local file = vim.api.nvim_buf_get_name(0)
      return file ~= "" and vim.fs.dirname(file) or nil
    end

    -- Snacks keys terminal instances by cwd and count, not by window style.
    vim.keymap.set("n", "<leader>t", function()
      local cwd = current_file_dir() or vim.fn.getcwd()
      vim.cmd("horizontal new")
      Snacks.terminal.open(nil, { count = 1, cwd = cwd, win = { style = "terminal_current" } })
    end, { desc = "Terminal above current window (buffer directory)" })

    vim.keymap.set("n", "<leader>T", function()
      local cwd = vim.fn.getcwd()
      vim.cmd("horizontal new")
      Snacks.terminal.open(nil, { count = 1, cwd = cwd, win = { style = "terminal_current" } })
    end, { desc = "Terminal above current window (cwd)" })

    vim.keymap.set("n", "<leader>f", function()
      Snacks.terminal(nil, { count = 2, cwd = current_file_dir(), win = { style = "terminal_float" } })
    end, { desc = "Floating terminal (buffer directory)" })

    vim.keymap.set("n", "<leader>F", function()
      Snacks.terminal(nil, { count = 2, cwd = vim.fn.getcwd(), win = { style = "terminal_float" } })
    end, { desc = "Floating terminal (cwd)" })
  '';
}
{ pkgs, ... }: {
  programs.neovim = {
    plugins = [{
      plugin = pkgs.vimPlugins.todo-comments-nvim;
      type = "lua";
      config = /*lua*/''
        require("todo-comments").setup({
          keywords = {
            EUREKA = { icon = "🤓", },
            TODO = { icon = "☐ ", color = "info" },
            DONE = { icon = " " },
          },
          highlight = {
            multiline = false,
            before = "",
            after = "",
            -- Use non-greedy .{-} so the first keyword wins when a line contains multiple keywords.
            pattern = [=[.{-}<(KEYWORDS)\s*[::]]=],
            comments_only = false,
          },
        })

        vim.keymap.set("n", "]t", function() require("todo-comments").jump_next() end, { desc = "Next todo comment" })
        vim.keymap.set("n", "[t", function() require("todo-comments").jump_prev() end, { desc = "Previous todo comment" })
        vim.keymap.set("n", "<space>t", function () Snacks.picker.todo_comments({ keywords = { "TODO" } }) end, { desc = "only TODO keyword" })
        vim.keymap.set("n", "<space>T", function () Snacks.picker.todo_comments() end, { desc = "all todo-comments supported keywords" })
      '';
    }];
  };
}
{ pkgs, ... }: let
  # /*lang*//* content... */
  gen_c_style_query = node: set-lang: /*query*/''
    ; extends
    (
      (${node}) @injection.language
      (#lua-match? @injection.language "/%*[%w%p]+%*/")
      .
      (${node}) @injection.content
      (#lua-match? @injection.content "/%*.*%*/")
      (#offset! @injection.content 0 2 0 -2)
      (#gsub! @injection.language "/%*([%w%p]+)%*/" "${if set-lang then "%1" else ""}")
      (#set! injection.combined)
    )
  '';
  gen_c_style_toggle_fn = lang: node: /*lua*/ ''function()
    if _G.${lang}_doccom_injection_enabled then
      vim.treesitter.query.set("${lang}", "injections", [[${gen_c_style_query node false}]])
      _G.${lang}_doccom_injection_enabled = false
    else
      vim.treesitter.query.set("${lang}", "injections", [[${gen_c_style_query node true}]])
      _G.${lang}_doccom_injection_enabled = true
    end
    -- refresh current buffer
    vim.cmd("e")
  end'';
in {
  programs.neovim = {
    initLua = /*lua*/ ''
      vim.api.nvim_create_user_command('DoccomInjectionToggle', function()
        local fns = {
          rust = ${gen_c_style_toggle_fn "rust" "block_comment"},
          typst = ${gen_c_style_toggle_fn "typst" "comment"},
        }
        local fn = fns[vim.bo.filetype]
        if fn ~= nil then fns[vim.bo.filetype]() end
      end, {})
    '';
  };
}
# DrawIt vs venn-nvim
# * DrawIt is slow when moving cursor adding spaces
{ pkgs, ... }: {
  programs.neovim = {
    plugins = [(
      pkgs.vimPlugins.venn-nvim.overrideAttrs (old: {
        # ▲ ▼ ◀ ▶
        postPatch = ''
          sed -i 's/►/▶/' lua/venn/init.lua
          sed -i 's/◄/◀/' lua/venn/init.lua
          sed -i 's/►/▶/' src/primitives/box.lua.t
          sed -i 's/◄/◀/' src/primitives/box.lua.t
        '';
      })
    )];
  };
}

vim-easy-align: A simple, easy-to-use Vim alignment plugin.

{ config, pkgs, stdenv, lib, ... }:
let
  my-vim-easy-align = {
    plugin = pkgs.vimPlugins.vim-easy-align;
    type = "viml";
    config = ''
      " Start interactive EasyAlign in visual mode (e.g. vipga)
      xmap ga <Plug>(EasyAlign)

      " Start interactive EasyAlign for a motion/text object (e.g. gaip)
      nmap ga <Plug>(EasyAlign)

      let g:easy_align_delimiters = {
      \ '>': { 'pattern': '>>\|=>\|>' },
      \ '/': {
      \     'pattern':         '//\+\|/\*\|\*/',
      \     'delimiter_align': 'l',
      \     'ignore_groups':   ['!Comment'] },
      \ ']': {
      \     'pattern':       '[\]]',
      \     'left_margin':   0,
      \     'right_margin':  0,
      \     'stick_to_left': 0
      \   },
      \ '[': {
      \     'pattern':       '[\[]',
      \     'left_margin':   0,
      \     'right_margin':  0,
      \     'stick_to_left': 0
      \   },
      \ ')': {
      \     'pattern':       '[)]',
      \     'left_margin':   0,
      \     'right_margin':  0,
      \     'stick_to_left': 0
      \   },
      \ '(': {
      \     'pattern':       '[(]',
      \     'left_margin':   0,
      \     'right_margin':  0,
      \     'stick_to_left': 0
      \   },
      \ }

      let g:easy_align_ignore_groups = [] " default: ['Comment', 'String']
    '';
  };
in {
  programs.neovim = {
    plugins = [
      my-vim-easy-align
    ];
  };
}

vim-mark: multi-color highlight

{ mark-src, ingo-src }: # local args
{ config, pkgs, stdenv, lib, ... }:
let
  vim-ingo-library = pkgs.vimUtils.buildVimPlugin {
    name = "vim-ingo-library";
    src = ingo-src;
  };
  my-vim-mark = {
    plugin = pkgs.vimUtils.buildVimPlugin {
      name = "vim-mark";
      # TODO: Place vim-mark's [current/total] at the exact same screen position as Neovim's native search counter.
      # Once UI2 is stable, consider using its search_cmd and search_count messages for native placement.
      patches = [ ./inline-search-count.patch ];
      src = mark-src;
    };
    type = "viml";
    config = ''
      " clear highlight created by vim-mark
      nnoremap <leader><F3> :MarkClear<CR>
      " show all marks
      nnoremap <leader>M :Marks<CR>
    '';
  };
in {
  programs.neovim = {
    plugins = [
      my-vim-mark
      vim-ingo-library
    ];
  };
}
{ pkgs, ... }: {
  programs.neovim = {
    plugins = [{
      plugin = pkgs.vimPlugins.vim-matchup;
      type = "lua";
      config = /*lua*/ ''
        -- use nvim-treesitter-context to show match lines
        vim.g.matchup_matchparen_offscreen = {}
        -- 不要加粗光标下的可匹配文字,不然写代码时常遇到的不协调感觉
        -- 比如写{}时{是普通字体}是加粗字体,光标左移一下,{变成加粗}是普通字体。
        vim.cmd("highlight MatchParenCur cterm=NONE gui=NONE")
      '';
    }];
  };
}

winshift-nvim: rearrange windows

{ config, pkgs, stdenv, lib, ... }:
let
  my-winshift-nvim = {
    plugin = pkgs.vimPlugins.winshift-nvim;
    type = "lua";
    config = ''
      -- Lua
      require("winshift").setup({
        highlight_moving_win = true,  -- Highlight the window being moved
        focused_hl_group = "Visual",  -- The highlight group used for the moving window
        -- moving_win_options = {
        --   -- These are local options applied to the moving window while it's
        --   -- being moved. They are unset when you leave Win-Move mode.
        --   wrap = true,
        --   cursorline = false,
        --   cursorcolumn = false,
        --   colorcolumn = "",
        -- },
        keymaps = {
          disable_defaults = false, -- Disable the default keymaps
          win_move_mode = {
            ["h"] = "left",
            ["j"] = "down",
            ["k"] = "up",
            ["l"] = "right",
            ["H"] = "far_left",
            ["J"] = "far_down",
            ["K"] = "far_up",
            ["L"] = "far_right",
            ["<left>"] = "left",
            ["<down>"] = "down",
            ["<up>"] = "up",
            ["<right>"] = "right",
            ["<S-left>"] = "far_left",
            ["<S-down>"] = "far_down",
            ["<S-up>"] = "far_up",
            ["<S-right>"] = "far_right",
          },
        },
        ---A function that should prompt the user to select a window.
        ---
        ---The window picker is used to select a window while swapping windows with
        ---`:WinShift swap`.
        ---@return integer? winid # Either the selected window ID, or `nil` to
        ---   indicate that the user cancelled / gave an invalid selection.
        window_picker = function()
          return require("winshift.lib").pick_window({
            -- A string of chars used as identifiers by the window picker.
            picker_chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890",
            filter_rules = {
              -- This table allows you to indicate to the window picker that a window
              -- should be ignored if its buffer matches any of the following criteria.
              cur_win = true, -- Filter out the current window
              floats = true,  -- Filter out floating windows
              filetype = {},  -- List of ignored file types
              buftype = {},   -- List of ignored buftypes
              bufname = {},   -- List of vim regex patterns matching ignored buffer names
            },
            ---A function used to filter the list of selectable windows.
            ---@param winids integer[] # The list of selectable window IDs.
            ---@return integer[] filtered # The filtered list of window IDs.
            filter_func = nil,
          })
        end,
      })

      vim.keymap.set('n', '<C-W>m', '<Cmd>WinShift<CR>')
    '';
  };
in {
  programs.neovim = {
    plugins = [
      my-winshift-nvim
    ];
  };
}

Agents Comparisons

Opencode

  • Pros:
    • Javascript based. The nix closure is not so large: 186MB!
  • Cons:
    • Javascript based. The memory consumption of open a new opencode instance: ~500MB
    • Use Esc instead of Ctrl-C to interrupt.
  • Summary: Its quality is not comparable to neovim, though it declares "OpenCode is built by neovim users ...".

Crush

  • Pros:
    • Go lang based.
      • Small nix-closure.
      • Small memory consumption: crush instance that have several conversations: ~70MB
  • Cons:
    • It's Ok for me now Token inefficiency: 300 line system prompt and cannot fully customize, only supports system prompt prefix.
    • The input line support Home, End key, but does not support Ctrl+Left/Right.
    • It's Ok for me now Does not support terminal scrollback.
    • It's Ok for me now Notification cannot click and jump to the corresponding terminal.
    • I need auto generating skill, so this is unnecessary now Does not support explicit skill: https://github.com/charmbracelet/crush/discussions/2505 and no discussions!
    • Generate .crush/ in every folder where crush launched

Aider

  • Pros:
    • Support script
    • Token efficiency
      • Test Prompt: Introduce yourself
        • Aider: 2.3k
        • Crush: 15K
    • Native input line support: scrollback, Ctrl-Left/Right, ...
  • Cons:
    • Python based, large codebase: nix closure > 2GB
    • Does not support skill, memory.
    • Models are out of date, e.g.: minimax 2.5, while latest is 2.7

Codex

  • Cons:
    • Latest versions only support wire_api = "responses", does not support completion. So does not support deepseek, minimax, .... Fine!
    • 603k source lines of rust, a pile of xxxx.

Cannot switch arbitrary custom model IDs in the TUI

  • /model only lists visible catalog presets; there is no /model <model_id> or "Custom model..." entry.
  • Runtime already accepts arbitrary model strings via AppEvent::UpdateModel(String) -> thread/settings/update -> Op::ThreadSettings.
  • Limitation: this only changes the model string, not model_provider; cross-provider switching is a larger issue.
  • Workarounds: launch with codex -m <model_name>, codex -p <profile>, config model / model_provider, or startup-only model_catalog_json.
  • Minimal fix: support /model <model_id> by letting SlashCommand::Model accept inline args and dispatching UpdateModel(model) plus PersistModelSelection { model, effort: None }.
  • Upstream: openai/codex#5841, #22160, #24659, #24612.

Code (Codex Fork)

  • Pros:
    • Support wire_api = "chat"
  • Cons:
    • A fork that always needs to rebase.

Forgecode

  • Pros:
    • Moved to AAIF at Linux Foundation: more stable, more reliable
  • Cons:
    • Claims being #1. Really?
    • Fixed: The global local is /forge/, really!? I doubt the project's taste of tech.
    • Does not support prompt injection, e.g. hook scripts.
      • The pull request is stale
        • https://github.com/tailcallhq/forgecode/issues/2562
        • https://github.com/tailcallhq/forgecode/pull/2757
    • Does not support ACP, and the pull request is stale.

Goose

  • Cons:
    • Fixed: Why goose does not saved in nix binary cache, and 1.23.2 cannot build in x86-64 Linux: checkPhase failed!? Why the compiling time so long 7min+?
    • Fixed: Why the output color render bug remain unsolved? VERY IMPORTANT: Oh, I guess this project focus on desktop, instead of cli.
    • zsh cursor sometimes disappear?
    • goose configure cannot configure kimi, minimax successfully, only by manually add a custom_xxx.json
    • minimax is still 2.5
      • https://github.com/aaif-goose/goose/pull/7981
    • cannot switch model during conversation
      • https://github.com/aaif-goose/goose/pull/8747
    • the context length is wrong
      • goose/2026-05-13-custom-provider-context-limit-bug.md

Hermes

  • Cons:
    • Declare able to self-improvement (auto skill generating), but does not support per-project skill yet!? https://github.com/NousResearch/hermes-agent/issues/4667 In my humble opinion, a auto-generating-skill skill is enough!
    • Why CLI+TUI? Why not unify them? split experience, split community?
      • TUI
        • scroll glitch
        • does not filter configured providers/models when selecting them, however CLI does.
      • CLI
        • resize => re-render
        • resume does not support selection UI, but TUI does.
    • Too many bugs that influence my experience, see my patches.

VTCode

  • Pros:
    • Author response very quickly.
  • Cons:
    • Single person maintained
    • ctrl-g does not run async
    • config files in a mess: ~/.config/vtcode/config.toml, ~/.config/vtcode/vtcode.toml, ~/.vtcode/

pi

  • Pros:
    • minimalist
  • Cons:
    • minimalist: lack of many features
      • lack of high-quality plugins such as memory, plan, subagents.
    • typescript-based

pi_agent_rust

  • Cons:
    • Single developer, thus less reliable.

nvim

Avante.nvim

  • Pros:
    • Leverages Neovim muscle memory
  • Cons:
    • No skills support Supported by ACP agents.
    • Uses plenary.nvim (curl without keepalive or auto-retry)
      • Frequent network issues cause interruptions that disrupt workflow
    • Second class ACP support: does not support ACP model switch.
      • Latest version add AvanteACPModels. Why not reusing AvanteModels? The implementation is not CLEAN!
    • The build is complicated (nixpkgs vim plugins non-generated), which has not updated for 3 months.

Codecompanion.nvim

  • Pros:
    • Leverages Neovim muscle memory
    • Minimal/Clean UI
    • Support more ACP capabilities than Agentic.nvim: fs.readTextFile, fs.writeTextFile And it explicitly state support of ACP capabilities in doc!
    • build is simple
  • Cons:
    • No skills support Supported by ACP agents.
    • Use plenary.nvim, the same to Avante.nvim.: Use ACP agent!
    • Codecompanion-history does not support ACP session restore.: If ACP client supports, we can use /resume!
    • tool calls display are trunct to 60 chars, and no way to configure it.
    • Removed because native Pi is the primary interface and CodeCompanion + pi-acp provides only a reduced Pi experience. This is not an intrinsic ACP limitation: ACP v1 supports custom _meta data, custom _-prefixed methods, and capability negotiation, while v2 adds structured elicitation. However, arbitrary Pi extension functionality is not automatic; it requires Pi-specific protocol extensions and corresponding client UI work.
    • The actual chain loses functionality at three layers:
      • pi-acp launches Pi in RPC mode, which cannot reproduce ctx.ui.custom(), component widgets, raw terminal input, custom editor components, or terminal shortcuts.
      • pi-acp v0.0.34 filters extension commands from ACP discovery, maps only select/confirm/notify partially, cancels input/editor requests, and does not generally bridge widgets, status lines, or titles.
      • CodeCompanion's ACP v1 client dispatches standard methods but has no generic Pi-extension UI bridge; it also lacks agent-plan and terminal support.
    • Background hooks and ordinary model tools still run inside Pi, but extension commands, custom views, rendering, questionnaires, and shortcuts are absent or degraded.

Agentic.nvim

  • Pros:
    • simple and only cares about ACP
  • Cons:
    • does not support any ACP capabilities, including fs.readTextFile, fs.writeTextFile, terminal. And it does not mentioned not support above ACP capabilities in doc.
    • Bugs:
      • when enter slash command like /skill, there is high, narrow auto completion floating window.
      • Cannot disable insert by default
      • Cannot hide winbar (need to edit source code)

TODO: zot

  • https://news.ycombinator.com/item?id=48319524
  • Pros:
    • extensions in any language via subprocess + json-rpc
  • Cons:
    • Does not support ACP
    • Does not support MCP

TODO: zerostack

  • https://news.ycombinator.com/item?id=48164287
  • Cons:
    • The discussions/plans are the explicit: e.g. Make zerostack extensible
    • Does not support hooks
    • Does not support per-model context window
    • ACP support incomplete: session resume, model switch
    • Explicitly state that skills is not supported. It prefer prompts.
{ enableExtendedCLI }:
{ config, lib, pkgs, ... }:
let
  npinsed = import <npins> {input=./sources.json;};
  pipkgs = import ./pkgs.nix {src = npinsed.nixpkgs;};
in {
  imports = [
    (lib.modules.importApply ./extensions {
      inherit enableExtendedCLI pipkgs;
      sources = npinsed;
    })
    ./providers
  ] ++ lib.optionals enableExtendedCLI [
    (lib.modules.importApply ./pi-web {src = npinsed.pi-web;})
  ];
  home.packages = [
    # Include session-file size (S5.5M) in Pi's built-in footer stats line.
    (pipkgs.pi-coding-agent.overrideAttrs (old: {
      patches = (old.patches or [ ]) ++ [
        ./footer-session-size.patch
        # Let extension widgets scroll with the fullscreen transcript instead of pinning them to the input dock.
        ./fullscreen-scrollable-widgets.patch
        # Let extensions observe fullscreen terminal focus reports without forwarding them to components.
        # Analogous upstream listener-order bug: https://github.com/earendil-works/pi/issues/10405.
        # Closed as not planned without a rationale, hence this local focus-propagation patch.
        ./fullscreen-focus-propagation.patch
      ];
    }))
  ];

  yq-merge.".pi/agent/settings.json" = {
    generator = builtins.toJSON;
    expr = {
      # Only fullscreen provides prompt navigation.
      tuiMode = "fullscreen";
      fullscreenWheelScrollLines = 1;
    };
  };

  yq-merge.".pi/agent/keybindings.json" = {
    generator = builtins.toJSON;
    expr = {
      "tui.altScreen.lineUp" = "shift+up";
      "tui.altScreen.lineDown" = "shift+down";
      "tui.altScreen.previousPrompt" = "alt+shift+up";
      "tui.altScreen.nextPrompt" = "alt+shift+down";
      "tui.altScreen.search" = "alt+shift+f";
      "tui.altScreen.top" = "alt+shift+left";
      "tui.altScreen.bottom" = "alt+shift+right";
    };
  };

  home.file.".pi/agent/sessions".source = config.lib.file.mkOutOfStoreSymlink ~/Gist/Data/pi/sessions;
}
{ enableExtendedCLI, sources, pipkgs }: # local-args
# My feeling: configure javascript/typescript plugins is awful.
{ lib, ... }: {
  imports = [
    (lib.modules.importApply ./pi-hermes-memory {src = sources.pi-hermes-memory; inherit pipkgs;})
    (lib.modules.importApply ./pi-co-authored-by.nix {src = sources.shelken-pi-extensions;})
    (lib.modules.importApply ./pi-math {src = sources.pi-math;})
    (lib.modules.importApply ./pi-language-tutor {src = sources.pi-language-tutor;})
    # No pi-retry: its detached loop can check before the retry starts, resetting backoff and bypassing limits.
    # Pi's native retry owns the lifecycle; we don't need the extension's continuation or nudge features.
    (lib.modules.importApply ./pi-context-view {src = sources.pi-context-view;})
    (lib.modules.importApply ./pi-model-fallback {src = sources.pi-model-fallback;})
    (lib.modules.importApply ./pi-model-project.nix {src = sources.pi-model-project;})
    (lib.modules.importApply ./pi-skill-usage.nix {src = sources.pi-skill-usage;})
    (lib.modules.importApply ./heuristic-notify.nix {src = sources.pi-heuristic-notify;})
    (lib.modules.importApply ./pi-web-access {src = sources.pi-web-access;})
    (lib.modules.importApply ./pi-title {src = sources.pi-title + "/extensions/title";})
    (lib.modules.importApply ./pi-subagents {src = sources.pi-subagents;})
    ./ponytail
    (lib.modules.importApply ./rpiv-ask-user-question.nix {src = sources.rpiv-mono;})
    (lib.modules.importApply ./rpiv-todo {src = sources.rpiv-mono;})
  ] ++ lib.optionals enableExtendedCLI [
    ./pi-read-aloud
  ];
  home.file = {
    # - Plan Extensions Comparison:
    #   - qmx/pi-plan-mode: fully read-only thus does not write md.
    #   - backnotprop/plannotator: I don't need the web annotation UI.
    #   - burneikis/pi-plan: no read-only support.
    # pi-constell-plan is a pi extension published by tridha643 from a fork that adds a packages/pi-constell directory to Owen
    # Gretzinger's original Constellagent desktop app, but its npm metadata incorrectly links to the upstream
    # owengretzinger/constellagent repo—which lacks that code—instead of the fork where the extension actually lives.
    #
    # OpenCode vs pi-constell-plan:
    # I test OpenCode plan mode and pi-constell-plan: using the prompt:
    # > Explain the essay "Memory dependence prediction using store sets" for me. You should first fetch it from internet, probably a
    # > pdf, then process pdf, then work on the content let me know what this paper it talk about.
    # OpenCode completely ignores plan mode, it call subagent to fetch pdf from the web, call subagent to explore, ...
    # pi-constell-plan obey perfectly: it write a plan file, then start follow the plan file.
    # Compared with upstream pi examples/extensions/plan-mode:
    # - upstream example: read-only planning + in-session todo execution tracking with [DONE:n] markers.
    # - pi-constell-plan: clarification-gated plan-file export to ~/.pi-constell/plans/, Constellagent-compatible, no todo executor.
    # - pi-constell-plan keeps write/edit available only for the active plan file after askUserQuestion; upstream disables write/edit entirely.
    # - pi-constell-plan does not allow DDGS MCP.
    # - builtin plan-mode also has `/todos`, which is the same name as rpiv-todo

    ".pi/agent/extensions/titlebar-spinner.ts" = {
      source = pipkgs.pi-coding-agent.src
        + "/packages/coding-agent/examples/extensions/titlebar-spinner.ts";
    };
  };
}
{ src }: # local-args
{ ... }: {
  home.file.".pi/agent/extensions/pi-heuristic-notify.ts".source = src.outPath + "/src/index.ts";
}
{ src }: # local-args
{ pkgs, ... }: {
  home.file.".pi/agent/extensions/pi-co-authored-by".source = pkgs.applyPatches {
    name = "pi-co-authored-by";
    src = src.outPath + "/extensions/pi-co-authored-by";
    # A root entrypoint makes Pi's compact banner show pi-co-authored-by, not src.
    postPatch = ''
      ${pkgs.jq}/bin/jq '.pi.extensions = ["./index.ts"]' package.json > package.json.new
      mv package.json.new package.json
      echo 'export { default } from "./src/index.ts";' > index.ts
    '';
  };
}
let
  pkgs = import <nixpkgs> {};
  sources = (import ../../../../../npins) {input=../sources.json;};
  module = import ./pi-co-authored-by.nix {src = sources.shelken-pi-extensions;} { inherit pkgs; };
  root = module.home.file.".pi/agent/extensions/pi-co-authored-by".source;
  manifest = builtins.fromJSON (builtins.readFile "${root}/package.json");
  original = builtins.fromJSON (builtins.readFile
    "${sources.shelken-pi-extensions}/extensions/pi-co-authored-by/package.json");
in pkgs.lib.runTests {
  test-coauthor-manifest = {
    expr = manifest;
    expected = original // { pi = original.pi // { extensions = [ "./index.ts" ]; }; };
  };
  test-coauthor-reexport = {
    expr = if builtins.pathExists "${root}/index.ts"
      then builtins.readFile "${root}/index.ts" else null;
    expected = "export { default } from \"./src/index.ts\";\n";
  };
}
{ src }: # local-args
{ pkgs, ... }:
let
  # Pi labels a local (non npm:/git:) extension in the startup banner after the
  # shortest unique tail of its entry path, with a trailing index.ts dropped.
  # Upstream declares ./src/index.ts, so the banner shows "src". Re-exporting
  # from a root index.ts makes the tail the package directory, "pi-context-view".
  patchedSrc = pkgs.applyPatches {
    name = "pi-context-view";
    inherit src;
    postPatch = ''
      substituteInPlace package.json --replace-fail '"./src/index.ts"' '"./index.ts"'
      echo 'export { default } from "./src/index.ts";' > index.ts
    '';
  };
in
{
  # Raw TypeScript source, zero runtime dependencies: Pi injects the
  # @earendil-works/* peer packages at runtime, so there is no npm build step.
  # `/context config` writes ~/.pi/agent/extensions/pi-context-view.json, a
  # sibling of this directory, so it stays writable.
  home.file.".pi/agent/extensions/pi-context-view".source = patchedSrc;
}
{ src, pipkgs }: # local-args
{ config, pkgs, lib, ... }: let
  # The node-gyp should be backed by the same version of nodejs as pi,
  # thus we use pkgspi.
  pkgspi = pipkgs;
in {
  home.file.".pi/agent/extensions/pi-hermes-memory" = {
    source = pkgspi.buildNpmPackage {
      name = "pi-hermes-memory";
      inherit src;
      # Pi supplies @earendil-works/* at runtime; dropping devDependencies and
      # peerDependencies also removes the nested lock entries whose missing
      # integrity used to require lock-integrity.patch.
      postPatch = ''
        ${lib.getExe pkgs.jq} 'del(.devDependencies, .peerDependencies, .scripts)' package.json > package.json.tmp && mv package.json.tmp package.json
        cp ${./package-lock.json} package-lock.json
      '';
      npmDepsFetcherVersion = 2;
      npmDepsHash = "sha256-iA9TQ21f3UcJoR3LGu6v8DR5VpSQFCXUXXyvkQpAkEc=";
      dontNpmBuild = true;
      # Pi uses the first path segment of pi.extensions entry as the banner
      # display name. Upstream uses "./src/index.ts" which shows as "src".
      # Move the entrypoint to "./index.ts" so it falls back to package name.
      postInstall = ''
        cd $out/lib/node_modules/pi-hermes-memory
        sed -i 's|"./src/index.ts"|"./index.ts"|' package.json
        echo 'export { default } from "./src/index.ts";' > index.ts
      '';
      nativeBuildInputs = with pkgspi; [
        node-gyp
        python3
      ];
    } + /lib/node_modules/pi-hermes-memory;
  };
  # Bound the session-search DB: prune indexed sessions untouched for 90 days on
  # startup. Rows only -- the JSONL transcripts on disk are never deleted.
  yq-merge.".pi/agent/hermes-memory-config.json" = {
    generator = builtins.toJSON;
    expr.sessionRetentionDays = 90;
  };

  home.file.".pi/agent/projects-memory".source = config.lib.file.mkOutOfStoreSymlink ~/Gist/Data/pi/projects-memory;

  # pi-hermes-memory writes MEMORY.md/USER.md via temp-file + rename, which would
  # replace per-file symlinks. Symlink the whole writable directory instead.
  home.file.".pi/agent/pi-hermes-memory".source = config.lib.file.mkOutOfStoreSymlink ~/Gist/Data/pi/pi-hermes-memory;
  my.syncthing.Gist-stignore = lib.mkAfter [
    "/Data/pi/pi-hermes-memory/sessions.db"
    "/Data/pi/pi-hermes-memory/sessions.db-*"
    # A SQLite inter-process lock DB, created next to the memory directory and
    # only meaningful on the machine holding it. Syncing it produced a pile of
    # .sync-conflict copies and no useful data.
    "/Data/pi/.pi-hermes-locks.*"
  ];
}
{ src }: # local-args
{ config, pkgs, lib, ... }:
{
  home.file.".pi/agent/extensions/pi-language-tutor".source = pkgs.buildNpmPackage {
    name = "pi-language-tutor";
    inherit src;
    postPatch = ''
      substituteInPlace src/config.ts src/flashcards.ts src/flashcard-settings.ts \
        --replace-fail "'.pi', 'agent'," "'.pi', 'agent', 'pi-language-tutor',"
      substituteInPlace src/config.ts README.md README.zh-CN.md \
        --replace-fail '~/.pi/agent/language-learn.json' '~/.pi/agent/pi-language-tutor/language-learn.json'
      substituteInPlace README.md README.zh-CN.md \
        --replace-fail '~/.pi/agent/flashcards.json' '~/.pi/agent/pi-language-tutor/flashcards.json' \
        --replace-fail '~/.pi/agent/flashcards-settings.json' '~/.pi/agent/pi-language-tutor/flashcards-settings.json'
      ${lib.getExe pkgs.jq} 'del(.peerDependencies, .devDependencies, .scripts)' package.json > package.json.tmp
      mv package.json.tmp package.json
      cp ${./package-lock.json} package-lock.json
      substituteInPlace src/learn.ts \
        --replace-fail "window.on('message', handleMessage)" \
        "window.on('message', handleMessage)
          window.on('error', (error: Error) => ctx.ui.notify(error.message, 'error'))"
    '';
    npmDepsHash = "sha256-B/zm5R+69hvwMYLkfUGMn0oVcXkO7lVKW/wAA+YZEdQ=";
    dontNpmBuild = true;
    npmRebuildFlags = [ "--ignore-scripts" ];
    postInstall = ''
      patch -p1 -d "$out/lib/node_modules/pi-language-tutor/node_modules/glimpseui" < ${./glimpse-stderr.patch}
    '';
  } + /lib/node_modules/pi-language-tutor;

  # Atomic writes replace file symlinks; link the writable directory instead.
  home.file.".pi/agent/pi-language-tutor".source = config.lib.file.mkOutOfStoreSymlink ~/Gist/Data/pi/pi-language-tutor;
  my.syncthing.Gist-stignore = lib.mkAfter [
    "/Data/pi/pi-language-tutor/*.tmp"
  ];
}
{ src }: # local-args
{ pkgs, lib, ... }:
{
  home.file.".pi/agent/extensions/pi-math".source = pkgs.buildNpmPackage {
    name = "pi-math";
    inherit src;
    postPatch = ''
      ${lib.getExe pkgs.jq} 'del(.peerDependencies, .devDependencies, .scripts)' package.json > package.json.tmp
      mv package.json.tmp package.json
      cp ${./package-lock.json} package-lock.json
    '';
    npmDepsHash = "sha256-gC8Y468G8f3AOVnggrWQYm3uO1IgVujviPJzfSjX/iE=";
    dontNpmBuild = true;
    postInstall = ''
      cd "$out/lib/node_modules/@monotykamary/pi-math"
      sed -i 's|"./src/index.ts"|"./index.ts"|' package.json
      echo 'export { default } from "./src/index.ts";' > index.ts
    '';
  } + "/lib/node_modules/@monotykamary/pi-math";
}
{ src }: # local-args
{ pkgs, lib, ai, ... }:
{
  # config.json and state.json live in Pi's agent dir (a sibling of this
  # extension), so `/model-fallback:*` keeps writing there.
  home.file.".pi/agent/extensions/pi-model-fallback".source = pkgs.buildNpmPackage {
    name = "pi-model-fallback";
    inherit src;
    # Pi injects @earendil-works/* and typebox at runtime; only proper-lockfile
    # is a real dependency, so the trimmed lockfile installs nothing else.
    postPatch = ''
      ${lib.getExe pkgs.jq} 'del(.devDependencies, .peerDependencies, .peerDependenciesMeta, .scripts)' package.json > package.json.tmp
      mv package.json.tmp package.json
      cp ${./package-lock.json} package-lock.json
    '';
    npmDepsHash = "sha256-8XXxcYSeq6rPOdL0BNW8lJFfM7Kco87pqNz4C6gKNaM=";
    dontNpmBuild = true;
  } + "/lib/node_modules/pi-model-fallback";

  # yq-merge deep-merges into the live file, so key and rule *deletions* here do
  # nothing and number arrays union. After removing a key or narrowing
  # `statuses`, delete ~/.pi/agent/model-fallback/config.json and switch again.
  # `version` is required by validateConfigShape: without it the extension only
  # warns "config error" and stays inert.
  yq-merge.".pi/agent/model-fallback/config.json" = {
    generator = builtins.toJSON;
    expr = {
      version = 1;
      rules = [
        {
          name = "kimi-unavailable";
          matchProviders = [ "jw2-kimi" ];
          statuses = [ 503 ];
          fallback = {
            provider = ai.moonshot-cn.id;
            model = ai.moonshot-cn.models."kimi-k3.1-pro".id;
          };
        }
      ];
    };
  };
}
{ src }: # local-args
{ ... }:
{
  home.file.".pi/agent/extensions/pi-model-project/index.ts".source = src + "/index.ts";
}

Pi read aloud

TTS-only integration for the selected Kokoro v1.1 FP32 model: af_maple (speaker 0), speed 1, four CPU threads. The original model, English/Chinese lexicons and Chinese normalization FSTs are preserved. No native pronunciation patches or runtime downloads are used.

Controls

  • Alt+R: idle → read the latest completed, speakable assistant reply; reading → pause the current reply, even if a newer reply exists; paused → resume the same reply, or replace it if a newer reply exists.
  • /voice-speak: wait for the agent to settle, then read its latest reply.
  • /voice-speak text: read supplied text immediately.
  • /voice-speak-stop: stop playback and cancel any read command still waiting for the agent.

Reply identity is the session entry ID, not text equality. Only persisted assistant text from the current branch is selected; thinking, tool output, failed/aborted messages and code blocks are excluded. Basic Markdown formatting is removed; inline names remain speakable. Sentences are generated one at a time in chunks of at most 400 UTF-16 code units, without splitting surrogate pairs. Pause during synthesis holds the completed audio until resume and prevents further synthesis while paused.

Playback does not display a footer status; failures use Pi notifications, never direct terminal output. Session shutdown/reload/switch closes both processes; tree navigation stops the current read. Nothing starts at extension load or agent completion: there is no automatic narration, dictation, model browser, HTTP server or settings framework. Fcitx5 vinput is unaffected. The model remains at ~/.pi/models/tts/kokoro-multi-lang-v1_1; native diagnostics go to <Pi agent directory>/read-aloud.log (normally ~/.pi/agent/read-aloud.log).

Synthesis

backend.mjs exposes Kokoro({ modelDir, logPath }), synthesize(text, { signal }) and close(). A request accepts at most 600 UTF-16 code units; only one request may be active. The caller splits longer replies instead of retaining an entire reply's audio.

worker.mjs is the only process that loads sherpa-onnx. It keeps the model warm across requests and returns mono 24 kHz float samples over IPC. Its stdout/stderr go directly to the specified append-only log, created with mode 0600. The log may contain text/phonemes from the reply; it is not a general Pi stderr log. Known native pronunciation diagnostics remain in the log without modifying the model.

Cancellation terminates the private worker and discards the current chunk; the next request reloads the model. close() rejects active work and waits for children to exit; a worker also exits when its parent disconnects. Synthesis failures and unexpected worker exits reject normally instead of crashing Pi.

Playback

player.mjs owns one mpv process per reply. Mono float PCM arrives through stdin; JSON commands and acknowledgements use inherited fd 3, with no public socket. write() applies backpressure, setPaused() waits for mpv's acknowledgement, and end() waits until the last audio finishes. stop() rejects pending work and reaps the process. A player can start paused, so a pause during synthesis never leaks the first audio. mpv configuration files and terminal input are disabled; read-ahead is capped at 256 KiB. Player diagnostics are captured and bounded, not printed into Pi.

Home Manager

default.nix installs the local npm package, the unchanged model symlink and mpv on x86-64/AArch64 Linux. It replaces the old voicekit module/pin and does not change Pi settings or the Pi launcher. No manual stderr redirection is needed. After a Home Manager activation, restart Pi or run /reload to unload the old extension. Building and testing this module does not activate it.

Verification

nix eval -f usr/cli/basic/pi/extensions/pi-read-aloud/test.nix
nix-build usr/cli/basic/pi/extensions/pi-read-aloud/check.nix --no-out-link

The check builds the native npm dependency with Nix ELF fixups and runs under a disposable HOME. It exercises actual Chinese, English and mixed-language synthesis, checks finite audible samples, proves native diagnostics stay out of the parent terminal and native libraries stay out of the parent process, verifies model reuse, and tests cancellation, shutdown, worker crashes and recovery. Playback tests use actual mpv with --ao=null: its real playback clock must freeze/resume, a paused write must apply backpressure, EOF must finish cleanly, and cancellation must reap the process without uncaught socket errors. Control tests cover newer replies (including identical text with different IDs), pause during synthesis, rapid controls, cleanup and failures. The installed Pi loader also runs the registered commands/shortcut through actual native synthesis and mpv, checking empty startup, cancelled idle waits, branch changes, explicit speech, stop and shutdown with clean parent output. A separate real Pi RPC process verifies slash-command dispatch without starting an LLM run, session replacement, active-playback shutdown on stdin EOF, child-process reaping, valid JSONL output and empty stderr.

{ pkgs ? import <nixpkgs> {} }:
let
  sources = (import ../../../../../../npins) {input=../../sources.json;};
  pipkgs = import ../../pkgs.nix {src = sources.nixpkgs;};
  package = import ./package.nix { inherit pkgs; };
  model = import ./model.nix { inherit pkgs; };
in pkgs.runCommand "pi-read-aloud-check" {
  nativeBuildInputs = [ pkgs.nodejs ];
  PI_ROOT = "${pipkgs.pi-coding-agent}/lib/node_modules/pi-monorepo";
  READ_ALOUD_PACKAGE = "${package}/lib/node_modules/pi-read-aloud";
  READ_ALOUD_MODEL = model;
  READ_ALOUD_MPV = pkgs.writeShellScript "mpv-null" ''
    exec ${pkgs.mpv-unwrapped}/bin/mpv --ao=null "$@"
  '';
} ''
  export HOME=$TMPDIR/home
  mkdir -p $HOME $out
  node --test ${./backend.test.mjs} > $out/backend.log 2>&1 || { cat $out/backend.log; exit 1; }
  cat $out/backend.log
  node --test ${./player.test.mjs} > $out/player.log 2>&1 || { cat $out/player.log; exit 1; }
  cat $out/player.log
  node --test ${./text.test.mjs} ${./reader.test.mjs} > $out/controls.log 2>&1 || { cat $out/controls.log; exit 1; }
  cat $out/controls.log
  export READ_ALOUD_TEST_HOME=$HOME
  mkdir -p test-bin
  ln -s $READ_ALOUD_MPV test-bin/mpv
  export PATH=$PWD/test-bin:$PATH
  if ! node --test ${./index.test.mjs} > $out/index.log 2> $out/index-stderr.log; then
    cat $out/index.log $out/index-stderr.log
    exit 1
  fi
  cat $out/index.log
  test ! -s $out/index-stderr.log
  if grep -E 'Unknown token:|Skip unknown phonemes' $out/index.log; then exit 1; fi
  if ! node --test ${./rpc.test.mjs} > $out/rpc.log 2> $out/rpc-stderr.log; then
    cat $out/rpc.log $out/rpc-stderr.log
    exit 1
  fi
  cat $out/rpc.log
  test ! -s $out/rpc-stderr.log
''
{ pkgs, lib, ... }:
let
  extension = import ./package.nix { inherit pkgs; };
  model = import ./model.nix { inherit pkgs; };
in lib.mkIf (builtins.elem pkgs.stdenv.hostPlatform.system [ "x86_64-linux" "aarch64-linux" ]) {
  home.file.".pi/agent/extensions/pi-read-aloud".source = extension + "/lib/node_modules/pi-read-aloud";
  home.file.".pi/models/tts/${model.modelId}".source = model;
  home.packages = [ pkgs.mpv-unwrapped ];
}
{ pkgs }:
let
  modelId = "kokoro-multi-lang-v1_1";
  archive = pkgs.fetchurl {
    url = "https://github.com/k2-fsa/sherpa-onnx/releases/download/tts-models/${modelId}.tar.bz2";
    hash = "sha256-t44axCuFLoOczqr76I9mgGv1hgmS0de5o/KtEZhCeu0=";
  };
in pkgs.runCommand modelId {
  nativeBuildInputs = [ pkgs.gnutar pkgs.bzip2 ];
  passthru = { inherit modelId; };
} ''
  mkdir -p $out
  tar -xjf ${archive} --strip-components=1 -C $out
  for file in model.onnx voices.bin tokens.txt lexicon-us-en.txt lexicon-zh.txt number-zh.fst date-zh.fst phone-zh.fst; do
    test -s "$out/$file"
  done
  test -d $out/espeak-ng-data
''
{ pkgs ? import <nixpkgs> {} }:
pkgs.buildNpmPackage {
  pname = "pi-read-aloud";
  version = "0.1.0";
  src = ./.;
  npmDepsHash = "sha256-lqMnKBGsJqKKtu4LMEyZ153qec+nxaOOeGjK5rIc67I=";
  npmFlags = [ "--ignore-scripts" ];
  dontNpmBuild = true;
  nativeBuildInputs = [ pkgs.autoPatchelfHook ];
  buildInputs = [ pkgs.stdenv.cc.cc.lib ];
}
let
  pkgs = import <nixpkgs> {};
  sources = (import ../../../../../../npins) {input=../../sources.json;};
  inherit (pkgs) lib;
  evaluate = packages: (lib.evalModules {
    specialArgs.pkgs = packages;
    modules = [
      {
        options.home.file = lib.mkOption { type = lib.types.attrsOf lib.types.anything; default = {}; };
        options.home.packages = lib.mkOption { type = lib.types.listOf lib.types.package; default = []; };
        options.yq-merge = lib.mkOption { type = lib.types.attrsOf lib.types.anything; default = {}; };
      }
      ./default.nix
    ];
  }).config;
  cfg = evaluate pkgs;
  unsupported = evaluate (pkgs // { stdenv = pkgs.stdenv // { hostPlatform.system = "x86_64-darwin"; }; });
  imports = builtins.readFile ../default.nix;
in lib.debug.throwTestFailures { failures = lib.runTests {
  test-installed-files = {
    expr = builtins.attrNames cfg.home.file;
    expected = [ ".pi/agent/extensions/pi-read-aloud" ".pi/models/tts/kokoro-multi-lang-v1_1" ];
  };
  test-auditioned-model-preserved = {
    expr = toString (cfg.home.file.".pi/models/tts/kokoro-multi-lang-v1_1".source or "missing");
    expected = toString (import ./model.nix { inherit pkgs; });
  };
  test-mpv-installed = { expr = cfg.home.packages; expected = [ pkgs.mpv-unwrapped ]; };
  test-no-global-settings-overrides = { expr = cfg.yq-merge; expected = {}; };
  test-unsupported-platform-stays-disabled = { expr = unsupported.home.file; expected = {}; };
  test-new-import = { expr = lib.hasInfix "./pi-read-aloud" imports; expected = true; };
  test-no-old-import = { expr = lib.hasInfix "./pi-voicekit" imports; expected = false; };
  test-no-old-upstream-pin = { expr = sources ? pi-voicekit; expected = false; };
}; }
{ src }: # local-args
{ config, lib, ... }: {
  # No runtime deps, and the entry lives at the repo root, so the pinned source
  # can be linked directly: pi labels the extension after the directory holding
  # its entry file, which is "pi-skill-usage" here.
  home.file.".pi/agent/extensions/pi-skill-usage".source = src.outPath;

  # The ledger is written via temp-file + rename, which replaces a per-file
  # symlink, so the counts are shared through a symlinked directory instead.
  home.file.".pi/agent/skill-usage".source = config.lib.file.mkOutOfStoreSymlink ~/Gist/Data/pi/skill-usage;
  # The temp file lives in that same directory; don't replicate it.
  my.syncthing.Gist-stignore = lib.mkAfter [ "/Data/pi/skill-usage/*.tmp" ];
}
{ src }: # local-args
{ pkgs, lib, ... }:
let
  package = pkgs.buildNpmPackage {
    name = "pi-subagents";
    inherit src;
    npmDepsHash = "sha256-IwiXL+YzM0jSlOnq/tmlTV9nA6ydWDwoFg3kUFbeOhs=";
    dontNpmBuild = true;
    postPatch = ''
      ${lib.getExe pkgs.jq} 'del(.devDependencies, .peerDependencies, .peerDependenciesMeta, .scripts)' \
        package.json > package.json.tmp
      mv package.json.tmp package.json
      cp ${./package-lock.json} package-lock.json
    '';
  };
in {
  yq-merge.".pi/agent/settings.json".expr.packages = [
    "${package}/lib/node_modules/pi-subagents"
  ];
}
{ src }: # local-args
{ pkgs, lib, ai, ... }: {
  home.file.".pi/agent/extensions/pi-title".source = pkgs.buildNpmPackage {
    name = "pi-title";
    inherit src;
    postPatch = ''
      ${lib.getExe pkgs.jq} 'del(.peerDependencies, .devDependencies, .scripts)' package.json > package.json.tmp
      mv package.json.tmp package.json
      cp ${./package-lock.json} package-lock.json
    '';
    npmDepsHash = "sha256-r4w9nnnKSZzYnvZ0mAiZt2XSx4uqFixiMJsJDGqhr7o=";
    dontNpmBuild = true;
  } + "/lib/node_modules/pi-title";

  yq-merge.".pi/agent/pi-title.jsonc" = {
    generator = builtins.toJSON;
    expr = {
      refreshTurns = 5;
      model = let
        effort = lib.findFirst (option: option.type == "effort")
          (throw "pi-title model has no reasoning effort levels") ai.default_small.model.reasoning_options;
      in "${ai.default_small.provider.id}/${ai.default_small.model.id}:${lib.head effort.values}";
    };
  };
}
let
  pkgs = import <nixpkgs> {};
  sources = import <npins> {input = ../../sources.json;};
  module = import ./default.nix {src = sources.pi-title + "/extensions/title";} {
    inherit pkgs;
    inherit (pkgs) lib;
    ai.default_small = {
      provider = { id = "test-provider"; };
      model = { id = "test-model"; reasoning_options = [{ type = "toggle"; } { type = "effort"; values = [ "low" "high" ]; }]; };
    };
  };
  root = module.home.file.".pi/agent/extensions/pi-title".source;
in pkgs.lib.debug.throwTestFailures { failures = pkgs.lib.runTests {
  test-installed-entrypoint = {
    expr = builtins.pathExists "${root}/index.ts";
    expected = true;
  };
  test-runtime-dependencies = {
    expr = builtins.attrNames (builtins.fromJSON (builtins.readFile "${root}/package.json")).dependencies;
    expected = [ "jsonc-parser" ];
  };
  test-title-settings = {
    expr = module.yq-merge.".pi/agent/pi-title.jsonc".expr;
    expected = { refreshTurns = 5; model = "test-provider/test-model:low"; };
  };
}; }
{ src }: # local-args
{ pkgs, lib, ai, ... }:
{
  # Search-provider keys live in Pi's agent dir, not in Nix. Written by yq-merge
  # (a real file, not a store symlink) so the extension's `/websearch` edits keep
  # working; the keys still end up in the store, same as auth.json.
  yq-merge.".pi/agent/web-search.json" = {
    generator = builtins.toJSON;
    expr = {
      webSearch.allowedProviders = [ "exa" "tavily" "deepseek" ];
      tavilyApiKey = ai.tavily.api_key;
      deepseekApiKey = ai.deepseek.api_key;
    };
  };

  home.file.".pi/agent/extensions/pi-web-access".source = pkgs.buildNpmPackage {
    name = "pi-web-access";
    inherit src;
    # Pi injects @earendil-works/* and typebox at runtime, so drop its dev/peer
    # deps and their transitive graph from the install.
    postPatch = ''
      ${lib.getExe pkgs.jq} 'del(.devDependencies, .peerDependencies, .peerDependenciesMeta, .scripts)' package.json > package.json.tmp
      mv package.json.tmp package.json
      cp ${./package-lock.json} package-lock.json
    '';
    npmDepsHash = "sha256-aoS9mSkbGjjnhm7rwWoPBgK2XWJCmg0OmUMuuwAI/yc=";
    dontNpmBuild = true;
    npmRebuildFlags = [ "--ignore-scripts" ];
    nativeBuildInputs = [ pkgs.jq ];
    postInstall = ''
      # `bin` points at dist/mcp-cli.js, which only upstream's publish build
      # creates; drop the dead wrapper and the field that promises it.
      rm -rf $out/bin
      dir=$out/lib/node_modules/pi-web-access
      jq 'del(.bin)' "$dir/package.json" > "$dir/package.json.tmp"
      mv "$dir/package.json.tmp" "$dir/package.json"
      # Guard the one contract Pi needs: every declared entry file must exist.
      jq -r '.pi.extensions[]' "$dir/package.json" | while read -r e; do test -f "$dir/$e"; done
    '';
  } + /lib/node_modules/pi-web-access;
}
{ ... }: {
  # Superseded the upstream ponytail extension (npins pin removed): the rules
  # now live in a pi-hermes-memory managed skill, injected by this one-file
  # extension. Level switching and the status bar went with the old extension.
  home.file.".pi/agent/extensions/inject-ponytail.ts".source = ./inject-ponytail.ts;
}
{ src }: # local-args
{ pkgs, ... }: {
  # No npm build needed: the only runtime dep is its sibling workspace package
  # (@juicesharp/rpiv-config), so drop it into node_modules by hand. Pi aliases
  # typebox / pi-tui / pi-coding-agent itself, and rpiv-i18n is an optional peer.
  home.file.".pi/agent/extensions/rpiv-ask-user-question" = {
    source = pkgs.runCommand "rpiv-ask-user-question" { } ''
      mkdir -p $out/node_modules/@juicesharp
      cp -r ${src}/packages/rpiv-ask-user-question/. $out/
      cp -r ${src}/packages/rpiv-config \
        $out/node_modules/@juicesharp/rpiv-config
      # Nothing at runtime reads docs/ or the tests; their deps (vitest,
      # rpiv-test-utils) are not installed either.
      # cp keeps the store's read-only modes.
      chmod -R u+w $out
      rm -rf $out/docs
      find $out -name '*.test.ts' -delete
      rm -f $out/test-fixtures.ts
    '';
  };
}
{ src }: # local-args
{ pkgs, lib, ... }: {
  home.file.".pi/agent/extensions/rpiv-todo" = {
    source = pkgs.buildNpmPackage {
      name = "rpiv-todo";
      inherit src;
      # Trim monorepo to only rpiv-todo's workspace deps so npm fetches less.
      # Strip devDeps from root and peerDeps from workspace packages — Pi
      # provides @earendil-works/* at runtime.
      postPatch = ''
        ${lib.getExe pkgs.jq} '
          .workspaces = ["packages/rpiv-todo", "packages/rpiv-config", "packages/rpiv-i18n"]
          | .devDependencies = {}
          | .scripts = {}
        ' package.json > package.json.tmp && mv package.json.tmp package.json
        for p in packages/rpiv-{todo,config,i18n}; do
          ${lib.getExe pkgs.jq} 'del(.peerDependencies, .devDependencies)' \
            "$p/package.json" > "$p/package.json.tmp" && mv "$p/package.json.tmp" "$p/package.json"
        done
        cp ${./lockfile.json} package-lock.json
      '';
      npmDepsHash = "sha256-QmawBpJVX4jyQ4vLZOyIlo1iCUzEYNrBlOqgOMCHG5Q=";
      dontNpmBuild = true;
    } + /lib/node_modules/rpiv-mono/packages/rpiv-todo;
  };
}
{ pkgs ? import <nixpkgs> {} }:
let
  sources = import <npins> { input = ../sources.json; };
  pipkgs = import ../pkgs.nix { src = sources.nixpkgs; };
in pkgs.runCommand "pi-native-retry-check" {
  nativeBuildInputs = [ pipkgs.nodejs ];
  PI_ROOT = "${pipkgs.pi-coding-agent}/lib/node_modules/pi-monorepo";
} ''
  export HOME=$TMPDIR/home
  mkdir -p "$HOME" "$out"
  node --test ${./test.mjs} > "$out/retry.log" 2>&1 || { cat "$out/retry.log"; exit 1; }
  cat "$out/retry.log"
  # The CLI uses a separate bundle; the basispoints classification must be compiled into it too.
  grep -rq 'basispoints_protocol_error' "$PI_ROOT/dist/bundle"
''

TLDR: In terms of Subpath / prefix deploy, jmfederico/pi-web is better, so I chose it.

Pi Web UI Comparison

Web/browser UIs for the pi coding agent. Evaluated for my setup:

  • VPS = Home Manager targets.genericLinux, root systemd user services + linger (server/default.nix, server/caddy, server/authelia).
  • Access = Caddy + Authelia forward_auth at xieby1.cn, one subpath per app with uri strip_prefix (see /sixu/xby/*, /circle/xby/*, /web/*).
  • pi is Nix-pinned via pkgs.pkgsu.pi-coding-agent; sessions symlinked out of store to ~/Gist/Data/pi/sessions. One reproducible agent runtime, please.
  • Use from phone/tablet, sessions must not die when the browser goes away.

Versions/stars as of 2026-09-23. pi-coding-agent latest = 0.87.1; our installed pi = 0.86.1 (pkgsu).

At a glance

jmfederico/pi-webxing-shuyin/pi-web-uiagegr/pi-web
Stars / npm803★ / 8.8k mo230★ / 27.2k mo6707★ / 21.7k mo
Runtimeseparate session daemon + web/APIpi SDK in-processpi SDK in-process
In-flight turn survives web restartyesnono
Idle evictionnonoyes, 10 min default (PI_WEB_IDLE_TIMEOUT_MS)
pi SDK bindingpeer >=0.87.0 (uses your pi)bundled >=0.85.1 <0.87.0bundled pinned 0.87.0
Works on our pi 0.86.1no — bump pi to ≥0.87.0 firstyes — bundled resolves to 0.86.1, same as oursyes (bundles 0.87.0, ignores ours)
Multi-machine fleetyesnono
Built-in authnone (proxy only)token (PI_WEB_TOKEN)password + throttle
Subpath / prefix deployfully portable — relative URLs, one build works at / or any prefix, no confignot prefix-safe — root-absolute /assets,/favicon.svg,/ws,/api/file; needs extra root-path proxy routesno documented basePath
Mobile / PWAPWA, mobile nav still openbest: PWA + SW OS notif + offlinePWA, iOS 16.2 blank page, poll battery
Nix packagingogglord/pi-web-nix (pkg + NixOS module)Sion10032/pi-web-ui-nix (home-manager module)none

pi SDK binding — the important axis

@earendil-works/pi-coding-agent is one package with both the pi CLI and the SDK.

  • jmfederico: peerDependencies >=0.87.0, no bundled copy → runs your installed pi. ogglord/pi-web-nix exposes a piPackage option for a Nix-provided pi. Clean fit with pkgs.pkgsu.pi-coding-agent.
  • xing-shuyin: bundles >=0.85.1 <0.87.0, which resolves to 0.86.1 — exactly our installed pi. It does not drift from us today; it only lags the upstream npm release (0.87.1). It will drift the moment pkgsu bumps us to 0.87.x, until the author widens the range. PI_WEB_SDK=global / /api/health → piSdkCopies are the escape hatches.
  • Reality for us: jmfederico's peer floor (>=0.87.0) is above our pin (0.86.1) → it cannot run until pi is bumped. xing-shuyin's bundle matches us today.
  • agegr: bundles pinned 0.87.0 (pi-ai/pi-tui/pi-agent-core/pi-coding-agent) → effectively aligned with the CLI, but still a second, npm-managed copy.

Config reuse is not blocked by bundling — all three read ~/.pi/agent (or PI_CODING_AGENT_DIR) and share sessions. Only the code version differs.

jmfederico/pi-web (PI WEB)

  • Pros:
    • Session daemon decoupled from web/API → phone disconnects and web restarts do not interrupt work. The one thing that matters for an always-on VPS.
    • Runs your pi (peer dep); ogglord/pi-web-nix already splits it into pi-web-sessiond + pi-web services — maps onto root systemd user services.
    • Blocker today: requires pi >=0.87.0; our pin is 0.86.1. Bump pi first.
    • Fleet: one gateway can proxy projects/sessions/terminals/git from other machines.
    • Fully prefix-portable (verified in the built client). index.html uses ./assets/*, and the client resolves every API/WS/PWA URL through resolveAppUrl/resolveAppWebSocketUrl (import.meta.env.BASE_URL resolved against document.baseURI; even a leading / is rewritten to the application root, not the origin root). Docs: "one build works at / and at canonical trailing-slash prefixes such as /ai/" — no rebuild, no config, no root-path routes. A prefix deploy is just handle_path /pi/* { import auth; reverse_proxy 127.0.0.1:8504 }.
    • Authelia covers its missing built-in auth.
  • Cons:
    • No built-in auth at all (README/FAQ: do not expose to the internet; VPN/tunnel/ authenticated proxy only).
    • English-only; no PDF/DOCX/audio preview (#119); no ANSI tool output (#121); no chat minimap (#118); no per-message rewind/fork (#237, #221); no web push (#193).
    • Session views go blank after a session-daemon restart, no replay (#185).
    • Mobile nav redesign pending (#173); younger project (803★).
    • ogglord/pi-web-nix is brand-new/0-star → vendor it, don't trust it blindly.

xing-shuyin/pi-web-ui

  • Pros:
    • Best browser/mobile client: installable PWA, service-worker OS notifications that fire while backgrounded, offline shell, 10 languages, desktop app.
    • Richest features: subagents + templates, MCP hot-reload, terminal-backed bash, Git panel, background-task panel, goal mode, plugins/themes, DSH engine.
    • Built-in token auth + strict Origin/Host check + host allow-list (defense in depth).
    • Best Nix story: Sion10032/pi-web-ui-nix ships a home-manager module + VM test.
    • Very active (daily releases).
  • Cons:
    • Bundled npm SDK (0.86.1) — matches our pi today, but is a second copy we do not control; drifts when pkgsu bumps pi (see above).
    • In-process runtime: a server restart loses the in-flight turn (it only reports "last run was interrupted" afterward).
    • Subpath hosting is a first-class weakness (root-absolute paths). The built web/dist keeps root-absolute refs the app cannot re-base: index.html → /assets/*, /favicon.svg; KaTeX CSS → url(/assets/…); JS → /icons/icon-192.png. Upstream's own deploy/nginx-subpath.conf therefore proxies /pi/ plus root /assets/, /favicon.svg, /api/file, /api/health, /ws — it works only if pi-web-ui owns those origin-root paths. There is no configurable base path (subpath, basePath, BASE_URL, proxy_pass, strip_prefix all return 0 hits across upstream issues+PRs; the README documents the nginx recipe instead of tracking it as a bug). Consequence: on a shared host the root /api/* route collides with anything else owning it (e.g. Authelia) → use a dedicated hostname. Also needs Host forwarded as the full authority incl. port (strict Origin≡Host, from #3) or WS upgrades 403.
    • Newest (2026-08); one merge/release owner (code contributions are multi-person). Its 0 open issues is a triage artifact, not stability: 137 filed in 7 weeks, median 4.1 h to close (see Stability).
    • node-pty native module → build script must be allowed in the derivation.

agegr/pi-web

  • Pros:
    • Biggest project (6707★) and most polished local client: session branching, file preview (PDF/DOCX/audio), minimap, ANSI, Mermaid, provider usage, i18n, built-in password + throttle.
    • Reads the same config/session files as pi ("shared configuration").
  • Cons:
    • Local-first design, not a remote control plane.
    • No documented basePath → awkward under the shared-host subpath Caddy pattern.
    • Idle session eviction (10 min) + no daemon separation.
    • Memory never returned to the OS — #923 (one forced GC freed 360 MB / 40% RSS at 14 h uptime; 48 h run degraded). Bad for a 24/7 root service.
    • Bundles its own pinned SDK; no Nix packaging exists.
    • iOS 16.2 blank page (#753); mobile battery/heat (#924).

Reuse of ~/.pi/agent

Both finalists default --agent-dir / PI_CODING_AGENT_DIR to ~/.pi/agent, so both read our settings, models, auth, extensions, skills, sessions, packages, and MCP — but it is not pure reuse:

~/.pi/agent/*jmfedericoxing-shuyin
settings.json✅ agent state✅ read + its own Settings UI
models.json, auth.json✅✅
extensions/ (our 7)✅ "globally installed Pi extensions"✅ per-extension switches
skills✅✅
sessions/✅✅ <agentDir>/sessions/--<cwd>--/
npm/ pi packages✅✅ reads <agentDir>/npm/package.json
trust.json✅ explicit; no browser trust promptreads agent dir; undocumented
mcp.json (ddgs)via our pi-mcp-adaptervia our extension + its own ~/.pi-web/mcp.json
injects own pi extension✅ extensions/pi-web.ts + packages✅ extensions/webui.ts
own UI state dir~/.config/pi-web/~/.pi-web/

Caveats:

  • Version gate (above) decides whether either even runs on our pin.
  • Both inject their own extension → ours plus theirs, not pure reuse.
  • xing-shuyin adds a second MCP surface (~/.pi-web/mcp.json) beside our extension.
  • Declarative conflict: our settings.json/models.json are yq-merge-managed and our extensions/ are read-only store symlinks; both UIs' Settings panels write those files, so treat them read-only or fold changes back into yq-merge. xing-shuyin also writes provider-keys.json into the agent dir.
  • TUI-only extensions (titlebar-spinner.ts, pi-heuristic-notify.ts) likely no-op or warn under a headless web runtime.
  • npm update flows (pi install, npm i -g) do not fit our Nix model — disable them.

Stability

xing-shuyinjmfederico
Age7 weeks4.5 months
Issues filed / open137 / 0104 / 38 (~5 bugs, rest features)
Median time-to-close4.1 h67.8 h
Closed ≤24 h93%33%
p90 time-to-close19 h≈37 days
Commits, last 30 d653191
Releases, last 30 d57 (~2/day)3 (monthly)
Bug reports / month~19~2.7

xing-shuyin is responsive but volatile — a rolling release at ~7× the bug-discovery rate; its 0-open board is a triage artifact (median 4.1 h), not an absence of defects (the closed set includes data loss #280 and a compaction desync #276). jmfederico is conservative but slow — monthly releases and fewer bugs, but a 37-day p90 lets real bugs (#185) linger. For a 24/7 box we leave alone, lower churn wins.

Verdict

jmfederico/pi-web for this box — once pi is bumped to >=0.87.0:

  1. Only one that runs our Nix-pinned pi (peer dep + piPackage), no second runtime.
  2. Only one whose architecture matches "VPS + phone/tablet" (daemon; survives web restart).
  3. Fits the existing Caddy subpath + Authelia forward_auth pattern (relative URLs).
  4. Authelia neutralises its one real weakness (no auth).
  5. Low churn / monthly releases — the more stable base (see Stability).

Today it does not run: our pin is 0.86.1, jmfederico needs >=0.87.0 — bump pi in pkgsu/npins and re-verify extensions/patches before adopting.

Switch to xing-shuyin/pi-web-ui only if the client experience (mobile PWA, notifications, subagents/MCP/git/goal mode) outweighs: bundled npm SDK instead of pkgsu pi, in-process runtime (restart kills the turn), subpath friction.

Not agegr/pi-web for the server — local-first, no basePath, idle eviction + memory leak, no Nix packaging. Keep it as a local desktop companion.

Integration sketch (jmfederico)

  • First bump pi to >=0.87.0 (pkgsu/npins) and re-verify extensions/patches.
  • Package @jmfederico/pi-web via buildNpmPackage (allow node-pty build script), or vendor ogglord/pi-web-nix; pin with npins like sixu.
  • Two systemd.user.services: pi-web-sessiond and pi-web, bind 127.0.0.1:8504, piPackage = pkgs.pkgsu.pi-coding-agent, PI_WEB_ALLOWED_HOSTS=xieby1.cn.
  • Caddy: redir /pi /pi/ + handle /pi/* { route { import auth; uri strip_prefix /pi; reverse_proxy 127.0.0.1:8504 } } (WebSocket included).
  • Skip pi-web install — define the units declaratively.

Also considered

  • ygncode/pi-web — Go server, PWA-first, Tailscale-native, mobile-optimised; beta, thinner adoption (711 mo). Best if mobile UX > maturity.
  • thecodacus/pithagoras — server-owned runs, append-only event log replays missed events, built-in PORTAL_PASSWORD, channels (Discord/Telegram); Docker. Pick if you want built-in auth without a VPN.
  • rcarmo/piclaw — self-hosted "AI workspace", Docker/portable, scheduled tasks, i18n.
  • BlackBeltTechnology/pi-agent-dashboard — "army of agents": parallel sessions, OpenSpec, zrok tunnel.
  • Epsilondelta-ai/pi-web — single Go binary + trusted plugin catalog.
  • isr4el-silv4/pi-web-ui — not a session UI: Chrome side-panel + CDP bridge to give the agent browser control.
  • Forks/derivatives of agegr: @pricening/pi-web, @silgrid/pi-web, @rainmanhhh/pi-web, @baique/pi-web-sky, @realchendahuang/dahuang-pi-web-ui, @twofive/snail-pi-web, @timmygod/pi-web-local (= ygncode fork tuned for local LLMs).
  • Shared gaps of all: no multi-user/RBAC, no sandbox (agent has the VPS shell), no native mobile app, no GitHub/PR integration, no cron/scheduled runs.
{ src }: # local-args
{ config, pkgs, lib, ... }:
let
  inherit (config.home) homeDirectory;

  nodejs = pkgs.nodejs_22;

  # NOT ~/.pi-web: that is xing-shuyin's default and upstream's default too.
  dataDir = "${homeDirectory}/.local/state/pi-web";
  port = 8504;

  pi-web = pkgs.buildNpmPackage {
    pname = "pi-web";
    version = src.version;

    inherit src;

    npmDepsFetcherVersion = 2;
    npmDepsHash = "sha256-wK8vjDm8JhaDWtj9GBfwYrkVyDb4bN9+W0hJypOleKs=";

    inherit nodejs;
    nativeBuildInputs = [ pkgs.makeWrapper ];

    installPhase = ''
      runHook preInstall
      mkdir -p $out/lib/node_modules/pi-web $out/bin
      cp -r dist node_modules package.json $out/lib/node_modules/pi-web/
      # npm workspace symlinks point into the relocated build tree; drop dangling ones.
      find $out/lib/node_modules/pi-web/node_modules -type l ! -exec test -e {} \; -delete 2>/dev/null || true
      makeWrapper ${nodejs}/bin/node $out/bin/pi-web          --add-flags "$out/lib/node_modules/pi-web/dist/cli.js"
      makeWrapper ${nodejs}/bin/node $out/bin/pi-web-server   --add-flags "$out/lib/node_modules/pi-web/dist/server/index.js"
      makeWrapper ${nodejs}/bin/node $out/bin/pi-web-sessiond --add-flags "$out/lib/node_modules/pi-web/dist/server/sessiond.js"
      runHook postInstall
    '';
  };

in
{
  home.packages = [ pi-web ];

  # Prevent pi-web from auto-installing packages into the managed Pi settings.
  home.file.".local/state/pi-web/pi-package-dismissals.json".text = builtins.toJSON {
    dismissals = map (packageId: {
      profileDir = "${homeDirectory}/.pi/agent";
      inherit packageId;
      dismissedAt = "1970-01-01T00:00:00.000Z";
    }) [ "@jmfederico/pi-session-naming" "@jmfederico/pi-relay" "@jmfederico/pi-web-workflows" ];
  };

  # A dismissal prevents reinstalling; remove references installed before it existed.
  home.activation.disablePiWebSessionNaming = lib.hm.dag.entryAfter [ "onFilesChange" ] ''
    if [[ -f "${homeDirectory}/.pi/agent/settings.json" ]]; then
      run ${lib.getExe pkgs.yq-go} -i '
        .packages = ((.packages // []) | map(select(
          ((.source // .) | test("(^npm:@jmfederico/pi-session-naming(@.*)?$|^@jmfederico/pi-session-naming(@.*)?$|/pi-web/dist/pi-packages/session-naming/?$)")) | not
        )))
      ' "${homeDirectory}/.pi/agent/settings.json"
    fi
  '';

  # Web/API restarts do not interrupt in-flight work; the daemon owns the runtimes.
  systemd.user.services.pi-web-sessiond = {
    Unit = {
      Description = "pi-web session daemon (owns Pi session runtimes)";
      After = [ "network.target" ];
    };
    Install.WantedBy = [ "default.target" ];
    Service = {
      ExecStart = "${pi-web}/bin/pi-web-sessiond";
      Environment = [
        "PI_WEB_DATA_DIR=${dataDir}"
      ];
      # No PATH override: inherit the manager PATH (50-systemd-path.conf) so the
      # embedded terminal gets ~/.nix-profile/bin (pi, node, git, coreutils...).
      Restart = "on-failure";
      RestartSec = 5;
    };
  };

  systemd.user.services.pi-web-web = {
    Unit = {
      Description = "pi-web web/API server";
      After = [ "pi-web-sessiond.service" ];
      Requires = [ "pi-web-sessiond.service" ];
    };
    Install.WantedBy = [ "default.target" ];
    Service = {
      ExecStart = "${pi-web}/bin/pi-web-server";
      Environment = [
        "PI_WEB_PORT=${toString port}"
        "PI_WEB_DATA_DIR=${dataDir}"
      ];
      Restart = "on-failure";
      RestartSec = 5;
    };
  };
}
let
  pkgs = import <nixpkgs> {};
  sources = (import ../../../../../npins) {input=../sources.json;};
  module = import ./default.nix {src = sources.pi-web;} {
    inherit pkgs;
    lib = import <home-manager/modules/lib/stdlib-extended.nix> pkgs.lib;
    config.home.homeDirectory = "/home/test";
  };
  cleanup = pkgs.writeText "disable-session-naming-test.sh"
    (pkgs.lib.replaceStrings [ "/home/test" ] [ "$TMPDIR/home" ]
      module.home.activation.disablePiWebSessionNaming.data);
  cleanedSettings = pkgs.runCommand "clean-session-naming-settings" {} ''
    mkdir -p "$TMPDIR/home/.pi/agent"
    cat > "$TMPDIR/home/.pi/agent/settings.json" <<'JSON'
    {"packages":["/nix/store/old/lib/node_modules/pi-web/dist/pi-packages/session-naming","npm:@jmfederico/pi-session-naming@1",{"source":"npm:@jmfederico/pi-session-naming"},"npm:keep",{"source":"npm:keep-object"}],"keep":true}
    JSON
    run() { "$@"; }
    source ${cleanup}
    source ${cleanup}
    cp "$TMPDIR/home/.pi/agent/settings.json" "$out"
  '';
in pkgs.lib.debug.throwTestFailures { failures = pkgs.lib.runTests {
  test-remove-installed-session-naming = {
    expr = builtins.fromJSON (builtins.readFile cleanedSettings);
    expected = { packages = [ "npm:keep" { source = "npm:keep-object"; } ]; keep = true; };
  };
  test-session-naming-dismissed = {
    expr = map (entry: entry.packageId) (builtins.fromJSON
      module.home.file.".local/state/pi-web/pi-package-dismissals.json".text).dismissals;
    expected = [ "@jmfederico/pi-session-naming" "@jmfederico/pi-relay" "@jmfederico/pi-web-workflows" ];
  };
}; }
{ src }:
# Pi updates independently of the main Nixpkgs pin.
import src {
  overlays = [ (_: prev: {
    pi-coding-agent = prev.pi-coding-agent.overrideAttrs (old: {
      # Share gateway error classification between the native CLI and SDK retry paths.
      patches = (old.patches or [ ]) ++ [ ./native-retry/main.patch ];
    });
  }) ];
}
{ ai, ... }: {
  imports = [
    (import ./models-dev-to-custom-provider ai.jw2-openai)
    (import ./models-dev-to-custom-provider ai.jw2-kimi)
    (import ./models-dev-to-custom-provider ai.moonshot-cn)
    # allrouter.cc rejects Pi's session_id header (HTTP 400); keep x-client-request-id.
    {yq-merge.".pi/agent/models.json".expr.providers.acc-openai.compat.sessionAffinityFormat = "openai-nosession";}
    (import ./models-dev-to-custom-provider ai.acc-gpt)

    # jw-deepseek proxy rejects 'developer' role (only accepts system/user/assistant/tool).
    # Setting supportsDeveloperRole=false makes pi send the system prompt as 'system' instead.
    {yq-merge.".pi/agent/models.json".expr.providers.jw2-deepseek.compat.supportsDeveloperRole = false;}
    (import ./models-dev-to-custom-provider ai.jw2-deepseek)
  ];
  yq-merge.".pi/agent/auth.json" = {
    generator = builtins.toJSON;
    expr = {
      deepseek = {type="api_key"; key=ai.deepseek.api_key;};
    };
  };
  home.file = {
    ".pi/agent/extensions/jw2-sub2api-pi-codex".source =
      if builtins.pathExists ~/Gist/Vault/AI/jw2/sub2api-pi-codex then
        ~/Gist/Vault/AI/jw2/sub2api-pi-codex
      else null;
  };
}
provider: let
  apiByNpm = {
    "@ai-sdk/openai" = "openai-responses";
    "@ai-sdk/openai-compatible" = "openai-completions";
  };
in {
  yq-merge.".pi/agent/models.json" = {
    generator = builtins.toJSON;
    expr.providers.${provider.id} = {
      baseUrl = provider.api;
      api = apiByNpm.${provider.npm};
      apiKey = provider.api_key;
      models = map (model: {
        inherit (model) id name reasoning;
        input = ["text"] ++ (if builtins.elem "image" model.modalities.input then ["image"] else []);
        cost = {
          inherit (model.cost) input output;
          cacheRead = model.cost.cache_read or 0;
          cacheWrite = model.cost.cache_write or 0;
        };
        contextWindow = model.workingContext;
        maxTokens = model.limit.output;
      }) (builtins.filter (model: (model.type or "chat") == "chat") (builtins.attrValues provider.models));
    };
  };
}
let
  lib = (import <nixpkgs> {}).lib;
  model = {
    id = "test-model";
    name = "Test Model";
    reasoning = true;
    modalities = { input = [ "text" "image" "video" ]; output = [ "text" ]; };
    cost = { input = 1; output = 2; cache_read = 0.1; cache_write = 0.2; };
    limit = { context = 100000; output = 10000; };
    workingContext = 33333;
  };
  convert = npm: models: (import ./. {
    id = "test-provider";
    api = "https://example.invalid/v1";
    api_key = "test-key";
    inherit npm models;
  }).yq-merge.".pi/agent/models.json".expr.providers.test-provider;
in lib.debug.throwTestFailures { failures = lib.runTests {
  test-openai-protocol = {
    expr = (convert "@ai-sdk/openai" { inherit model; }).api;
    expected = "openai-responses";
  };
  test-openai-compatible-protocol = {
    expr = (convert "@ai-sdk/openai-compatible" { inherit model; }).api;
    expected = "openai-completions";
  };
  test-model-metadata = {
    expr = (convert "@ai-sdk/openai" { inherit model; }).models;
    expected = [{
      id = "test-model";
      name = "Test Model";
      reasoning = true;
      input = [ "text" "image" ];
      cost = { input = 1; output = 2; cacheRead = 0.1; cacheWrite = 0.2; };
      contextWindow = 33333;
      maxTokens = 10000;
    }];
  };
  test-optional-cache-pricing = {
    expr = (builtins.head (convert "@ai-sdk/openai-compatible" {
      model = model // { cost = { input = 1; output = 2; }; };
    }).models).cost;
    expected = { input = 1; output = 2; cacheRead = 0; cacheWrite = 0; };
  };
  test-attachment-is-not-vision = {
    expr = let
      converted = builtins.head (convert "@ai-sdk/openai-compatible" {
        model = model // {
          reasoning = false;
          attachment = true;
          modalities = { input = [ "text" "pdf" ]; output = [ "text" ]; };
        };
      }).models;
    in { inherit (converted) reasoning input; };
    expected = { reasoning = false; input = [ "text" ]; };
  };
  test-exclude-specialized-models = {
    expr = map (m: m.id) (convert "@ai-sdk/openai" {
      inherit model;
      embedding = { type = "embedding"; };
      image = { type = "image"; };
      realtime = { type = "realtime"; };
    }).models;
    expected = [ "test-model" ];
  };
}; }
{ config, lib, pkgs, isNixOnDroid, ... }: {
  home.packages = [
    pkgs.sshfs
  ];
  programs.ssh.enable = true;
  programs.ssh.includes = lib.optional (
    builtins.pathExists ~/Gist/Config/ssh.conf
    # SSH need ssh.conf are only writable for current user, while nix-on-droid cannot change the system folder's permissions.
    # So I disable inluding ssh.conf in nix-on-droid
    && !isNixOnDroid
  ) "~/Gist/Config/ssh.conf";
  # For compatibility
  programs.ssh.enableDefaultConfig = false;
  programs.ssh.settings = {
    "*" = {
      ForwardAgent = false;
      AddKeysToAgent = "no";
      Compression = false;
      ServerAliveInterval = 0;
      ServerAliveCountMax = 3;
      HashKnownHosts = false;
      UserKnownHostsFile = "~/.ssh/known_hosts";
      ControlMaster = "no";
      ControlPath = "~/.ssh/master-%r@%n:%p";
      ControlPersist = "no";
    };
    # https://docs.github.com/zh/authentication/troubleshooting-ssh/using-ssh-over-the-https-port
    "github.com" = {
      HostName = "ssh.github.com";
      Port = 443;
      User = "git";
      ProxyCommand = "nc -X connect -x 127.0.0.1:${toString config.proxyPort} %h %p";
    };
    "aliyun" = {
      HostName = lib.trim (builtins.readFile ~/Gist/Vault/server/ip.txt);
      User = "root";
      ServerAliveInterval = 60;
    };
  };
  programs.zsh.initContent = lib.optionalString isNixOnDroid ''
    # start sshd
    if [[ -z "$(pidof sshd-start)" ]]; then
        tmux new -d -s sshd-start sshd-start
    fi
  '';
}
{ ... }: {
  programs.starship = {
    enable = true;
    settings = {
      directory = {
        truncation_length = 0;
        truncate_to_repo = false;
      };
      custom.fhs = {
        when = "test -e /nix-support/is-fhsenv";
        format = "[󱄅FHS]($style) ";
        style = "bold yellow";
      };
    };
  };
}
{ config, ... }: {
  services.syncthing.enable = true;
  # TODO: configure devices and folders
  services.syncthing.overrideDevices = false;
  services.syncthing.overrideFolders = false;
  # 通过 tailscale 访问 GUI,禁用 localhost host check。
  services.syncthing.settings.gui.insecureSkipHostcheck = true;
  # 启用代理,因为有些syncthing的服务器似乎是被墙了的。
  systemd.user.services.syncthing.Service.Environment = [
    # https://docs.syncthing.net/users/proxying.html
    # "http_proxy=http://127.0.0.1:${toString config.proxyPort}"
  ];
}
# VPS firewall/security-group ports for the official Tailscale instance:
# - UDP 41641: normal Tailscale peer-to-peer/direct traffic (--port below).
# - UDP 40000: peer relay traffic (--relay-server-port set after startup).
{ ... }: {
  imports = [
    ./module
    ./ssh.nix
  ];

  my.tailscale.instances.official = {
    httpPort = 1056;
    socks5Port = 1066;
    relayServerPort = 40000;
  };
}
{ ... }: {
  imports = [
    ./instances.nix
    ./devices.nix
  ];
}
{ lib, ... }: {
  options.my.tailscale.devices = lib.mkOption {
    type = lib.types.attrsOf ( lib.types.submodule { options = {
      user = lib.mkOption {
        type = lib.types.str;
      };
      ip = lib.mkOption {
        type = lib.types.str;
      };
    };});
    readOnly = true;
    default = {
      yoga = {
        user = "xieby1";
        ip = "100.70.248.78";
      };
      techrevo = {
        user = "xieby1";
        ip = "100.70.252.78";
      };
      dell = {
        user = "xieby1";
        ip = "100.83.73.38";
      };
      aliyun = {
        user = "root";
        ip = "100.99.83.68";
      };
    };
  };
}
{ config, pkgs, lib, isNixOnDroid, ... }:
let
  cfg = config.my.tailscale.instances;

  mkInstance = suffix: instance:
    let
      stateDir = "${config.home.homeDirectory}/.local/share/tailscale-${suffix}";
      relayServerPort = toString instance.relayServerPort;
      tailscale-wrapped = pkgs.writeShellScriptBin "tailscale-${suffix}" ''
        ${pkgs.tailscale}/bin/tailscale --socket /tmp/tailscale-${suffix}.sock $@
      '';
      tailscaled-wrapped = pkgs.writeShellScriptBin "tailscaled-${suffix}" ''
        TS_LOGS_DIR="${stateDir}" \
          ${pkgs.tailscale}/bin/tailscaled \
          --port=41641 \
          --tun userspace-networking \
          --outbound-http-proxy-listen=localhost:${toString instance.httpPort} \
          --socks5-server=localhost:${toString instance.socks5Port} \
          --socket=/tmp/tailscale-${suffix}.sock \
          --state=${stateDir}/tailscaled.state \
          --statedir=${stateDir} \
          $@
      '';
      setRelayServerPort = pkgs.writeShellScript "tailscale-${suffix}-set-relay-server-port" ''
        i=0
        while [ "$i" -lt 20 ]; do
          if ${tailscale-wrapped}/bin/tailscale-${suffix} set --relay-server-port=${relayServerPort}; then
            exit 0
          fi
          i=$((i + 1))
          ${pkgs.coreutils}/bin/sleep 0.5
        done
        exit 1
      '';
    in {
      packages = [
        tailscale-wrapped
        tailscaled-wrapped
      ];
      service = {
        Unit = {
          Description = "Auto start tailscaled-${suffix} userspace network";
          After = ["clash.service"];
        };
        Install = {
          WantedBy = ["default.target"];
        };
        Service = {
          Environment = [
            "HTTPS_PROXY=http://127.0.0.1:${toString config.proxyPort}"
            "HTTP_PROXY=http://127.0.0.1:${toString config.proxyPort}"
            "https_proxy=http://127.0.0.1:${toString config.proxyPort}"
            "http_proxy=http://127.0.0.1:${toString config.proxyPort}"
          ];
          ExecStart = "${tailscaled-wrapped}/bin/tailscaled-${suffix}";
          # The relay server port is a tailscale preference, not a tailscaled flag.
          # ExecStartPost can race the daemon socket on startup, so retry briefly.
          ExecStartPost = "${setRelayServerPort}";
        };
      };
      zshInit = ''
        compdef _tailscale tailscale-${suffix}
      '' + lib.optionalString isNixOnDroid ''
        # start tailscale-${suffix}
        if [[ -z "$(pidof tailscaled-${suffix})" ]]; then
            tmux new -d -s tailscaled-${suffix} tailscaled-${suffix}
        fi
      '';
    };

  instanceNames = lib.attrNames cfg;
  instances = map (name: {
    inherit name;
    value = mkInstance name cfg.${name};
  }) instanceNames;
in {
  options.my.tailscale.instances = lib.mkOption {
    type = lib.types.attrsOf (lib.types.submodule {
      options = {
        httpPort = lib.mkOption {
          type = lib.types.port;
          default = 1056;
        };
        socks5Port = lib.mkOption {
          type = lib.types.port;
          default = 1066;
        };
        relayServerPort = lib.mkOption {
          type = lib.types.port;
          default = 40000;
        };
      };
    });
    default = {};
  };

  config = {
    home.packages = lib.mkIf (instanceNames != []) (
      [ pkgs.tailscale ] ++ lib.concatMap (instance: instance.value.packages) instances
    );

    systemd.user.services = lib.mkMerge (map (instance: {
      "tailscaled-${instance.name}" = instance.value.service;
    }) instances);

    programs.zsh.initContent = lib.concatStringsSep "" (map (instance: instance.value.zshInit) instances);
  };
}
{ config, lib, pkgs, ... }:
let
  # tailscaled-official runs in userspace networking mode. Its HTTP CONNECT
  # proxy reaches remote tailnet peers, but CONNECT to this node's own 100.x IP
  # hangs instead of hairpinning back to the host network stack where local sshd
  # listens. Check the runtime Tailscale IPs and use 127.0.0.1 for self; keep
  # HTTP CONNECT for real remote peers.
  #
  # Do not detect self by comparing `tso.<name>` with `/etc/hostname`: Tailscale
  # aliases can intentionally differ from machine hostnames.
  tailscaleOfficialSshProxy = pkgs.writeShellScriptBin "tailscale-official-ssh-proxy" ''
    set -u

    host="$1"
    port="$2"
    self_ips="$(${pkgs.coreutils}/bin/timeout 2s ${pkgs.tailscale}/bin/tailscale --socket /tmp/tailscale-official.sock ip -4 2>/dev/null || true)"

    for ip in $self_ips; do
      if [ "$host" = "$ip" ]; then
        exec ${pkgs.netcat}/bin/nc 127.0.0.1 "$port"
      fi
    done

    exec ${pkgs.netcat}/bin/nc -X connect -x 127.0.0.1:${toString config.my.tailscale.instances.official.httpPort} "$host" "$port"
  '';
in {
  home.packages = [
    tailscaleOfficialSshProxy
  ];

  programs.ssh.settings = lib.mapAttrs' (name: value: lib.nameValuePair
    "tso.${name}" {
      HostName = value.ip;
      User = value.user;
      ServerAliveInterval = 60;
      ProxyCommand = "${tailscaleOfficialSshProxy}/bin/tailscale-official-ssh-proxy %h %p";
    }
  ) config.my.tailscale.devices;
}
{ pkgs, ... }: {
  home.shell.enableZshIntegration = true;
  programs.zsh = {
    enable = true;
    enableVteIntegration = true;
    autosuggestion.enable = true;
    syntaxHighlighting.enable = true;
    plugins = [
      {
        name = "zsh-completion-sync";
        src = pkgs.zsh-completion-sync;
        file = "share/zsh-completion-sync/zsh-completion-sync.plugin.zsh";
      }
    ];
    # zsh startup split:
    # - envExtra -> .zshenv: every zsh, including ssh 'cmd'; keep tiny, quiet, and reliable.
    # - initContent -> .zshrc: interactive shells; keybindings, completion, aliases, prompts, and autostart.
    envExtra = ''
      # Avoid duplicate NixOS global zsh init (/etc/zshrc); Home Manager config is enough.
      setopt no_global_rcs

      # SSH forwards TERM but not COLORTERM/KITTY_WINDOW_ID, so truecolor-aware
      # tools (pi, nvim, ls, ...) fall back to 256-color on remote hosts. Re-derive
      # COLORTERM from TERM, which does survive the SSH hop (kitty is always truecolor).
      [[ $TERM == *kitty* ]] && export COLORTERM=truecolor
    '';
    completionInit = ''
      # Load the zsh/complist module, which provides colored completion listings,
      # scrolling through long lists, and an alternative menu selection style.
      # According to zshall(1), this should be done before compinit so that the
      # menu-select widget is properly re-defined by the completion system.
      zmodload zsh/complist

      # Initialize the programmable completion system (compinit).
      # This re-defines all completion widgets to use the smart, context-aware system.
      autoload -U compinit && compinit

      # Configure completion colors via the list-colors style.
      # When using compinit, ZLS_COLORS should not be set directly because the
      # completion system controls colors itself. Instead, we use zstyle with the
      # same colon-separated format as GNU ls. The (s.:.) flag splits LS_COLORS
      # by colons so each name=value pair is passed as a separate argument.
      zstyle ':completion:*:default' list-colors ''${(s.:.)LS_COLORS}

      # Show normal listings and enter interactive menu selection
      zstyle ':completion:*' menu select=1
      # Shift-Tab for reverse cycling
      bindkey -M menuselect "$terminfo[kcbt]" reverse-menu-complete
    '';
    initContent = ''
      # Ghostty sends CSI Home/End in normal keypad mode; terminfo supplies SS3 forms.
      bindkey -M viins "$terminfo[khome]" beginning-of-line
      bindkey -M viins "$terminfo[kend]" end-of-line
      bindkey -M viins "^[[H" beginning-of-line
      bindkey -M viins "^[[F" end-of-line

      # Ctrl+arrows use vi small-word motions, stopping at punctuation.
      bindkey -M viins  "^[[1;5C" vi-forward-word
      bindkey -M viins  "^[[1;5D" vi-backward-word
      bindkey -M visual "^[[1;5C" vi-forward-word
      bindkey -M visual "^[[1;5D" vi-backward-word
      bindkey -M vicmd  "^[[1;5C" vi-forward-word
      bindkey -M vicmd  "^[[1;5D" vi-backward-word
      bindkey -M viopp  "^[[1;5C" vi-forward-word
      bindkey -M viopp  "^[[1;5D" vi-backward-word

      # Other ZLE word widgets still use WORDCHARS; vi motions do not.
      WORDCHARS=_

      # source my zshrc
      if [[ -f ~/Gist/Config/zshrc ]]; then
        source ~/Gist/Config/zshrc
      fi
    '';
  };
}
{
  enableExtendedCLI,
  enableServer,
}: # local args
{ lib, ... }: {
  imports = [
    (lib.modules.importApply ./basic { inherit enableExtendedCLI; })
  ] ++ lib.optional enableExtendedCLI ./extended
    ++ lib.optional enableServer ./server
  ;
}
{ pkgs, ... }:
let
  sysconfig = (
    # <...> are expression search in NIX_PATH
    if (builtins.tryEval <nixos-config>).success
    then import <nixpkgs/nixos> {}
    else import <nixpkgs/nixos> {configuration={};}
  ).config;
in
{
  imports = [
    ./tmux.nix
    ./gdb.nix
    ./fzf.nix
    ./tldr.nix
    ./zellij.nix

    ./extra.nix
  ] ++ [{ # functions & attrs
    home.packages = [pkgs.nix-index];
    home.file.nix_index_database = {
      source = builtins.fetchurl "https://github.com/Mic92/nix-index-database/releases/latest/download/index-${builtins.currentSystem}";
      target = ".cache/nix-index/files";
    };
  }{
    home.packages = with pkgs; [
      cachix
    ];
    home.file.cachix_dhall = {
      source = if (builtins.pathExists ~/Gist/Config/cachix.dhall)
        then ~/Gist/Config/cachix.dhall
        else builtins.toFile "empty-cachix.dhall" "";
      target = ".config/cachix/cachix.dhall";
    };
  }];

  home.packages = with pkgs; [
    # tools
    parallel
    comma
    python3Packages.qrcode
    ## archive
    unar
    ## manage
    (import (import <npins> {input=../server/sources.json;}).circle {inherit pkgs;})
    # htop search in intuitive
    btop
    witr
    nix-tree
    ## text
    pandoc
    poppler-utils # pdftotext
    pdfgrep
    yq-go
    clipboard-jh
    ## compile
    gnumake
    makefile2graph
    remake
    ## draw
    graphviz
    ## - Pros
    ##   - GitHub native support. (GitHub does not support d2, graphviz, etc)
    ## - Cons
    ##   - Not modular (no naming space, all naming are flat!)
    ##   - Cannot control the flowchart rank by edge.
    ##     e.g. a <-- b is same as b --> a. Thus, the layout is fragile.
    mermaid-cli
    figlet
    nyancat
    d2
    ## file system
    file
    # magika # detect file content types with deep learning
    tree
    ## network
    wget
    axel
    bind.dnsutils # nslookup
    netcat
    nload
    nmap
    nethogs
    browser-sync
    ## x11
    xdotool

    # programming
    inotify-tools
    clang-tools
    cmake
    capstone
    scc
    ## https://stackoverflow.com/questions/40165650/how-to-list-all-files-tracked-by-git-excluding-submodules
    (writeShellScriptBin "scc-git" "${scc}/bin/scc $(git grep --cached -l '')")
    ## python
    ( python3.withPackages ( p: with p; [
      ipython
      pydot
      networkx
    ]))
    ## c
    (lib.setPrio # make bintools less prior
      (bintools-unwrapped.meta.priority + 1)
      bintools-unwrapped
    )
    (if builtins.currentSystem == "x86_64-linux"
      then gcc_multi
      else gcc
    )
    ### docs
    stdmanpages
    man-pages
    #gccStdenv
    bear
    ## xml
    libxml2
    ## bash
    bc
    ## nix
    nixos-option
    nix-output-monitor
    ### allow non-nixos access `man configuration.nix`
    # see: nixos/modules/misc/documentation.nix
    #        nixos/doc/manual/default.nix
    sysconfig.system.build.manual.nixos-configuration-reference-manpage
    nurl
    npins
  ];

  programs.eza.enable = true;
  home.shellAliases.ls = "eza";

  home.sessionVariables = {
    NIXPKGS_ALLOW_INSECURE = "1";
    # 解决tmux在nix-on-droid上不显示emoji和中文的问题
    LANG = "C.UTF-8";
  };

  # bash
  programs.bash.enable = true;

  programs.direnv = {
    enable = true;
    nix-direnv = {
      enable = true;
    };
  };

  programs.ripgrep = {
    enable = true;
    arguments = [
      "--no-ignore-vcs"
    ];
  };

  programs.command-not-found = {
    enable = true;
    # NixOS channels generate programs.sqlite; nixpkgs-unstable does not.
    # Keep the npins Nixpkgs pin on nixos-unstable for this database.
    dbPath = "${pkgs.npinsed.nixpkgs.outPath}/programs.sqlite";
  };

  programs.bat.enable = true;
  home.shellAliases.cat = "bat -pp";

  # ~/.config/npins/nixpkgs, home-manager, and nix-on-droid are defined in bootstrap/main.sh,
  # because <nixpkgs>, <home-manager>, and <nix-on-droid> are needed to bootstrap
  # nixos-rebuild, home-manager, and nix-on-droid.
  # However,nur are not needed during bootstrap, so they are defined here.
  home.file.nur = {
    target = ".config/npins/nur";
    source = pkgs.npinsed.nur;
  };
}

cli-extra.nix: Extra CLI configs (added to minimal cli config)

{ config, pkgs, stdenv, lib, ... }: {
  imports = [{
    home.packages = [
      pkgs.act
      (pkgs.writeShellScriptBin "act-podman" ''
        export DOCKER_HOST=unix://$XDG_RUNTIME_DIR/podman/podman.sock
        CMD=(
          "${pkgs.act}/bin/act"
          "--bind"

          # use podman
          "--container-daemon-socket" "unix://$XDG_RUNTIME_DIR/podman/podman.sock"

          # use host proxy
          "--container-options" "--network=host"
          "--env" "HTTPS_PROXY='http://127.0.0.1:${toString config.proxyPort}'"
          "--env" "HTTP_PROXY='http://127.0.0.1:${toString config.proxyPort}'"
          "--env" "FTP_PROXY='http://127.0.0.1:${toString config.proxyPort}'"
          "--env" "https_proxy='http://127.0.0.1:${toString config.proxyPort}'"
          "--env" "http_proxy='http://127.0.0.1:${toString config.proxyPort}'"
          "--env" "ftp_proxy='http://127.0.0.1:${toString config.proxyPort}'"

          "$@"
        )
        eval "''${CMD[@]}"
      '')
    ];
  }];

  home.packages = with pkgs; [
    ### pdfcrop
    (texliveMinimal.withPackages (p: [p.pdfcrop]))
    # runXonY
    qemu
  ];

  services.podman.enable = true;
}
{ pkgs, ... }: let
  go-there = pkgs.writeScriptBin "go-there" /*bash*/ ''
    dir=$(dirname "$1")
    cd "$dir" || exit
    bash -i
  '';
  fzf-doc = pkgs.writeScriptBin "fzf-doc" /*bash*/ ''
    allCmds() {
      # bash alias
      compgen -A alias

      # external commands
      # https://unix.stackexchange.com/questions/94775/list-all-commands-that-a-shell-knows
      case "$PATH" in
        (*[!:]:) PATH="$PATH:" ;;
      esac
      set -f
      IFS_OLD="$IFS"
      IFS=:
      for dir in $PATH; do
        set +f
        [ -z "$dir" ] && dir="."
        for file in "$dir"/*; do
          if [ -x "$file" ] && ! [ -d "$file" ]; then
            echo "''${file##*/}"
          fi
        done
      done
      IFS="$IFS_OLD"
    }

    cd ~/Docs
    FILE=$(fzf)
    [ -z "$FILE" ] && exit
    cd $(dirname "$FILE")
    FILE=$(basename "$FILE")

    # move o and go-there to top
    { echo o; echo go-there; allCmds | grep -vw o | grep -vw go-there; } | fzf \
      --bind     "enter:execute(      bash -ic '{} \"$FILE\"'               )+accept" \
      --bind "alt-enter:execute(nohup bash -ic '{} \"$FILE\"' &> /dev/null &)+accept"
  '';
in {
  home.packages = [
    go-there
    fzf-doc
  ];
  # * hstr: not handle `~` correctly, always expand
  # * atuin: often not record my command, do know why
  #   * besides, the network sync is redundant for me
  # * mcfly: the fuzzy ranking algorithm is not as good/intuitive as fzf
  programs.fzf = {
    enable = true;
    defaultOptions = [
      "--reverse"
    ];
  };
}

GDB configurations

{ pkgs, ... }: {
  home.packages = [
    pkgs.gdb
  ];
  home.file.gdbinit = {
    source = pkgs.fetchFromGitHub {
      owner = "cyrus-and";
      repo = "gdb-dashboard";
      rev = "616ed5100d3588bb70e3b86737ac0609ce0635cc";
      hash = "sha256-xoBkAFwkbaAsvgPwGwe1JxE1C8gPR6GP1iXeNKK5Z70=";
    } + /.gdbinit;
    target = ".gdbinit";
  };
  home.file.gdb_dashboard_init = {
    text = ''
      # gdb-dashboard init file

      # available layout modules
      #   stack registers history assembly
      #   breakpoints expressions memory
      #   source threads variables
      dashboard -layout source

      # https://en.wikipedia.org/wiki/ANSI_escape_code
      #dashboard -style prompt
      ## fg bold blue
      dashboard -style prompt_not_running "\\[\\e[1;34m\\]$\\[\\e[0m\\]"
      ## fg bold green
      dashboard -style prompt_running "\\[\\e[1;32m\\]$\\[\\e[0m\\]"
    '';
    target = ".gdbinit.d/init";
  };
}
{ pkgs, ... }: {
  home.packages = [
    pkgs.tlrc
  ];
  home.file.tlrc_config = {
    target = ".config/tlrc/config.toml";
    text = pkgs.lib.generators.toINI {} {
      cache = {
        dir = ''"~/.cache/tlrc"''; # this is the default dir
        auto_update = false;
      };
    };
  };
  home.file.tldr_cache = {
    target = ".cache/tlrc";
    source = builtins.fetchTarball "https://github.com/tldr-pages/tldr/archive/main.tar.gz";
  };
}

tmux

{ config, pkgs, stdenv, lib, ... }: {
  home.packages = [pkgs.tmux];

bash config for tmux

Auto start tmux in non-GUI device. mkAfter ensure the tmux config is appended to the tail of .bashrc.

  # programs.zsh.initContent = lib.mkAfter ''
  #   # Auto start tmux
  #   # see: https://unix.stackexchange.com/questions/43601/how-can-i-set-my-default-shell-to-start-up-tmux
  #   # ~~1. tmux exists on the system~~, nix ensure that tmux does exist
  #   # 2. we're in an interactive shell, and
  #   # 3. tmux doesn't try to run within itself
  #   if [ -z "$DISPLAY" ] && [ -n "$PS1" ] && [[ ! "$TERM" =~ screen ]] && [[ ! "$TERM" =~ tmux ]] && [ -z "$TMUX" ]; then
  #     exec tmux
  #   fi
  # '';

tmux config file

  home.file.tmux = {
    text = ''
      # display status at top
      set -g status-position top
      set -g status-right ""

      # status bar
      ## display title on terminal
      set -g set-titles on
      set -g window-status-format "#F#I #W #{=/-20/…:pane_title}"
      set -g window-status-current-format "🐶#F#I #W #{=/-20/…:pane_title}"
      ## hide status bar when only one window
      ### refer to
      ### https://www.reddit.com/r/tmux/comments/6lwb07/is_it_possible_to_hide_the_status_bar_in_only_a/
      ### It not good, since its global!
      # if -F "#{==:#{session_windows},1}" "set -g status off" "set -g status on"
      # set-hook -g window-linked 'if -F "#{==:#{session_windows},1}" "set -g status off" "set -g status on"'
      # set-hook -g window-unlinked 'if -F "#{==:#{session_windows},1}" "set -g status off" "set -g status on"'
      ## color
      ### colour256的前10个和终端(gnome-terminal tango)的配色一致
      set -g status-style "bg=white fg=black"
      set -g window-status-last-style "bg=white fg=green bold"
      set -g window-status-current-style "bg=black fg=green bold"
      set -g window-status-separator " ┇"

      # Fix tmux color
      # https://hmgle.github.io/terminal/tmux/color/2024/05/12/term-color.html
      set -g default-terminal "xterm-256color"
      set -as terminal-features ",xterm*:RGB"

      # enable mouse scroll
      set -g mouse on

      # window index start from 1
      set -g base-index 1
      setw -g pane-base-index 1

      # auto re-number
      set -g renumber-windows on

      # Set new panes to open in current directory
      bind c new-window -c "#{pane_current_path}"
      bind '"' split-window -c "#{pane_current_path}"
      bind % split-window -h -c "#{pane_current_path}"

      # alt-num select window
      bind-key -n M-1 select-window -t 1
      bind-key -n M-2 select-window -t 2
      bind-key -n M-3 select-window -t 3
      bind-key -n M-4 select-window -t 4
      bind-key -n M-5 select-window -t 5
      bind-key -n M-6 select-window -t 6
      bind-key -n M-7 select-window -t 7
      bind-key -n M-8 select-window -t 8
      bind-key -n M-9 select-window -t 9
      # ctrl-t new window
      bind-key -n C-t new-window -c "#{pane_current_path}"

      # vi key bindings
      set -g mode-keys vi
      set -g status-keys vi

      # Home, End key not work in nix-on-droid
      # https://stackoverflow.com/questions/18600188/home-end-keys-do-not-work-in-tmux
      bind-key -n Home send Escape "OH"
      bind-key -n End send Escape "OF"

      set -g allow-passthrough on
    '';
    target = ".tmux.conf";
  };
}
# Pros:
# Cons:
# - does not support kitty image protocol.
# - does not auto naming tab
# - 1k+ open issues on github
{ ... }: {
  programs.zellij = {
    enable = true;
    layouts.simple.layout._children = [{
      pane = {
        _props = {
          size = 1;
          borderless = true;
        };
        plugin = {
          location = "tab-bar";
        };
      };
    }{
      pane = {};
    }];
    settings = {
      theme = "everforest-dark";
      show_startup_tips = false;
      pane_frames = false;
      simplified_ui = true;
      default_layout = "simple";
      # ui = {
      #   pane_frames = {
      #     hide_session_name = true;
      #   };
      # };
      keybinds = {
        normal._children = [
          {bind = {_args=["Ctrl Shift t"]; NewTab={};};}
          {bind = {_args=["Ctrl Shift Left"]; GoToPreviousTab={};};}
          {bind = {_args=["Ctrl Shift Right"]; GoToNextTab={};};}
        ];
      };
    };
  };
}

binutils's ld and gcc's ld collsion

Background: I want to install gcc and objdump, where objdump is contained in binutils. Home-manager tolds me gcc's ld collides with binutils's ld. As I explore into gcc and binutils, weird thing comes.

Packages binutils and gcc both contain ld executable. binutils and gcc has the same priority 10.

The WEIRD thing is,

  • binutils wants to have a lower priority than gcc-wrapper, so sets its priority to 10, see nixpkgs: pkgs/development/tools/misc/binutils/default.nix

    Give binutils a lower priority than gcc-wrapper to prevent a collision due to the ld/as wrappers/symlinks in the latter.

  • Both gcc wrapper and all-packages set gcc priority to 10, see nixpkgs: pkgs/top-level/all-packages.nix and pkgs/build-support/cc-wrapper/default.nix All-packages set priority by lowPrio function, which will set priority to 10. Cc-wrapper directly set priority to 10.

As a result, binutils will definitely collide with gcc!

My solution: assign binutils a lower priority, like this

home.packages = with pkgs; [
  (lib.setPrio # higher value, less prior
    (bintools-unwrapped.meta.priority + 1)
    bintools-unwrapped
  )
  gdb
]

Nodejs packages (npm) in NixOS

NixOS中的Nodejs包(npm)

太长不看:手动暴露buildNodePackage,添加自定义的npm包。

nixpkgs中的node包虽多但有限, 遇到需要的node包不存在时,是个麻烦事。

让我觉得十分诡异的是, nixpkgs中存在一个十分方便的添加node包的函数nodeEnv.buildNodePackage, 但是这个函数却不暴露出来给用户。 甚至,有些nixpkgs中的包为了使用这个函数, 复制粘贴该函数到自己的包中。

在这些奇怪的事情的基础上, 还衍生出来自动生成该buildNodePackage函数软件node2nix。

所以这真的是存在即合理嘛? 还是我学艺不精,不能理解设计者的意图?

一个简单的暴露buildNodePackage的方法, 直接导入buildNodePackage所在的文件。 为了跨平台可用, 路径的构建采用了一点使用了点点小把戏,

<nixpkgs> + /pkgs/development/node-packages/node-env.nix

以@types/node为例子,nodepkgs.nix:

{ ... }:
let
  pkgs = import <nixpkgs> {};
  nodeEnv = import (<nixpkgs> + /pkgs/development/node-packages/node-env.nix) {
    inherit (pkgs) lib stdenv nodejs python2;
    inherit pkgs;
    inherit (pkgs) libtool runCommand writeTextFile writeShellScript;
  };
  globalBuildInputs = [];
in {
  "@types/node" = nodeEnv.buildNodePackage {
    name = "_at_types_slash_node";
    packageName = "@types/node";
    version = "18.7.15";
    src = pkgs.fetchurl {
      url = "https://registry.npmjs.org/@types/node/-/node-18.7.15.tgz";
      sha512 = "XnjpaI8Bgc3eBag2Aw4t2Uj/49lLBSStHWfqKvIuXD7FIrZyMLWp8KuAFHAqxMZYTF9l08N1ctUn9YNybZJVmQ==";
    };
    buildInputs = globalBuildInputs;
    meta = {
      description = "TypeScript definitions for Node.js";
      homepage = "https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/node";
      license = "MIT";
    };
    production = true;
    bypassCache = true;
    reconstructLock = true;
  };
}

该nodepkgs.nix文件为用户自定义的node包, 可以像nixpkgs一样使用这个文件,例如导入

myNodePkgs = import ./cli/nodepkgs.nix {}

包的表达式为myNodePkgs."@types/node"。

Python in Nix/NixOS

2023.05.03
ProjectMaintainedDescriptionPurityCompatibility
venv❌100%?
mach-nix✅
pypi2nix❌
pip2nix✅✅
buildPythonPackage✅✅
[TODO] poetry
[TODO] dream2nix

pip2nix

Noted: Latest version of pip2nix only use python39. While nixpkgs 22.11 (current stable) is python310. I dont to install multiple versions of python3.

If pip2nix can overcome the disadvantage of that generate a long list of python packages, and reuse python3Packages in nixpkgs, I would prefer to use pip2nix completely.

Currently, I use buildPythonPackage.

buildPythonPackage

pkgs.python3Packages.buildPythonPackage

venv

Use virtualenv, pip is available, no need to write nix expressions to install packages.

Code see https://xieby1.github.io/scripts/index.html#venvnix

poetry

2022.05.15

According to What is the correct way to setup pip with nix to install any python package in an isolated nix environment, I found two useful tools to install python packages in Nix/NixOS

  • [TODO] poetry
  • mach-nix

mach-nix

mach-nix github repo: github.com/DavHau/mach-nix

Here is [python_mach.nix]({{ site.repo_url }}/scripts/shell/python_mach.nix), an example which create a shell with a python package called expmcc.

{ config, pkgs, lib, ... }:
let
  cfg = config.my.server.caddyAuthelia;
  yaml = pkgs.formats.yaml { };
  guestGroups = import ../guest-groups.nix { inherit lib; };
  # Same prefix Caddy serves cgit under; Authelia's regexes are case-sensitive.
  cgitConsts = import ../caddy/cgit/consts.nix;
  registry = import ~/Gist/Vault/server/users.nix { inherit lib; };

  # The user database is generated from the vault registry, so its argon2 hashes
  # do land in /nix/store, which is world-readable. That trade-off and the
  # reasoning behind it are at the top of that file; do not add other secrets
  # there. authelia.env (session, storage-encryption, reset secrets) stays out,
  # as a string path: interpolating a path value (`"${~/…}"`) would copy the
  # whole directory into the store.
  vaultDir = toString ~/Gist/Vault/server;
  autheliaUsersFile = yaml.generate "authelia-users.yml" {
    # sshKeys is registry data for the ssh side; Authelia ignores unknown keys,
    # but the generated database should be the schema Authelia actually uses.
    users = builtins.mapAttrs (_: u: builtins.removeAttrs u [ "sshKeys" ]) registry;
  };

  # One rule per guest team, then the owner's rules. Authelia takes the first
  # matching rule, and a rule whose `subject` the user is not in does not
  # match, so a guest falls through to the default deny for anything outside
  # their team. Owner rules keep `subject = group:admins`, otherwise an
  # authenticated guest could reach /sixu, /web, the portal settings, …
  # A guest's group is the team name itself, derived from the user registry;
  # guest-groups.nix drops "admins" from that list, which would otherwise match
  # the owner rules below.
  accessRules = map (g: {
    domain = "xieby1.cn";
    resources = [ "^${cgitConsts.prefix}/${g.name}(/.*)?$" ];
    subject = [ "group:admins" "group:${g.name}" ];
    policy = "two_factor";
  }) guestGroups.teams ++ [
    {
      domain = "xieby1.cn";
      resources = [ "^/BTeam/XingYao(/.*)?$" ];
      subject = [ "group:BTeam" "group:admins" ];
      policy = "two_factor";
    }
    {
      domain = "xieby1.cn";
      resources = [ "^${cgitConsts.prefix}(/.*)?$" ];
      subject = [ "group:admins" ];
      policy = "two_factor";
    }
    {
      domain = "xieby1.cn";
      subject = [ "group:admins" ];
      policy = "two_factor";
    }
  ];

  autheliaConfig = yaml.generate "authelia-configuration.yml" {
    theme = "auto";

    server.address = "tcp://127.0.0.1:9091/";

    log.level = "info";

    totp.issuer = "xieby1.cn";

    authentication_backend.file.path = autheliaUsersFile;

    # No outgoing email exists on this host; the notifier is the filesystem and
    # the code lands in ~/.config/authelia/notification.txt, which a guest can
    # never read. So the "Forgot password?" flow could only ever produce a dead
    # end: the prompt says it mailed a one-time code, nothing arrives, and the
    # guest is stuck. Passwords are managed here instead (users.nix, step 1).
    authentication_backend.password_reset.disable = true;

    access_control = {
      default_policy = "deny";
      rules = accessRules;
    };

    session.cookies = [{
      domain = "xieby1.cn";
      authelia_url = "https://xieby1.cn";
      same_site = "lax";
      # You can leave it idle during a workday without re-login.
      inactivity = "1d";
      # Even with activity, normal sessions must re-authenticate weekly.
      expiration = "1M";
      # It does not mean “remember my username”. It means “keep me authenticated longer”.
      # The maximum session lifetime when the user checks “Remember me” at login.
      remember_me = "6M";
    }];

    storage.local.path = "${config.xdg.configHome}/authelia/db.sqlite3";

    # Authelia says it "sent" an identity-verification one-time code when
    # registering a TOTP device. With the filesystem notifier, read it from
    # ~/.config/authelia/notification.txt on this server.
    notifier.filesystem.filename = "${config.xdg.configHome}/authelia/notification.txt";
  };
in {
  config = lib.mkIf cfg.enable {
    home.packages = [ pkgs.authelia ];

    systemd.user.services.authelia = {
      Unit = {
        Description = "Authelia authentication portal";
        After = [ "network.target" ];
      };
      Install.WantedBy = [ "default.target" ];
      Service = {
        # Same string-not-path reason as autheliaUsersFile above.
        EnvironmentFile = "${vaultDir}/authelia.env";
        ExecStart = "${pkgs.authelia}/bin/authelia --config ${autheliaConfig}";
        Restart = "on-failure";
      };
    };
  };
}
# Caddy route fragment for cgit, included by ../default.nix.
#
# Serves <prefix>/… : browsing via cgit.cgi and smart clones via
# git-http-backend, both over FastCGI to the loopback fcgiwrap started in
# ./config.nix. cgit speaks plain CGI (env in, stdout out), which Caddy cannot
# run; the fcgiwrap hop is what lets Caddy serve it at all.
#
# Access control lives entirely in Authelia (see ../../authelia/default.nix):
# guests of a team are allowed only <prefix>/<team>/…, which is why the repo
# name must come from the path alone — hence the ?url= refusal below.
{ cgit, git, cgitrc, themeRoot, reposPath }:
let
  consts = import ./consts.nix;
  prefix = consts.prefix;
  upstream = "127.0.0.1:${toString consts.fcgiwrapPort}";
in ''
  redir ${prefix} ${prefix}/

  # Only the pinned stylesheet is copied into the served theme directory,
  # and this handler matches its exact path. A browser can cache it for an
  # hour; deployment changes its content only when the pinned source changes.
  @cgit_theme path ${prefix}${consts.themeFile}
  handle @cgit_theme {
    route {
      header Cache-Control "public, max-age=3600"
      uri strip_prefix ${prefix}
      root * ${themeRoot}
      file_server
    }
  }

  # cgit's static assets; the URLs come from css=/favicon=/… in cgitrc. No auth
  # here: they are plain files from the cgit package.
  @cgit_assets path ${prefix}/cgit.css ${prefix}/cgit.js ${prefix}/cgit.png ${prefix}/favicon.ico ${prefix}/robots.txt
  handle @cgit_assets {
    route {
      uri strip_prefix ${prefix}
      root * ${cgit}/cgit
      file_server
    }
  }

  handle ${prefix}/* {
    route {
      import auth

      # cgit takes the repo from ?url= in preference to PATH_INFO, so any
      # allowed path could render any repo (/Repos/BTeam/x/?url=/Other.git).
      # Authelia only sees the path, so refuse the parameter here. Applies to the
      # owner too; cgit emits no such links when virtual-root is set.
      # shortcut: blocklist of one parameter; re-check on cgit upgrades.
      @repo_override query url=*
      respond @repo_override 403

      uri strip_prefix ${prefix}

      # Clones and browsing share this route: only a regexp matches repos
      # nested at any depth (…/BTeam/x.git/info/refs), and Caddy sorts
      # regexp-only `handle` blocks after path ones, so a separate clone
      # handler would be shadowed by the browsing handler. Anchored on .git so
      # a cgit file view ending in info/refs (…/x.git/plain/info/refs) is not
      # mistaken for a clone; every repo here is a …​.git directory.
      @clone path_regexp \.git/(info/refs|git-upload-pack)$
      reverse_proxy @clone ${upstream} {
        transport fastcgi {
          env SCRIPT_FILENAME ${git}/libexec/git-core/git-http-backend
          env GIT_PROJECT_ROOT ${reposPath}
          env GIT_HTTP_EXPORT_ALL 1
          env PATH_INFO {http.request.uri.path}
        }
      }

      reverse_proxy ${upstream} {
        transport fastcgi {
          env SCRIPT_FILENAME ${cgit}/cgit/cgit.cgi
          env CGIT_CONFIG ${cgitrc}
          env SCRIPT_NAME ${prefix}
          env PATH_INFO {http.request.uri.path}
        }
      }
    }
  }
''
{ config, pkgs, lib, ... }:
let
  cfg = config.my.server.caddyAuthelia;
  consts = import ./consts.nix;

  cacheRoot = "${config.xdg.cacheHome}/${consts.cacheDir}";

  # The same patched cgit the web route serves, so running cgit.cgi by hand
  # shows the same numbers as the page.
  cgit = import ./package.nix { inherit pkgs; };
in {
  config = lib.mkIf cfg.enable {
    home.packages = [ cgit pkgs.fcgiwrap ];
    cachix_packages = [ cgit ];

    # cgit writes its page-cache files directly into cache-root but never
    # creates that directory, so it must exist before the first request.
    home.activation.cgitCacheDir = lib.hm.dag.entryAfter [ "writeBoundary" ] ''
      run mkdir -p $VERBOSE_ARG "${cacheRoot}"
    '';

    # cgit.cgi is plain CGI, which Caddy cannot run. fcgiwrap is the
    # FastCGI->CGI bridge: it stays up, accepts FastCGI from Caddy over
    # loopback and forks cgit.cgi (or git-http-backend) per request.
    # -c 4: one clone holds its slot for the whole transfer, and -c 1 would
    # queue everyone's browsing behind it.
    systemd.user.services.fcgiwrap-cgit = {
      Unit.Description = "fcgiwrap CGI bridge for cgit";
      Install.WantedBy = [ "default.target" ];
      Service = {
        ExecStart = "${pkgs.fcgiwrap}/bin/fcgiwrap -c 4 -s tcp:127.0.0.1:${toString consts.fcgiwrapPort}";
        Restart = "on-failure";
        RestartSec = 3;
      };
    };
  };
}
# Shared by the cgit Caddy route fragment (./caddy.nix) and the fcgiwrap
# service (./config.nix), which are generated from separate files but must
# agree. Keeping the port here stops the FastCGI upstream and the fcgiwrap
# listener from drifting apart.
{
  # Loopback port Caddy's fastcgi transport dials; fcgiwrap listens here.
  fcgiwrapPort = 9007;

  # URL prefix Caddy serves and strips before handing the request to cgit.
  # Capitalised to match ~/Repos; it ends up in Authelia regexes verbatim (they
  # are case-sensitive), so change it here only.
  prefix = "/Repos";

  # Served stylesheet path in the generated theme root. Referenced by the
  # cgitrc (../default.nix) and the Caddy route (./caddy.nix), so the name
  # lives here to keep them in step.
  themeFile = "/theme.css";

  # cgit's page cache lives at $XDG_CACHE_HOME/<cacheDir>.
  cacheDir = "cgit";
}
# The cgit this tree serves and installs.
#
# The repolist "Idle" column stats refs/heads/<defbranch> and hardcodes
# "master" as the default; repos found by scan-path never get a defbranch, so a
# repo whose HEAD is main was reported as idle since the last gc (the
# packed-refs mtime) however recently it was pushed to. The patch follows HEAD.
#
# Single source for the web route, home.packages and the route test: a second,
# unpatched cgit in the profile would show the old numbers when run by hand.
# shortcut: patch touches ui-repolist.c only; re-check when cgit is bumped.
{ pkgs }:
pkgs.cgit.overrideAttrs (prev: {
  patches = (prev.patches or [ ]) ++ [ ./cgit-idle-follow-head.patch ];
})
# Root's SSH access for this server.
#
# - The "admins" keys get a normal login shell (also usable for git).
# - Every other key is forced through restricted-git-ssh: read-only git
#   plumbing only, limited to repos under reposDir. No shell, no push, no
#   port/agent/X11 forwarding.
# Both lists come from ~/Gist/Vault/server/users.nix via guest-groups.nix, so
# ssh access has exactly one source.
{ config, pkgs, lib, ... }:
let
  reposDir = "${config.home.homeDirectory}/Repos";
  registry = import ../../../guest-groups.nix { inherit lib; };

  # Forced command for guest keys. Parses the command line safely (shlex),
  # resolves the repo path (realpath), requires it under the root given as
  # argv[1] (set per key below), then execs git-upload-pack/git-upload-archive
  # directly. Python is used because doing this correctly in shell means
  # fighting git's argument quoting.
  restrictedGitSsh = pkgs.writeScriptBin "restricted-git-ssh" ''
    #!${pkgs.python3}/bin/python3
    import os
    import shlex
    import sys

    # argv[1] is mandatory: a missing root must fail, not default to all of
    # ~/Repos (every generated authorized_keys line passes one).
    if len(sys.argv) < 2:
        sys.exit("restricted-git-ssh: no repo root given by authorized_keys")
    REPOS = os.path.realpath(sys.argv[1])
    ALLOWED = {
        "git-upload-pack": "${pkgs.git}/bin/git-upload-pack",
        "git-upload-archive": "${pkgs.git}/bin/git-upload-archive",
    }

    args = shlex.split(os.environ.get("SSH_ORIGINAL_COMMAND", ""))
    if len(args) != 2 or args[0] not in ALLOWED:
        sys.exit("read-only git access only")

    # Join against $HOME so both `ssh://host/root/Repos/x.git` (absolute) and
    # `host:Repos/x.git` / `ssh://host/~/Repos/x.git` forms land in one place.
    path = args[1][2:] if args[1].startswith("~/") else args[1]
    repo = os.path.realpath(os.path.join("${config.home.homeDirectory}", path))
    if repo != REPOS and not repo.startswith(REPOS + os.sep):
        sys.exit("access limited to " + REPOS)

    os.execv(ALLOWED[args[0]], [args[0], repo])
  '';

  # Restriction applied to every guest key: read-only git, no shell, no
  # port/agent/X11 forwarding, no pty.
  guestRestrictions =
    "no-port-forwarding,no-agent-forwarding,no-pty,no-X11-forwarding";
  guestLine = root: k:
    ''command="${config.home.homeDirectory}/.nix-profile/bin/restricted-git-ssh ${root}",${guestRestrictions} ${k}'';

  # The admins' keys: full login shell plus git.
  ownerKeys = registry.adminKeys;

  # Guest keys are `sshKeys` in ~/Gist/Vault/server/users.nix, one entry per
  # user, scoped to that user's team folders by ../../../guest-groups.nix.

  authorizedKeys = pkgs.writeText "authorized_keys" (
    lib.concatMapStrings (k: "${k}\n") ownerKeys
    + lib.concatMapStrings (g:
      lib.concatMapStrings (k: "${guestLine "${reposDir}/${g.name}" k}\n") g.sshKeys)
      registry.teams
  );
in {
  home.packages = [ restrictedGitSsh ];

  # sshd's StrictModes (default yes) refuses an authorized_keys symlinked into
  # /nix/store, since /nix/store is group-writable. Copy it into a real 0600
  # file instead of using home.file.
  home.activation.sshAuthorizedKeys = lib.hm.dag.entryAfter [ "writeBoundary" ] ''
    $DRY_RUN_CMD mkdir -p $VERBOSE_ARG "$HOME/.ssh"
    $DRY_RUN_CMD chmod 700 "$HOME/.ssh"
    $DRY_RUN_CMD install -m 600 ${authorizedKeys} "$HOME/.ssh/authorized_keys"
  '';
}
''
  redir /circle/xby /circle/xby/
  redir /circle/wxy /circle/wxy/
  handle /circle/xby/* {
    route {
      import auth
      uri strip_prefix /circle/xby
      reverse_proxy 127.0.0.1:3002
    }
  }
  handle /circle/wxy/* {
    route {
      import auth
      uri strip_prefix /circle/wxy
      reverse_proxy 127.0.0.1:3003
    }
  }
''
{ config, pkgs, lib, ... }:
let
  cfg = config.my.server.caddyAuthelia;
  consts = import ./cgit/consts.nix;

  # Bare repos, synced from the laptop by Syncthing; cgit's scan-path picks up
  # every repo under here automatically.
  cgitReposPath = "${config.home.homeDirectory}/Repos";
  cgitCacheRoot = "${config.xdg.cacheHome}/${consts.cacheDir}";

  # Mobile-friendly cgit stylesheet, pinned to a Git revision.
  cgitTheme = ((import <npins> {input=./cgit/sources.json;}).responsive-cgit-css {inherit pkgs;}).outPath;

  # Fail the build if the pinned theme no longer provides its stylesheet.
  cgitThemeRoot = pkgs.runCommandLocal "cgit-theme-root" { } ''
    install -Dm644 ${cgitTheme}/cgit.css $out${consts.themeFile}
  '';

  cgit = import ./cgit/package.nix { inherit pkgs; };

  # The viewport tag lets the theme's mobile media queries use device width.
  cgitHeadInclude = pkgs.writeText "cgit-head-include.html" ''
    <meta name="viewport" content="width=device-width, initial-scale=1"/>
  '';

  # No spaces around '=': cgit's config reader keeps them in the key name
  # ("scan-path " != "scan-path"), silently ignoring the option.
  cgitrc = pkgs.writeText "cgitrc" ''
    # Served by Caddy at https://xieby1.cn${consts.prefix}/ ; see ./cgit/.
    virtual-root=${consts.prefix}/
    # HTTPS clone needs git-compatible auth in front of it, so advertise the
    # SSH URL people actually clone with (same form as npins/my/sources.json).
    # $CGIT_REPO_URL is the repo path relative to scan-path.
    clone-url=ssh://root@xieby1.cn/~/Repos/$CGIT_REPO_URL

    # Caddy serves the pinned responsive stylesheet; cgit's other assets
    # still come from the cgit package (see ./cgit/caddy.nix).
    css=${consts.prefix}${consts.themeFile}
    head-include=${cgitHeadInclude}
    favicon=${consts.prefix}/favicon.ico
    logo=${consts.prefix}/cgit.png
    js=${consts.prefix}/cgit.js

    # Clones go through git-http-backend on the Caddy side, not cgit's own
    # dumb-HTTP endpoint.
    enable-http-clone=0

    # cgit creates files directly under cache-root, so it must already exist;
    # ./cgit/config.nix creates it.
    cache-root=${cgitCacheRoot}
    # cgit hardcodes the footer timestamp to UTC (+0000); local-time makes it use
    # the server timezone (Asia/Shanghai here).
    # shortcut: local-time is global, so commit/tag/atom dates also render as
    # +0800 instead of the author's tz; patch cgit's footer if per-view tz matters.
    local-time=1
    scan-path=${cgitReposPath}
  '';

  caddyfile = pkgs.writeText "Caddyfile" ''
    (auth) {
      forward_auth 127.0.0.1:9091 {
        uri /api/authz/forward-auth
        copy_headers Remote-User Remote-Groups Remote-Name Remote-Email
      }
    }

    https://xieby1.cn {
      # Nothing here pre-compresses; the stylesheet and cgit's HTML are plain text.
      encode zstd gzip

      # sixu routes; see ./sixu/.
      ${import ./sixu/caddy.nix}

      # circle routes; see ./circle/.
      ${import ./circle/caddy.nix}

      # XingYao authenticates before stripping its public prefix.
      ${import ./xingyao/caddy.nix}

      # syncthing routes; see ./syncthing/.
      ${import ./syncthing/caddy.nix}

      # pi-web (dell) routes; see ./pi-web/.
      ${import ./pi-web/caddy.nix}

      # cgit routes; see ./cgit/.
      ${import ./cgit/caddy.nix {
        inherit cgit;
        inherit (pkgs) git;
        inherit cgitrc;
        themeRoot = cgitThemeRoot;
        reposPath = cgitReposPath;
      }}

      redir /web /web/
      handle /web/* {
        route {
          import auth
          uri strip_prefix /web
          root * ${config.home.homeDirectory}/web
          file_server
        }
      }

      reverse_proxy 127.0.0.1:9091
    }
  '';
in {
  imports = [
    ./pi-web/config.nix
    ./cgit/config.nix
    ./cgit/ssh
  ];

  config = lib.mkIf cfg.enable {
    home.packages = [ pkgs.caddy ];

    systemd.user.services.caddy-auth-proxy = {
      Unit = {
        Description = "Caddy auth proxy";
        After = [ "authelia.service" ];
        Wants = [ "authelia.service" ];
      };
      Install.WantedBy = [ "default.target" ];
      Service = {
        ExecStart = "${pkgs.caddy}/bin/caddy run --config ${caddyfile} --adapter caddyfile";
        ExecReload = "${pkgs.caddy}/bin/caddy reload --config ${caddyfile} --adapter caddyfile --force";
        Restart = "on-failure";
      };
    };
  };
}
# dell's pi-web (jmfederico) over the tailnet via the socat bridge (./config.nix).
# pi-web is prefix-portable, so only this sub-path needs routing; it keeps its
# browser/PWA/WS URLs under /pi/dell/ itself.
let
  consts = import ./consts.nix;
in ''
  redir /pi/dell /pi/dell/
  handle /pi/dell/* {
    route {
      import auth
      uri strip_prefix /pi/dell
      reverse_proxy 127.0.0.1:${toString consts.dellBridgePort}
    }
  }
''
{ config, pkgs, lib, ... }:
let
  cfg = config.my.server.caddyAuthelia;
  consts = import ./consts.nix;

  # dell's pi-web (jmfederico) listens only on its own loopback. aliyun reaches
  # the tailnet through its userspace tailscaled SOCKS5 proxy; socat turns that proxy
  # into a plain loopback upstream Caddy can reverse_proxy to.
  dellIp = config.my.tailscale.devices.dell.ip;
  tailscaleSocksPort = config.my.tailscale.instances.official.socks5Port;
in {
  config = lib.mkIf cfg.enable {
    home.packages = [ pkgs.socat ];

    # Loopback TCP -> aliyun's userspace-tailscale SOCKS5 -> dell pi-web.
    systemd.user.services.pi-web-bridge-dell = {
      Unit = {
        Description = "SOCKS bridge: Caddy -> dell pi-web over userspace tailscale";
        After = [ "tailscaled-official.service" ];
      };
      Install.WantedBy = [ "default.target" ];
      Service = {
        ExecStart = "${pkgs.socat}/bin/socat TCP-LISTEN:${toString consts.dellBridgePort},bind=127.0.0.1,fork,reuseaddr SOCKS5-CONNECT:127.0.0.1:${toString tailscaleSocksPort}:${dellIp}:${toString consts.piWebPort}";
        Restart = "on-failure";
        RestartSec = 3;
      };
    };
  };
}
# Shared by the Caddy route fragment (./caddy.nix) and the bridge service
# (./config.nix), which are generated from separate files but must agree on the
# port. Keeping them here stops the reverse_proxy upstream and the socat
# listener from drifting apart.
{
  # pi-web's own listening port; identical on every device.
  piWebPort = 8504;

  # aliyun-side loopback bridge -> dell:piWebPort, over the userspace-tailscale
  # SOCKS5 proxy. Caddy reverse_proxy targets this port.
  dellBridgePort = 9008;
}
''
  redir /sixu/xby /sixu/xby/
  redir /sixu/wxy /sixu/wxy/
  handle /sixu/xby/* {
    route {
      import auth
      uri strip_prefix /sixu/xby
      reverse_proxy 127.0.0.1:3000
    }
  }
  handle /sixu/wxy/* {
    route {
      import auth
      uri strip_prefix /sixu/wxy
      reverse_proxy 127.0.0.1:3001
    }
  }
''
''
  redir /syncthing /syncthing/
  handle /syncthing/* {
    route {
      import auth
      uri strip_prefix /syncthing
      reverse_proxy 127.0.0.1:8384 {
        header_up Host {upstream_hostport}
      }
    }
  }
''

XingYao proxy and local deployment test

The public path is /BTeam/XingYao/. The sibling caddy.nix strips untrusted identity headers, authenticates the original path, then strips the prefix and proxies to 127.0.0.1:3004. Authelia allows BTeam or admins with two-factor authentication; both groups can edit the shared collection. The Home Manager instance is configured in ../../xingyao/default.nix and uses a server-local data repository, not an actively synchronized directory. initializeWithSamples = true seeds a missing/empty directory before startup using the service user's configured Git identity; nonempty repositories are never rewritten. This check runs on every start, so it can also reseed samples after data loss. Disable the option after first use if that is undesirable. The GitHub source is pinned in ../../xingyao/sources.json using SSH because anonymous archive downloads are unavailable; the building user's GitHub SSH access is required.

Test locally without deploying

From the Nix configuration repository:

nix-shell -p python3Packages.pyyaml caddy authelia \
  --run 'python3 server/caddy/xingyao/test.py'

This evaluates the real XingYao and Authelia modules with Home Manager, builds the pinned application, and runs the exact Caddy route on temporary loopback ports. It uses a temporary HOME, synthetic user registry, temporary TLS CA, randomly generated passwords/TOTP secrets, and a sample repository created by the generated service pre-start script. Requests use the production hostname for Host/SNI but connect directly to loopback; DNS and the live server are never used. It installs no certificates, activates no Home Manager generation, changes no services and removes its temporary data/processes afterward. Nix build outputs and disposable password hashes remain in the Nix store as usual.

Checks include:

  • Service environment, data path, public prefix, default-target startup, sample initialization and repeat-start preservation.
  • Generated Authelia policy and database schema.
  • Signed-out and password-only denial, successful BTeam/admins TOTP logins, and unrelated-group denial.
  • Original-path authorization, neighboring/case-mismatched path policy, and forged identity rejection.
  • Trailing-slash redirect, prefixed packaged assets and sample reads.
  • Missing/foreign Origin denial and one authenticated mutation with correct Git authorship.

This is a focused deployment test, not a full server Home Manager build. It intentionally avoids unrelated applications and does not read the real vault registry. The full server build still requires all other pinned dependencies to be available.

''
  @xingyao path /BTeam/XingYao /BTeam/XingYao/*
  handle @xingyao {
    route {
      request_header -Remote-User
      request_header -Remote-Name
      request_header -Remote-Email
      request_header -Remote-Groups
      # Authorize the original resource path, before stripping the prefix.
      forward_auth 127.0.0.1:9091 {
        uri /api/authz/forward-auth
        copy_headers Remote-User Remote-Name Remote-Email
      }
      redir /BTeam/XingYao /BTeam/XingYao/ 308
      uri strip_prefix /BTeam/XingYao
      reverse_proxy 127.0.0.1:3004
    }
  }
''
# Evaluate real deployment modules with a disposable HOME/registry, never activate.
{ pkgs ? import <nixpkgs> { config = {}; overlays = []; } }:
let
  src = (import <npins> {input=../../xingyao/sources.json;}).xingyao;
  hm = import <home-manager/modules> {
    inherit pkgs;
    configuration = { lib, ... }: {
      imports = [
        ../../authelia
        (lib.modules.importApply ../../xingyao {inherit src;})
      ];
      options.my.server.caddyAuthelia.enable = lib.mkEnableOption "test proxy";
      config = {
        home.username = "test";
        home.homeDirectory = builtins.getEnv "HOME";
        home.stateVersion = "25.05";
        my.server.caddyAuthelia.enable = true;
      };
    };
  };
  cfg = hm.config;
  commandConfig = command: builtins.head (pkgs.lib.splitString " " (builtins.elemAt (pkgs.lib.splitString "--config " (builtins.head command)) 1));
in
assert builtins.all (a: a.assertion) cfg.assertions;
pkgs.writeText "xingyao-deployment-test.json" (builtins.toJSON {
  autheliaConfig = commandConfig cfg.systemd.user.services.authelia.Service.ExecStart;
  xingyao = cfg.systemd.user.services.xingyao-main;
  route = import ./caddy.nix;
})
{ src }: # local-args
{ config, ... }:
{
  imports = [
    (src + /nix/home-manager/circle.nix)
  ];

  services.circle = {
    enable = true;
    instances = {
      xby = {
        dataDir = "${config.home.homeDirectory}/Gist/Data/circle/xby/";
        host = "127.0.0.1";
        port = 3002;
      };
      wxy = {
        dataDir = "${config.home.homeDirectory}/Gist/Data/circle/wxy/";
        host = "127.0.0.1";
        port = 3003;
      };
    };
  };
}
{ lib, ... }:
let
  sources = import <npins> {input = ./sources.json;};
in {
  imports = [
    ./authelia
    ./caddy
    (lib.modules.importApply ./circle { src = sources.circle; })
    (lib.modules.importApply ./sixu { src = sources.sixu; })
    (lib.modules.importApply ./xingyao { src = sources.xingyao; })
  ];

  options.my.server.caddyAuthelia.enable = lib.mkEnableOption "Caddy + Authelia prototype user services";

  config = {
    targets.genericLinux.enable = true;
    targets.genericLinux.gpu.enable = false;

    # NOTE: These server daemons run as root Home Manager user services. The host
    # must keep root's systemd user manager alive after logout:
    #
    #   loginctl enable-linger root
    #
    # Without lingering, the last root SSH logout stops user@0.service, which
    # stops Caddy/Authelia and browsers may report PR_END_OF_FILE_ERROR.
    my.server.caddyAuthelia.enable = true;
  };
}
# Everything derived from the server's user registry:
#   ~/Gist/Vault/server/users.nix
#
# That one file is the only list of people, so adding a guest is one entry there
# and nothing in this repo. It is interpreted here once, for both consumers:
#   - teams: each non-"admins" group. Its repository access is limited to
#       https://xieby1.cn/Repos/<name>/…   (Authelia group "<name>"; the path
#       rule in ../authelia/default.nix is the whole web-side boundary)
#       read-only git for ~/Repos/<name> (enforced by ../caddy/cgit/ssh/default.nix)
#   - adminKeys: the ssh keys of the "admins" users, for a normal login shell
#     ../authelia/default.nix also grants BTeam/admins the shared XingYao app;
#     that web permission does not broaden SSH or repository access.
#     ../authelia/default.nix generates Authelia's user database from the same
#     file (with the ssh keys stripped).
#
# A missing or malformed registry fails evaluation of the whole home-manager
# configuration; that is deliberate, the alternatives are silent empty rules.
{
  lib,
  # Overridable so ../tests/guest-groups can run against a fixture.
  usersFile ? ~/Gist/Vault/server/users.nix,
  reposDir ? ~/Repos,
}:
let
  users = import usersFile { inherit lib; };
  everyone = builtins.attrValues users;
  keyed = u: u.sshKeys or [ ];
  hasGroup = name: u: builtins.elem name (u.groups or [ ]);

  # "admins" is the owner group, granted /sixu and /web by the rules in
  # ../authelia/default.nix; it is never a team.
  teams = builtins.filter (n: n != "admins")
    (lib.unique (lib.concatMap (u: u.groups or [ ]) everyone));
in
# The name ends up in an Authelia regex (^/Repos/<name>(/.*)?$) and on the
# forced-command line in authorized_keys, both of which read more than a path
# segment: a "." would match any character (team A.B also matching /Repos/AXB/)
# and a space would split the ssh command's argument list. Keep names plain.
assert builtins.all (n: builtins.match "[A-Za-z0-9_-]+" n != null) teams;
# A team is a folder under ~/Repos. A typo would mean a guest who logs in and
# silently sees nothing; a stray *file* with a team's name would build too and
# grant nothing, so ask for a directory specifically.
assert builtins.all (n: ((builtins.readDir reposDir).${n} or "") == "directory") teams;
# A misspelled or extra field is otherwise silent: `sshKey` would drop a key
# without an error, and a secret pasted into the wrong field would be written
# into the generated user database in /nix/store.
assert builtins.all (u:
  builtins.all (k: builtins.elem k [ "displayname" "password" "email" "groups" "sshKeys" ])
    (builtins.attrNames u)) everyone;
# Keys are only emitted for admins and for team members, so a user with no group
# would silently get none.
assert builtins.all (u: (u.groups or [ ]) != [ ]) everyone;
# Every access rule for the owner needs this group; without it nobody can reach
# the portal, /sixu or /web, and only a shell on the box can fix it.
assert builtins.any (hasGroup "admins") everyone;
{
  adminKeys = lib.concatMap keyed (builtins.filter (hasGroup "admins") everyone);
  teams = map (name: {
    inherit name;
    # Keys of every user in the group, so one key can cover several teams.
    sshKeys = lib.concatMap keyed (builtins.filter (hasGroup name) everyone);
  }) teams;
}

Rustical base-path patch

package.nix applies base-path.patch to pkgs.rustical (based on 0.16.7). The patch implements the subpath deployment described in upstream issue #148.

[http]
base_path = "/cal"

Omit base_path to keep root deployment. For /cal, the proxy must forward /cal and /cal/* without stripping the prefix. Host-root CalDAV/CardDAV discovery can be forwarded to Rustical's prefixed /.well-known/caldav and /.well-known/carddav paths. The OIDC redirect URI is https://xieby1.cn/cal/frontend/login/oidc/callback.

Verify locally

From the Nix config root:

RUSTICAL="$(nix-build --no-out-link -E 'import ./server/rustical/package.nix { pkgs = import <nixpkgs> {}; }')/bin/rustical"
export RUSTICAL
nix-shell -p python3 openssl caddy authelia --run 'python3 server/rustical/test.py "$RUSTICAL"'

The integration test uses loopback only, with a temporary TLS CA, OIDC credentials and SQLite databases. localhost.localdomain must resolve to 127.0.0.1. It exercises root and prefixed mounts, same-origin HTTPS routing, Authelia OIDC with TOTP, app-password revocation, and CalDAV event operations. It checks frontend responses and client setup URLs over HTTP, not through native client or browser UI automation.

Rebase on an upgrade

Apply the patch to a clean checkout of the new packaged tag and review upstream changes for newly hardcoded root paths. If frontend source changes, regenerate crates/frontend/public/assets/js/bundle.mjs using upstream's deno task build in crates/frontend/js-components, and include that diff. The Nix package embeds the bundle rather than rebuilding it. Export the updated patch and rerun the build and local integration test before shipping.

{ pkgs }:
pkgs.rustical.overrideAttrs (old: {
  patches = (old.patches or [ ]) ++ [ ./base-path.patch ];
})
{ src }: # local-args
{ config, ... }: {
  imports = [
    (src + /nix/home-manager/sixu.nix)
  ];
  services.sixu = {
    enable = true;
    instances = {
      xby = {
        dataDir = "${config.home.homeDirectory}/Gist/Data/sixu/xby/";
        host = "127.0.0.1";
        port = 3000;
      };
      wxy = {
        dataDir = "${config.home.homeDirectory}/Gist/Data/sixu/wxy/";
        host = "127.0.0.1";
        port = 3001;
      };
    };
  };
}
{ src }: # local-args
{ config, ... }:
{
  imports = [
    (src + /nix/home-manager/xingyao.nix)
  ];

  services.xingyao = {
    enable = true;
    instances.main = {
      dataDir = "${config.home.homeDirectory}/Repos/BTeam/XingYaoData";
      port = 3004;
      basePath = "/BTeam/XingYao/";
      initializeWithSamples = true;
    };
  };
}
2022.05.29

静态链接,以qemu为例

太长不看

  • 实现了qemu静态链接,无任何动态链接库的依赖。 采用了两个版本的qemu,当前版本Nix的qemu(nix 21.11, qemu 6.1.1) 和qemu3.1.0这两个版本。
  • nix脚本:pkgs_qemu_static.nix

pkgsStatic及其源代码

Nixpkgs含有pkgsStatic软件包,但是大多软件无法直接使用。 需要进行手动修复。

pkgsStatic加载过程的源码

  • pkgs/top-level/stage.nix 将crossSystem设置为static且abi为musl。 之所以用Musl是因为,

    Currently uses Musl on Linux (couldn’t get static glibc to work).

    其代码大致的如下,

    pkgsStatic = nixpkgsFun {
      crossSystem = {
        isStatic = true;
        parsed = stdenv.hostPlatform.parsed // {
          abi = musl;
    };};};
    
    • nixpkgsFun = newArgs: import pkgs/top-level/default.nix (...)
      • pkgs/top-level/default.nix: stdenvStages {..., crossSystem, ...}
        • pkgs/stdenv/default.nix: stagesCross
          • pkgs/stdenv/cross/default.nix: stdenvAdapters.makeStatic
            • pkgs/stdenv/adapters.nix: makeStatic
              • makeStaticLibraries
                • 添加configureFlags "--enable-static" "--disable-shared"
                • 添加cmakeFlags "-DBUILD_SHARED_LIBS:BOOL=OFF"
                • 添加mesonFlags "-Ddefault_library=static"
              • makeStaticBinaries
                • 添加NIX_CFLAGS_LINK "-static"
                • 添加configureFlags "--disable-shared"

TODO: 读懂makeStaticLibraries和makeStaticBinaries。

基本思路

对于当前版本的qemu,使用pkgsStatic.qemu ,挨个修复编译报错即可。

对于历史版本的qemu,以3.1.0为例,编译方式已和现在有区别, 比如之前完全是configure, make,而现在引入了meson。 初步设想两种方案,

  1. 嫁接老版本nixpkgs到当前版本 将qemu-3.1.0对应的nixpkgs嫁接到当前的nixpkgs
  2. 改造新版本nixpkgs以适应老版本 通过overlay,override方法修改当前nixpkgs的qemu的nix表达式

我采用的第一种办法,将老版本nixpkgs嫁接到当前版本nixpkgs。 使用lazamar.co.uk/nix-versions 查询支持qemu-3.1.0的nixpkgs版本。 引入qemu-3.1.0的示例代码如下,详细见pkgs_qemu_static.nix

# get old nixpkgs which contains qemu-3.1.0
oldNixpkgsSrc = builtins.fetchTarball {...}
qemu31 = pkgs.callPackage (
  oldNixpkgsSrc + "/pkgs/applications/virtualization/qemu/default.nix"
) {...}

然后挨个修复编译报错即可。

调试手段

还原构建环境

# 保留构建失败的现场
nix-build pkgs_qemu_static.nix -K

进入现场包含env-vars文件和失败时的源码文件夹。 恢复环境,

. ./env-vars
. $stdenv/setup

查看依赖树

nix-store --query --tree <xxx.drv>

结果

目前仅需要命令行的qemu,因此为了省事, 我去掉了声音和图像支持。

注:在NixOS 21.11上和在ubuntu 22配合nix上编译出来的qemu二进制文件一模一样。

xieby1@yoga14s:~
$ pkgs_qemu_static.nix 
/nix/store/gs6plgyc0jr9i5qams0ifksijnq9hkq2-qemu-static-x86_64-unknown-linux-musl-6.1.1
/nix/store/lm9kl1nm7bs4hy6l4qng03k4srx1x28n-qemu-3.1.0-x86_64-unknown-linux-musl
xieby1@yoga14s:~
$ ldd result/bin/qemu-system-x86_64 
	not a dynamic executable
xieby1@yoga14s:~
$ result/bin/qemu-system-x86_64 --version
QEMU emulator version 6.1.1
Copyright (c) 2003-2021 Fabrice Bellard and the QEMU Project developers
xieby1@yoga14s:~
$ ldd result-2/bin/qemu-system-x86_64 
	not a dynamic executable
xieby1@yoga14s:~
$ result-2/bin/qemu-system-x86_64  --version
QEMU emulator version 3.1.0
Copyright (c) 2003-2018 Fabrice Bellard and the QEMU Project developers

usr/default.nix

home-manager的入口配置文件,它导入了:

因为部分系统不需要GUI程序,比如安卓手机nix-on-droid或是树莓派等。 我利用环境变量DISPLAY用于判断是否导入GUI程序的配置。

{
  enableGraphics ? true,
  enableExtendedCLI ? true,
  enableServer ? false,
}: # local args
{ lib, ... }: {
  imports = [
    ./ai
    ./cachix-push.nix
    ./yq-merge
    ./syncthing-gist-ignore.nix
    (lib.modules.importApply ./cli { inherit enableExtendedCLI enableServer; })
  ]
  ++ lib.optional enableGraphics ./gui;
  _module.args = {
    isNixOnDroid = (builtins.getEnv "USER") == "nix-on-droid";
  };
}
{ pkgs, config, ... }: let
  # Ghostty requires a dotted GTK application ID; match StartupWMClass for the desktop icon.
  class = "cn.xieby1.CheatsheetEdit";
  open_my_cheatsheet_md_sh = pkgs.writeShellScript "open_my_cheatsheet_md" ''
    cd ${config.home.homeDirectory}/Docs/Tech/my_cheatsheet
    # Open Outline and focus on code
    ghostty --class=${class} -e nvim index.mkd -c Outline!
    make
  '';
in {
  xdg.desktopEntries = {
    # singleton apps
    my_cheatsheet_md = {
      name = "Cheatsheet Edit MD";
      genericName = "cheatsheet";
      exec = "${open_my_cheatsheet_md_sh}";
      icon = builtins.toFile "cheatsheet.svg" ''
        <svg width="64" height="64" xmlns="http://www.w3.org/2000/svg">
          <rect width="100%" height="100%" rx="20%" ry="20%" fill="#666666"/>
          <text x="50%" y="50%" text-anchor="middle" dominant-baseline="middle" font-size="18" font-weight="bold" fill="#F5F5F5">
            <tspan x="50%" dy="-1.0em">CS</tspan>
            <tspan x="50%" dy="1.0em">Edit</tspan>
            <tspan x="50%" dy="1.0em">MD</tspan>
          </text>
        </svg>
      '';
      settings = {
        StartupWMClass = class;
      };
    };
  };
}
{ ... }: {
  imports = [
    ./niri
    # ./dms
    ./noctalia
  ];
}

Gnome

  • Incompatibility issues: Updates frequently break extensions and addons.
  • Conservative approach: GNOME doesn't support the layer_shell protocol, which is required by applications like rofi.
    • https://gitlab.gnome.org/GNOME/mutter/-/issues/973
    • Other protocols may also be unsupported.
  • JavaScript-based extensions with memory leaks: The extension system appears to have memory leaks that consume significant memory. I often need to use alt-f2 r to reclaim some memory.
  • Wayland limitations exacerbated by GNOME:
    • After transitioning from X11 to Wayland, several important desktop features stopped working, such as using xdotool to move specific windows to specific workspaces.
    • While these limitations originate from Wayland itself, many window managers provide alternative solutions. However, GNOME makes it particularly difficult to implement such workarounds. Creating custom GNOME extensions is possible, but the learning curve is steep and the API lacks stability.

Hyprland

  • Cons:
    • Static workspace (id: 1,2,3,...)
      • As a result, it is not easy to insert a new workspace into a place.
      • Though we can write a script to swap workspace from tail to the place, it is very inelegant.

Plasma

Cons:

  • Does not support set 3-finger swipe directions
  • Extensions use JS
{ pkgs, ... }: {
  xdg.cacheFile."dms-avatar.png" = {
    source = pkgs.fetchurl {
      url = "https://github.com/xieby1.png";
      sha256 = "1s20qy3205ljp29lk0wqs6aw5z67db3c0lvnp0p7v1q2bz97s9bm";
    };
    # DMS currently has no config option for the avatar path, so set it through IPC.
    onChange = ''
      PATH="$PATH:${pkgs.quickshell}/bin" ${pkgs.dms-shell}/bin/dms ipc call profile setImage ~/.cache/dms-avatar.png
    '';
  };
}
{ ... }: {
  yq-merge.".config/DankMaterialShell/clsettings.json" = {
    generator = builtins.toJSON;
    expr = {
      # default clipboard entries is 100
      maxHistory = 999;
    };
  };
}
let
  pkgs = import <nixpkgs> {};
  dms-src = pkgs.dms-shell.src;
  SPEC = pkgs.runCommand "SPEC" {} ''
    awk '/^var SPEC/,/^}/' ${dms-src}/quickshell/Common/settings/SettingsSpec.js > $out
  '';
  configVersion = pkgs.runCommand "configVersion" {} ''
    sed -n 's/.*readonly property int settingsConfigVersion: \([0-9]*\).*/\1/p' \
      ${dms-src}/quickshell/Common/SettingsData.qml | tr -d '\n' > $out
  '';
  gen-settings_js =  pkgs.writeTextFile {
    name = "gen-settings.js";
    text = /*js*/ ''
      const percentToUnit = null;
      ${builtins.readFile SPEC}
      var root = {};
      for (var k in SPEC) {
        if (SPEC[k].persist === false) continue;
        root[k] = SPEC[k].def;
      }
      root.configVersion = ${builtins.readFile configVersion};
      console.log(JSON.stringify(root, null, 2));
    '';
  };
in pkgs.runCommand "settings.json" {} ''
  ${pkgs.nodejs}/bin/node ${gen-settings_js} > $out
''
{ pkgs, ... }:
let
  patchedDmsShell = pkgs.dms-shell.overrideAttrs (old: {
    postInstall = (old.postInstall or "") + ''
      substituteInPlace $out/share/quickshell/dms/Modules/Notifications/Popup/NotificationPopup.qml \
        --replace-fail 'visible: cardHoverHandler.hovered' 'visible: true' \
        --replace-fail 'visible: actionCount < 3 && cardHoverHandler.hovered' 'visible: actionCount < 3'
    '';
  });
in
{
  imports = [
    ./avatar.nix
    ./settings.nix
    ./plugins
    ./clsettings.nix
  ];
  cachix_packages = [ patchedDmsShell ];
  home.packages = [
    patchedDmsShell
    pkgs.quickshell
    pkgs.dgop

    # App icons for many apps not showing in App Launcher.
    # https://github.com/AvengeMedia/DankMaterialShell/issues/1132
  ];
}
{ ... }: {
  home.file.".config/DankMaterialShell/plugins/wallpaperBing".source = (import <npins> {input=./sources.json;}).DankPluginBingWallpaper;
  yq-merge.".config/DankMaterialShell/plugin_settings.json" = { generator = builtins.toJSON; expr = {
    wallpaperBing = {
      enabled = true;
    };
  };};
}
{ ... }: {
  imports = [
    ./bing-wallpaper.nix
    ./unified-taskbar.nix
  ];
  yq-merge.".config/DankMaterialShell/plugin_settings.json" = {
    preOnChange = ''
      if [[ ! -e ~/.config/DankMaterialShell/plugin_settings.json ]]; then
        echo '{}' > ~/.config/DankMaterialShell/plugin_settings.json
      fi
    '';
  };
}
{ ... }: {
  home.file.".config/DankMaterialShell/plugins/dms-unified-taskbar".source = (import <npins> {input=./sources.json;}).dms-unified-taskbar;
  yq-merge.".config/DankMaterialShell/plugin_settings.json" = {
    generator = builtins.toJSON;
    expr = {
      unifiedTaskbar = {
        enabled = true;
        compactMode = true;
        allMonitors = false;
        iconPadding = 2;
        itemSpacing = 0;
        workspaceSpacing = 0;
      };
    };
  };
}
{ pkgs, ... }: let
  settings-relpath = ".config/DankMaterialShell/settings.json";
in {
  yq-merge.${settings-relpath} = {
    preOnChange = ''
      if [[ ! -e ~/${settings-relpath} ]]; then
        cat ${import ./default-settings.nix} > ~/${settings-relpath}
      fi
      ${pkgs.yq-go}/bin/yq -i ' .barConfigs[0].leftWidgets=[]
                           | .barConfigs[0].centerWidgets=[]
                           | .barConfigs[0].rightWidgets=[]' ~/${settings-relpath}
    '';
    generator = builtins.toJSON;
    expr = {
      currentThemeName = "dynamic";
      currentThemeCategory = "dynamic";
      cursorSettings.theme = "Adwaita";
      centeringMode = "geometric";
      clockDateFormat = "yyyy.MM.dd ddd";
      lockDateFormat = "yyyy.MM.dd dddd";
      showDock = false;
      dockAutoHide = true;
      dockOpenOnOverview = true;
      barConfigs = [{
        autoHide = true;
        showOnWindowsOpen = true;
        openOnOverview = true;
        noBackground = true;
        spacing = 0;
        widgetPadding = 0;
        leftWidgets = [
          { enabled = true; id = "privacyIndicator"; }
          { enabled = true; id = "notificationButton"; }
          { enabled = true; id = "clipboard"; }
          { enabled = true; id = "wallpaperBing"; }
          { enabled = true; id = "music"; }
          { enabled = true; id = "spacer"; size = 10; }
          { enabled = true; id = "unifiedTaskbar"; }
        ];
        centerWidgets = [
          { enabled = true; id = "weather"; }
          { enabled = true; id = "spacer"; size = 10; }
          { enabled = true; id = "clock"; }
        ];
        rightWidgets = [
          { enabled = true; id = "systemTray"; }
          { enabled = true; id = "cpuUsage"; }
          { enabled = true; id = "memUsage"; showSwap = true; }
          { enabled = true; id = "diskUsage"; }
          { enabled = true; id = "network_speed_monitor"; }
          { enabled = true; id = "battery"; }
          { enabled = true; id = "controlCenterButton"; }
        ];
      }];
      notificationTimeoutLow = 5000;
      notificationTimeoutNormal = 0;
      notificationTimeoutCritical = 0;
    };
  };
}
# Use `wev` to find out key name
{ pkgs, ... }: {
  wayland.windowManager.niri.settings = {
    binds = {
      "Ctrl+Alt+T".spawn = "ghostty";
      "Mod+D".spawn-sh = "noctalia msg panel-toggle launcher";
      "Mod+W".spawn-sh = "noctalia msg panel-open launcher '/win '";
      "Mod+Alt+L".spawn-sh = "noctalia msg session lock";
      "Mod+N".spawn-sh = "noctalia msg panel-toggle control-center notifications";
      "Mod+C".spawn-sh = "noctalia msg panel-toggle control-center calendar";
      "Mod+M".spawn-sh = "noctalia msg panel-toggle control-center media";
      "Mod+X".spawn-sh = "noctalia msg panel-toggle session";
      "Mod+V".spawn-sh = "noctalia msg panel-toggle clipboard";
      # Until Noctalia can toggle Smart/Off and reserve space conditionally:
      # https://github.com/noctalia-dev/noctalia/issues/3761
      # https://github.com/noctalia-dev/noctalia/issues/3780
      "Mod+H".spawn-sh = ''
        case "$(noctalia msg config-get bar.default.smart_auto_hide)" in
          true)
            noctalia msg config-set bar.default.smart_auto_hide false
            noctalia msg config-set bar.default.reserve_space true
          ;;
          false)
            noctalia msg config-set bar.default.reserve_space false
            noctalia msg config-set bar.default.smart_auto_hide true
          ;;
          *) echo "Could not read Noctalia smart auto-hide setting" >&2; exit 1 ;;
        esac
      '';
      "Mod+Shift+H".spawn-sh = "noctalia msg bar-toggle";
      "Mod+F".spawn-sh = "ghostty -e bash -i fzf-doc";
      "Mod+S".spawn-sh = "${pkgs.wl-kbptr}/bin/wl-kbptr -o modes=floating,click -o mode_floating.source=detect";
      "Mod+Shift+S".spawn-sh = "${pkgs.wl-kbptr}/bin/wl-kbptr -o modes=floating,click -o mode_floating.source=detect -o mode_click.button=right";

      XF86AudioRaiseVolume = {
        _props.allow-when-locked = true;
        spawn-sh = "${pkgs.wireplumber}/bin/wpctl set-volume @DEFAULT_AUDIO_SINK@ 0.05+ -l 1.0";
      };
      XF86AudioLowerVolume = {
        _props.allow-when-locked = true;
        spawn-sh = "${pkgs.wireplumber}/bin/wpctl set-volume @DEFAULT_AUDIO_SINK@ 0.05-";
      };
      XF86AudioMute = {
        _props.allow-when-locked = true;
        spawn-sh = "${pkgs.wireplumber}/bin/wpctl set-mute @DEFAULT_AUDIO_SINK@ toggle";
      };
      XF86AudioMicMute = {
        _props.allow-when-locked = true;
        spawn-sh  = "${pkgs.wireplumber}/bin/wpctl set-mute @DEFAULT_AUDIO_SOURCE@ toggle";
      };
      XF86AudioPlay = {
        _props.allow-when-locked = true;
        spawn-sh = "${pkgs.playerctl}/bin/playerctl play-pause";
      };
      XF86AudioStop = {
        _props.allow-when-locked = true;
        spawn-sh = "${pkgs.playerctl}/bin/playerctl stop";
      };
      XF86AudioPrev = {
        _props.allow-when-locked = true;
        spawn-sh = "${pkgs.playerctl}/bin/playerctl previous";
      };
      XF86AudioNext = {
        _props.allow-when-locked = true;
        spawn-sh = "${pkgs.playerctl}/bin/playerctl next";
      };
      XF86MonBrightnessUp = {
        _props.allow-when-locked = true;
        spawn-sh = "${pkgs.brightnessctl}/bin/brightnessctl --class=backlight set +5%";
      };
      XF86MonBrightnessDown = {
        _props.allow-when-locked = true;
        spawn-sh = "${pkgs.brightnessctl}/bin/brightnessctl --class=backlight set 5%-";
      };

      # Open/close the Overview: a zoomed-out view of workspaces and windows.
      # You can also move the mouse into the top-left hot corner,
      # or do a four-finger swipe up on a touchpad.
      # "Mod" = {
      #   _props = { repeat = false; release = true; };
      #   toggle-overview = {};
      # };
      "Mod+O".toggle-overview = {};

      "Alt+F4" = {
        _props.repeat = false;
        close-window = {};
      };
      "Mod+BackSpace" = {
        _props.repeat = false;
        close-window = {};
      };

      "Mod+T".toggle-column-tabbed-display = {};

      "Mod+Left".focus-column-left = {};
      "Mod+Right".focus-column-right = {};
      "Mod+Up".focus-window-up = {};
      "Mod+Down".focus-window-down = {};

      "Ctrl+Mod+Left".move-column-left = {};
      "Ctrl+Mod+Right".move-column-right = {};
      "Ctrl+Mod+Up".move-window-up = {};
      "Ctrl+Mod+Down".move-window-down = {};

      "Ctrl+Alt+Left".focus-monitor-left = {};
      "Ctrl+Alt+Right".focus-monitor-right = {};
      "Ctrl+Alt+Up".focus-workspace-up = {};
      "Ctrl+Alt+Down".focus-workspace-down = {};

      "Mod+Home".focus-column-first = {};
      "Mod+End".focus-column-last = {};
      "Mod+Ctrl+Home".move-column-to-first = {};
      "Mod+Ctrl+End".move-column-to-last = {};

      "Shift+Mod+Left".move-column-to-monitor-left = {};
      "Shift+Mod+Right".move-column-to-monitor-right = {};
      "Shift+Mod+Up".move-column-to-workspace-up = {};
      "Shift+Mod+Down".move-column-to-workspace-down = {};

      "Mod+Shift+Page_Down".move-workspace-down = {};
      "Mod+Shift+Page_Up".move-workspace-up = {};

      "Mod+WheelScrollDown" = {
        _props.cooldown-ms = 150;
        focus-workspace-down = {};
      };
      "Mod+WheelScrollUp" = {
        _props.cooldown-ms = 150;
        focus-workspace-up = {};
      };
      "Mod+Ctrl+WheelScrollDown" = {
        _props.cooldown-ms = 150;
        move-column-to-workspace-down = {};
      };
      "Mod+Ctrl+WheelScrollUp" = {
        _props.cooldown-ms = 150;
        move-column-to-workspace-up = {};
      };

      "Mod+WheelScrollRight".focus-column-right = {};
      "Mod+WheelScrollLeft".focus-column-left = {};
      "Mod+Ctrl+WheelScrollRight".move-column-right = {};
      "Mod+Ctrl+WheelScrollLeft".move-column-left = {};

      "Mod+Shift+WheelScrollDown".focus-column-right = {};
      "Mod+Shift+WheelScrollUp".focus-column-left = {};
      "Mod+Ctrl+Shift+WheelScrollDown".move-column-right = {};
      "Mod+Ctrl+Shift+WheelScrollUp".move-column-left = {};

      "Mod+BracketLeft".consume-or-expel-window-left = {};
      "Mod+BracketRight".consume-or-expel-window-right = {};

      "Mod+Comma".consume-window-into-column = {};
      "Mod+Period".expel-window-from-column = {};

      "Mod+R".switch-preset-column-width = {};
      "Mod+Shift+R".switch-preset-window-height = {};
      "Mod+Ctrl+R".reset-window-height = {};
      "Mod+Shift+F".fullscreen-window = {};
      "Mod+Alt+F".fullscreen-window = {};

      "Mod+Ctrl+F".expand-column-to-available-width = {};

      "Mod+Minus".set-column-width = "50%";
      "Mod+Equal".set-column-width = "100%";
      "Mod+Shift+Minus".set-column-width = "-25%";
      "Mod+Shift+Equal".set-column-width = "+25%";
      "Mod+0".set-window-height = "+25%";
      "Mod+9".set-window-height = "-25%";

      "Mod+Backslash".toggle-window-floating = {};
      "Print".screenshot = {};
      "Mod+P".screenshot = {};
      "Ctrl+Print".screenshot-screen = {};
      "Ctrl+Mod+P".screenshot-screen = {};
      "Alt+Print".screenshot-window = {};
      "Alt+Mod+P".screenshot-window = {};

      "Mod+Escape" = {
        _props.allow-inhibiting = false;
        toggle-keyboard-shortcuts-inhibit = {};
      };

      "Mod+Shift+E".quit = {};
      "Ctrl+Alt+Delete".quit = {};
    } // (let
      # Inspired by: https://github.com/niri-wm/niri/discussions/2769
      move-column-to-new-workspace-ARG = arg: pkgs.writeShellScript "move-column-to-new-workspace" ''
        idx=$(niri msg --json workspaces \
          | ${pkgs.yq-go}/bin/yq '.[] | select (.is_focused) | .idx')
        niri msg action move-column-to-workspace 1
        niri msg action move-workspace-to-index $((idx${arg}))
      '';
      move-column-to-new-workspace-up = move-column-to-new-workspace-ARG "";
      move-column-to-new-workspace-down = move-column-to-new-workspace-ARG "+1";
      new-empty-workspace = delta: pkgs.writeShellScript "new-empty-workspace" ''
        set -euo pipefail
        exec {lock}>"$XDG_RUNTIME_DIR/niri-empty-workspace.lock"
        ${pkgs.util-linux}/bin/flock "$lock"
        ws=$(niri msg -j workspaces)
        idx=$(printf '%s\n' "$ws" | ${pkgs.yq-go}/bin/yq -r '.[] | select(.is_focused) | .idx')
        output=$(printf '%s\n' "$ws" | ${pkgs.yq-go}/bin/yq -r '.[] | select(.is_focused) | .output')
        last=$(printf '%s\n' "$ws" | ${pkgs.yq-go}/bin/yq -r \
          '(.[] | select(.is_focused) | .output) as $monitor | .[] | select(.output == $monitor) | .idx' \
          | sort -n | tail -1)
        [[ "$idx" =~ ^[0-9]+$ && "$last" =~ ^[0-9]+$ && -n "$output" ]]
        name="__niri-empty-$$"
        niri msg action set-workspace-name "$name" --workspace "$last"
        prior_name=""
        cleanup() {
          if [[ -n "$prior_name" && "$prior_name" != null ]]; then
            niri msg action set-workspace-name "$prior_name" --workspace "$name"
          else
            niri msg action unset-workspace-name "$name"
          fi
        }
        trap cleanup EXIT
        named=$(niri msg -j workspaces)
        named_output=$(printf '%s\n' "$named" | NIRI_WS_NAME="$name" ${pkgs.yq-go}/bin/yq -r '.[] | select(.name == strenv(NIRI_WS_NAME)) | .output')
        named_id=$(printf '%s\n' "$named" | NIRI_WS_NAME="$name" ${pkgs.yq-go}/bin/yq -r '.[] | select(.name == strenv(NIRI_WS_NAME)) | .id')
        [[ "$named_id" =~ ^[0-9]+$ ]]
        prior_name=$(printf '%s\n' "$ws" | NIRI_WS_ID="$named_id" ${pkgs.yq-go}/bin/yq -r '.[] | select(.id == env(NIRI_WS_ID)) | .name')
        [[ "$named_output" == "$output" ]]
        occupied=$(niri msg -j windows | ${pkgs.yq-go}/bin/yq -r ".[] | select(.workspace_id == $named_id) | .id")
        [[ -z "$occupied" ]]
        niri msg action move-workspace-to-index "$((idx + ${toString delta}))" --reference "$name"
        niri msg action focus-workspace "$name"
        cleanup
        trap - EXIT
      '';
    in {
      "Ctrl+Shift+Mod+Up".spawn = toString move-column-to-new-workspace-up;
      "Ctrl+Shift+Mod+Down".spawn = toString move-column-to-new-workspace-down;

      "Ctrl+Shift+Alt+Up" = {
        _props.repeat = false;
        spawn = toString (new-empty-workspace 0);
      };
      "Ctrl+Shift+Alt+Down" = {
        _props.repeat = false;
        spawn = toString (new-empty-workspace 1);
      };
    });
  };
}
{ ... }: {
  imports = [
    ./binds.nix
  ];
  wayland.windowManager.niri.settings = {
    # Ghostty's OSC 777 notification action selects the right Pi tab, but
    # niri 26.04 rejects the window activation under its default serial check.
    # Trade-off: apps can steal focus with invalid-serial tokens. This niri
    # debug option is not covered by its config stability policy.
    # Remove when clicking a Pi notification from another workspace and tab
    # works without this flag, or replace it with a Ghostty-only
    # on-xdg-activate rule once our niri supports that rule (26.04 does not).
    #
    # noctalia also need this: Allows notification actions and window activation from Noctalia.
    debug.honor-xdg-activation-with-invalid-serial = {};

    prefer-no-csd = {};
    output = {
      _args = ["eDP-1"];
      scale = 2.0;
    };
    input = {
      touchpad = {
        tap = {};
      };
    };
    layout = {
      gaps = 0;
      focus-ring.off = {};
      shadow = {
        on = {};
        spread = 2;
        offset._props = {x=2; y=2;};
      };
      empty-workspace-above-first = {};
    };
    window-rule = {
      match._props.is-focused = false;
      clip-to-geometry = true ;
      # geometry-corner-radius._args= [12 36 36 12];
      geometry-corner-radius = 64;
    };
    spawn-at-startup = ["noctalia"];
    screenshot-path = "~/Pictures/Screenshots/niri.%Y%m%d.%H%M%S.png";
    gestures.hot-corners.off = {};
    overview.zoom = 0.4;
    switch-events = {
      lid-close.spawn = ["dms" "ipc" "lock" "lock"];
    };
    cursor = {
      hide-when-typing = {};
    };
  };
}
{ pkgs, config, ... }: {
  imports = [
    ./config
    ./win_align.nix
    ./focus-shrink
  ];
  wayland.windowManager.niri.enable = true;
  cachix_packages = [ config.wayland.windowManager.niri.package ];
  services.gnome-keyring.enable = true;

  home.packages = [
    pkgs.adwaita-icon-theme
    pkgs.papirus-icon-theme
  ];
  wayland.windowManager.niri.settings = {
    cursor = {
      xcursor-theme = "Adwaita";
      xcursor-size = 24;
    };
  };
}
{ ... }: {
  nixpkgs.overlays = [
    (self: super: {
      niri = super.niri.overrideAttrs (old: {
        patches = (old.patches or []) ++ [
          # https://github.com/niri-wm/niri/discussions/1380
          ./main.patch
        ];
      });
    })
  ];
  wayland.windowManager.niri.settings = {
    animations.window-focus = {
      on-keyboard = {};
      on-mouse = false;
      window-switch-only = {};
      scale = 0.9;
      duration-ms = 300;
      curve = "ease-out-cubic";
    };
    binds = {
      "Mod+Z".animate-window = {};
    };
  };
}
{ pkgs, ... }: {
  nixpkgs.overlays = [
    (self: super: {
      niri = super.niri.overrideAttrs (old: {
        patches = (old.patches or []) ++ [
          # [feat: add column alignment actions #3033](https://github.com/niri-wm/niri/pull/3033)
          (pkgs.fetchurl {
            name = "column-alignment";
            url = "https://github.com/niri-wm/niri/commit/7ac6abd0b42422bc79c2a67309c16bbb2be48176.patch";
            sha256 = "sha256-5+3R97TyBFF9KP+1ECpiMdvedxWllHXepvGY064cNAw=";
          })
          (pkgs.fetchurl {
            name = "column-alignment-floating-fix";
            url = "https://github.com/niri-wm/niri/commit/7aa5e4cab76eb6164bc930336cb6ac7bdd362668.patch";
            sha256 = "sha256-Fx3x2hhBxW2UmYbJVL96ZgxaPWK1oSE2Uzm6qywFFqE=";
          })
        ];
      });
    })
  ];
  wayland.windowManager.niri.settings = {
    binds = {
      "Mod+Semicolon".align-column-left = {};
      "Mod+Apostrophe".align-column-right = {};
    };
  };
}
# We want to edit the remote ICS files before feed them to Noctalia.
# So we need to fetch ICS files by ourselves,
# that is why we utilize systemd timer.
{ lib, pkgs, config, ... }:
let
  feeds = [ "cal_holiday_1" "cal_solarTerm" "cal_lunar" ];
  calendarDir = "${config.home.homeDirectory}/.local/share/calendars";
  fetchCalendars = pkgs.writeShellScript "noctalia-calendar-ics" ''
    failed=0
    for feed in ${lib.concatStringsSep " " feeds}; do
      (
        dir="${calendarDir}/$feed"
        ${pkgs.coreutils}/bin/mkdir -p "$dir"
        raw=$(${pkgs.coreutils}/bin/mktemp "$dir/.raw.XXXXXX.tmp")
        out=$(${pkgs.coreutils}/bin/mktemp "$dir/.calendar.XXXXXX.tmp")
        trap '${pkgs.coreutils}/bin/rm -f "$raw" "$out"' EXIT

        ${pkgs.curl}/bin/curl --fail --location --silent --show-error \
          --connect-timeout 10 --max-time 60 --retry 2 \
          -o "$raw" "https://yangh9.github.io/ChinaCalendar/$feed.ics" || exit 1
        ${pkgs.gnugrep}/bin/grep -q '^BEGIN:VCALENDAR' "$raw" &&
          ${pkgs.gnugrep}/bin/grep -q '^BEGIN:VEVENT' "$raw" &&
          ${pkgs.gnugrep}/bin/grep -q '^END:VCALENDAR' "$raw" || exit 1
        ${pkgs.gnused}/bin/sed -e '/^SUMMARY[:;]/s/[「」『』]//g' \
          -e 's/^\(SUMMARY:\)\([^ ]*月\) \([^ ]*\)/\1\3 \2/' "$raw" > "$out" || exit 1
        ${pkgs.coreutils}/bin/mv -f "$out" "$dir/calendar.ics"
      ) || failed=1
    done
    exit "$failed"
  '';
in {
  systemd.user.services.noctalia-calendar-ics = {
    Unit.Description = "Fetch and edit ChinaCalendar ICS feeds";
    Service = {
      Type = "oneshot";
      ExecStart = fetchCalendars;
    };
  };
  systemd.user.timers.noctalia-calendar-ics = {
    Unit.Description = "Refresh ChinaCalendar ICS feeds hourly";
    Timer = {
      OnCalendar = "hourly";
      Persistent = true;
    };
    Install.WantedBy = [ "timers.target" ];
  };
  programs.noctalia.settings.calendar.account = {
    cal_holiday_1 = {
      type = "vdir";
      color = "#B85450";
      name = "法定节假日";
      path = "${calendarDir}/cal_holiday_1";
    };
    cal_solarTerm = {
      type = "vdir";
      color = "#82B366";
      name = "二十四节气";
      path = "${calendarDir}/cal_solarTerm";
    };
    cal_lunar = {
      type = "vdir";
      color = "#666666";
      name = "农历、天干地支";
      path = "${calendarDir}/cal_lunar";
    };
  };
}
{ lib, ... }: {
  imports = [
    ./event-titles
    ./china-calendar.nix
  ];
  programs.noctalia.settings = {
    calendar = {
      enabled = true;
      event_date_format = "%B %e %A";
    };
    calendar.reminders = {
      default_lead_minutes = 3; # min
      all_day_digest_time = "08:00";
    };
    calendar.account.outlook = {
      type = "ics";
      name = "xieby1 Outlook";
      server_url = lib.trim (builtins.readFile ~/Gist/Vault/calendars/outlook.txt);
    };
    calendar.account.outlook_kxh = {
      type = "ics";
      color = "on_tertiary";
      name = "KXH Outlook";
      server_url = lib.trim (builtins.readFile ~/Gist/Vault/calendars/outlook_kxh.txt);
    };

    # Filters are evaluated in filter_order; the first matching enabled filter wins:
    # https://docs.noctalia.dev/noctalia/v5.5.0/services/notifications/#filtering
    notification.filter_order = [ "calendar-lunar" "calendar" ];
    notification.filter.calendar-lunar = {
      match = "Calendar";
      # Match a lunar title in either a reminder summary or one line of an all-day digest body.
      match_content = "(^|\\n)[^ \\n]+ [^ \\n]+月 [0-9]{4}年(\\n|$)";
      # Calendar reminders are persistent by default; use the standard 6000 ms timeout for lunar ones.
      allow_permanent = false;
    };
    notification.filter.calendar = {
      match = "Calendar";
      override_duration = 0;
    };
  };
}
{ ... }: {
  nixpkgs.overlays = [
    (self: super: {
      noctalia = super.noctalia.overrideAttrs (old: {
        patches = (old.patches or []) ++ [
          ./main.patch
        ];
      });
    })
  ];
}
{ config, ... }: {
  imports = [
    ./settings.nix
    ./plugins
  ];
  programs.noctalia = {
    enable = true;
  };
  cachix_packages = [ config.programs.noctalia.package ];
  xdg.desktopEntries.noctalia-settings = {
    name = "Noctalia Settings";
    exec = "noctalia msg settings-open";
    icon = "noctalia";
  };
}
{ lib, ... }: {
  programs.noctalia.settings = {
    bar.default.start = lib.mkBefore ["daily-wallpaper"];
    plugins = {
      enabled = [
        "nzlov/daily-wallpaper"
      ];
    };
    widget.daily-wallpaper = {
      type = "nzlov/daily-wallpaper:widget";
      show_text = false;
    };
  };
}
{ ... }: {
  imports = [
    ./daily-wallpaper.nix
    ./pi-noctalia
    ./niri-displays.nix
  ];
}
{ ... }: {
  programs.noctalia.settings = {
    plugins = {
      enabled = [
        "raycursive/niri-displays"
      ];
    };
  };
  xdg.desktopEntries.niri-displays = {
    name = "Noctalia Niri Displays";
    exec = "noctalia msg panel-toggle raycursive/niri-displays:panel";
    icon = "noctalia";
  };
}
{ lib, ... }: let
  src = (import <npins> { input = ./sources.json; }).pi-noctalia;
in {
  home.file.".pi/agent/extensions/pi-noctalia".source = src + "/pi-extension";
  home.file.".local/share/noctalia/plugins/pi-noctalia".source = src + "/noctalia-plugin";
  programs.noctalia.settings = {
    bar.default = {
      start = lib.mkAfter [ "pi-noctalia" ];
    };
    plugins = {
      enabled = [ "local/pi-noctalia" ];
    };
    widget.pi-noctalia = {
      type = "local/pi-noctalia:widget";
      max_visible = 3;
    };

    notification.filter_order = [ "pi" ];
    notification.filter.pi = {
      match_content = "^Pi";
      override_duration = 0;
    };
  };
  wayland.windowManager.niri.settings = {
    binds = {
      "Mod+A".spawn-sh = "noctalia msg panel-toggle local/pi-noctalia:sessions";
    };
  };
}
{ ... }: {
  imports = [
    ./calendar
  ];
  programs.noctalia.settings = {
    bar.default = {
      radius = 0;
      smart_auto_hide = true;
      auto_hide_reserve_space = true;
      margin_ends = 0;
      start = [
        "notifications"
        "taskbar"
      ];
      center = [
        # "active_window"
        "clock_date"
        "clock_time"
        "clock_weekday"
        "weather"
      ];
      end = [
        "media"
        "tray"
        "cpu" "ram" "ram_pct" "swap_pct" "disk_used" "disk_used_pct"
        "network_tx" "network_rx"
        "output_volume"
        "bluetooth"
        "network"
        "battery"
        "control-center"
      ];
    };
    location.address = "shenzhen";

    widget.taskbar = {
      group_by_workspace = true;
      hide_empty_workspaces = true;
      show_workspace_label = false;
      workspace_group_inactive_border_color = "surface";
    };

    widget.clock_date = {
      type = "clock";
      format = "{:%Y.%m.%d}";
    };
    widget.clock_time = {
      type = "clock";
      format = "{:%H:%M}";
      anchor = true;
      font_weight = 700;
    };
    widget.clock_weekday = {
      type = "clock";
      format = "{:%a}";
    };
    widget.weather = {
      show_condition = false;
    };

    widget.media = {
      album_art_only = true;
      rotate_album_art = true;
      hide_when_no_media = true;
      actions = {
        left = "media toggle";
        right = "panel-toggle control-center media";
      };
    };
    widget.cpu = {
      show_glyph = false;
      visualization = "none";
    };
    widget.ram = {
      visualization = "none";
      show_glyph = false;
    };
    widget.ram_pct = {
      type = "sysmon";
      stat = "ram_pct";
      visualization = "none";
      show_glyph = false;
    };
    widget.swap_pct = {
      type = "sysmon";
      stat = "swap_pct";
      visualization = "none";
      show_glyph = false;
    };
    widget.disk_used = {
      type = "sysmon";
      stat = "disk_used";
      visualization = "none";
      show_glyph = false;
    };
    widget.disk_used_pct = {
      type = "sysmon";
      stat = "disk_used_pct";
      visualization = "none";
      show_glyph = false;
    };
    widget.network_tx = {
      label_min_width = 32;
      network_speed_compact = true;
      network_speed_unit = "mb";
      visualization = "none";
      show_glyph = false;
    };
    widget.network_rx = {
      label_min_width = 32;
      network_speed_compact = true;
      network_speed_unit = "mb";
      visualization = "none";
      show_glyph = false;
    };
    widget.network = {
      show_label = false;
    };
    widget.output_volume = {
      show_label = false;
    };
    widget.battery = {
      display_mode = "graphic";
    };

    shell = {
      clipboard_auto_paste = "off";
      clipboard_history_max_entries = 10000;
    };

    idle.behavior.lock = {
      action = "lock";
      enabled = true;
      timeout = 600;
    };
    idle.behavior.screen-off = {
      action = "screen_off";
      enabled = true;
      timeout = 660;
    };
    idle.behavior.lock-and-suspend = {
      action = "lock_and_suspend";
      enabled = false;
    };
    osd.kinds = {
      keyboard_layout = false;
    };

    shell.launcher = {
      default_view = "all";
    };

    control_center = {
      width = 1200;
      shortcuts = [
        {type = "wifi";}
        {type = "bluetooth";}
        {type = "dark_mode";}
        {type = "session";}
      ];
    };
  };
}
{ pkgs, ... }: {
  imports = [
    ./mime.nix
    ./kdeconnect.nix
    ./xdot.nix
    ./firefox
    ./warpd.nix
    ./rustdesk.nix
    ./terminal
    ./fonts.nix
    ./cheatsheet_edit.nix
    ./xcolor.nix
    ./drawio.nix
    ./flameshot.nix
    ./fcitx5
    ./de
    ./low-battery-notify.nix
    ./xingyao-audio
    ./dingtalk
  ];

  xdg.mimeApps = {
    enable = true;
    defaultApplications = {
      "application/pdf" = [ "org.gnome.Evince.desktop" ];
      "image/jpeg" = [ "org.gnome.Loupe.desktop" ];
      "image/png" = [ "org.gnome.Loupe.desktop" ];
      "image/gif" = [ "org.gnome.Loupe.desktop" ];
      "image/webp" = [ "org.gnome.Loupe.desktop" ];
      "image/tiff" = [ "org.gnome.Loupe.desktop" ];
      "image/bmp" = [ "org.gnome.Loupe.desktop" ];
      "image/svg+xml" = [ "org.gnome.Loupe.desktop" ];
    };
  };

  home.packages = with pkgs; [
    (pkgs.writeShellScriptBin "o" ''nohup xdg-open "$@" &> /dev/null &'')
    libnotify
    # browser
    # dont ask me for keyring chromium-like browsers!
    (chromium.override {commandLineArgs="--password-store=basic";})
  ] ++ [
    # network
  ] ++ pkgs.lib.optionals (builtins.currentSystem=="x86_64-linux") [
    feishu
    wechat
    wemeet
    (pkgs.makeDesktopItem {
      name = "WemeetApp-XWayland";
      desktopName = "WemeetApp-XWayland";
      exec = "wemeet-xwayland %u";
      icon = "wemeet";
      type = "Application";
      terminal = false;
      categories = ["AudioVideo"];
      mimeTypes = ["x-scheme-handler/wemeet"];
    })
  ] ++ [
    # text
    #wpsoffice
    libreoffice
    # pi-attachments reads copied files via wl-paste on Wayland
    wl-clipboard
    # draw
    #aseprite-unfree
    inkscape
    gimp
    # viewer
    evince
    gnome-characters
    nautilus
    loupe
    gnome-calculator
    surfer
  ] ++ [
    vlc
    obsidian
  ] ++ [
    keepassxc
    # entertainment
    antimicrox
  ];
}
{ pkgs, ... }:
let
  # As there is not dingtalk in nixpkgs, so we use dingtalk in nur.
  dingtalk = pkgs.nur.repos.yakkhini.dingtalk;
in {
  home.packages = [ dingtalk ];
  # Cachix long-build-time packages, see ~/.local/state/nix-output-monitor/build-reports.csv
  # openssl: 3min+ build time)
  cachix_packages = builtins.filter (p: pkgs.lib.hasInfix "openssl" p) dingtalk.buildInputs;
}
{ pkgs, ... }: {
  home.packages = [
    pkgs.drawio
  ];
  xdg.mime.types = {
    drawio = {
      name = "draw-io";
      type = "text/draw-io";
      pattern = "*.drawio";
      defaultApp = "drawio.desktop";
    };
  };
  programs.neovim = {
    extraConfig = ''
      augroup filetype
        au! BufRead,BufNewFile *.drawio set filetype=xml
      augroup END
    '';
  };
}

Thoughts about the volume issue Failed to turn `` into a value of type f64 and my adoption of eww. I followed the link to the user's eww configuration (https://github.com/HardoMX/eww/tree/master) and discovered it hasn't been updated in three years. This made me realize there aren't many eww configuration repositories on GitHub, and most of them haven't been updated for years. Searching through his repository, I found in his hypr configuration:

(# exec-once = $HOME/.config/eww/launch_bar.sh # Change away from EWW in progress) He has switched to waybar instead. This led me to reconsider: Why does eww have so many GitHub stars, yet people seem to be abandoning it?

  • Why so many stars: eww's appearance is visually impressive, creating a great first impression for newcomers.
  • Why people leave: The documentation is lacking, and there are persistent bugs that go unfixed. So my conclusion is eww may not be a good choice for my desktop environment.

Input method

Why replace ibus with fcitx5

  • ibus mozc not support shift toggle activation
  • ibus configuration use db, not file
  • ibus cannot be configured by user (home-manager)
{ pkgs, lib, ... }: let
  # 自建拼音字典
  #   参考:https://wiki.archlinux.org/title/Fcitx5
  #         https://github.com/fcitx/libime/blob/master/tools/libime_pinyindict.cpp
  #         TLDR: libime_pinyindict:语法: 词 pin'yin 频率
  my-dict = pkgs.runCommand "my-fcitx-dict" {} ''
    DIR=$out/share/fcitx5/pinyin/dictionaries
    mkdir -p $DIR
    ${pkgs.libime}/bin/libime_pinyindict ${~/Gist/dicts/fcitx/main.txt} $DIR/main.dict
  '';
in {
  i18n.inputMethod = {
    enable = true;
    type = "fcitx5";
    fcitx5 = {
      addons = [
        pkgs.qt6Packages.fcitx5-chinese-addons
        pkgs.fcitx5-pinyin-zhwiki
        pkgs.fcitx5-mozc-ut
        pkgs.fcitx5-hangul
        my-dict
      ];
    };
  };

  imports = [ ./module ./quick-phrase-fzf ./vinput ];
  my.config-fcitx5.".config/fcitx5/config" = {
    expr.sections = {
      # Disable default super+space, shift+super+space
      "Hotkey/EnumerateGroupForwardKeys"."0" = "";
      "Hotkey/EnumerateGroupBackwardKeys"."0" = "";
      "Hotkey/TriggerKeys"."0"="Shift_L";
      "Hotkey/EnumerateForwardKeys"."0"="Super+space";
      "Hotkey/EnumerateBackwardKeys"."0"="Super+Shift+space";
    };
  };
  my.config-fcitx5.".config/fcitx5/profile" = {
    expr.sections = {
      "Groups/0" = {
        Name="Default";
        "Default Layout"="us";
      };
      "Groups/0/Items/0" = {
        Name="keyboard-us";
      };
      "Groups/0/Items/1" = {
        Name="pinyin";
      };
      "Groups/0/Items/2" = {
        Name="mozc";
      };
      "Groups/0/Items/3" = {
        Name="hangul";
      };
    };
  };
  my.config-fcitx5.".config/fcitx5/conf/classicui.conf" = {
    expr.globalSection = {
      Font=''"Sans Serif 16"'';
      MenuFont=''"Sans Serif 16"'';
      TrayFont=''"Sans Serif 16"'';
      Theme="default";
      DarkTheme="default-dark";
      # Follow system light/dark color scheme
      UseDarkTheme="True";
      # Follow system accent color if it is supported by theme and desktop
      UseAccentColor="True";
    };
  };
  my.config-fcitx5.".config/fcitx5/conf/punctuation.conf" = {
    expr.globalSection = {
      # Half width punctuation after latin letter or number
      HalfWidthPuncAfterLetterOrNumber = "False";
    };
  };
  my.config-fcitx5.".config/fcitx5/conf/chttrans.conf" = {
    expr.sections = {
      Hotkey."0" = "Alt+F";
    };
  };
  home.file.punc_mb_zh_CN = {
    source = pkgs.runCommand "punc.mb.zh_CN" {} /*bash*/ ''
      sed '/_ ——/d' ${pkgs.qt6Packages.fcitx5-chinese-addons}/share/fcitx5/punctuation/punc.mb.zh_CN > $out
      {
      cat <<APPEND
      < <
      > >
      ^ ^
      APPEND
      } >> $out
    '';
    target = ".local/share/fcitx5/punctuation/punc.mb.zh_CN";
  };

  my.config-fcitx5.".config/fcitx5/conf/pinyin.conf".expr.globalSection = {
    # Disable pre edit, as the pre edit cause feishu online sheet/doc in firefox pre-edit text duplications which is annoying.
    PreeditMode="Do not show";
  };
}
{ config, lib, ... }: {
  options = {
    my.config-fcitx5 = lib.mkOption {
      type = lib.types.attrsOf lib.types.attrs;
      default = {};
      description = ''
        The fcitx5 config files in ~/.config/fcitx5/
        The implementation is based on yq-merge module.
      '';
    };
  };
  config = {
    yq-merge = lib.mapAttrs (path: attrs: {
      # The globalSection is compulsory in lib.generators.toINIWithGlobalSection, here we change it into optional
      generator = {globalSection ? {}, sections ? {}}: lib.generators.toINIWithGlobalSection {} {inherit globalSection sections;};
      yqExtraArgs = "-o ini -p ini";
      # `yq`'s `--properties-separator '='` only works for properties files, not for INI.
      # So we manually strip spaces around `=`.
      postOnChange = ''sed -i 's/\s\+=\s\+/=/' ${path}'';
    } // attrs) config.my.config-fcitx5;
  };
}
let
  pkgs = import <nixpkgs> {};
  hm = import <home-manager/modules> {
    inherit pkgs;
    configuration = {
      imports = [
        ../.
        ../../../../yq-merge
      ];
      home = { stateVersion = "25.11"; username = "dummy"; homeDirectory = "/dummy"; };
      my.config-fcitx5.".config/fcitx5/conf/chttrans.conf" = {
        expr = {
          globalSection = {
            Engine = "OpenCC";
          };
          sections = {
            Hotkey."0" = "Alt+F";
          };
        };
      };
    };
  };
in pkgs.lib.debug.throwTestFailures { failures = pkgs.lib.runTests {
  test-onChange = let
    # TODO: modularize the test-onChange, e.g. create a standalone dummy-home generation function
    dummy-home = pkgs.runCommand "test-onChange" {} ''
      mkdir -p $out/.config/fcitx5/conf
      cd $out
      echo '[Hotkey]' > .config/fcitx5/conf/chttrans.conf
      echo '0=Miao' >> .config/fcitx5/conf/chttrans.conf
      cat > .config/fcitx5/conf/yq-merge.chttrans.conf <<EOF
      ${hm.config.home.file.".config/fcitx5/conf/chttrans.conf".text}EOF
      run() { "$@"; }
      ${hm.config.home.file.".config/fcitx5/conf/chttrans.conf".onChange}
    '';
  in {
    expr = builtins.readFile (dummy-home + /.config/fcitx5/conf/chttrans.conf);
    expected = ''
      Engine=OpenCC

      [Hotkey]
      0=Alt+F
    '';
  };
}; }
{ pkgs, ... }: let
  class = "cn.xieby1.fcitx-quick-phrase-fzf";
  quick-phrase-fzf = import ./package.nix { inherit pkgs; };
in {
  xdg.desktopEntries.quick_phrase_fzf = {
    name = "Fcitx Quick Phrase FZF";
    genericName = "Fcitx quick phrase picker";
    exec = "ghostty --class=${class} -e ${quick-phrase-fzf}/bin/quick-phrase-fzf";
    icon = ./icon.svg;
    settings.StartupWMClass = class;
  };
}
{
  pkgs ? import <nixpkgs> {}
}: pkgs.writeShellScriptBin "quick-phrase-fzf" ''
  ${pkgs.ripgrep}/bin/rg -I -N ''' \
    ${pkgs.fcitx5.src}/src/modules/quickphrase/quickphrase.d/emoji-eac.mb \
    ${pkgs.qt6Packages.fcitx5-chinese-addons.src}/im/pinyin/symbols \
    ${pkgs.fcitx5.src}/src/modules/quickphrase/quickphrase.d/latex.mb \
  | ${pkgs.fzf}/bin/fzf
''
{ pkgs, lib, ai, ... }: let
  system = pkgs.stdenv.hostPlatform.system;
  model = import ./model.nix { inherit pkgs; };
  modelName = lib.removePrefix "model.sherpa-onnx." model.modelId;
  vinput = (pkgs.flake-compat {
    src = (import <npins> {input=./sources.json;}).fcitx5-vinput;
  }).defaultNix.packages.${system}.default;
in lib.mkIf (builtins.elem system [ "x86_64-linux" "aarch64-linux" ]) {
  home.packages = [ vinput ];
  cachix_packages = [ vinput ];
  i18n.inputMethod.fcitx5.addons = [ vinput ];

  xdg.dataFile."vinput/models/sherpa-onnx/${modelName}".source = model;
  yq-merge.".config/vinput/config.json" = {
    generator = builtins.toJSON;
    expr.asr = {
      active_provider = "sherpa-onnx";
      providers = [{ id = "sherpa-onnx"; type = "local"; model = model.modelId; }];
    };
    expr.llm.providers = [{
      id = ai.default_small.provider.id;
      base_url = ai.default_small.provider.api;
      api_key = ai.default_small.provider.api_key;
    }];
    expr.scenes = {
      active_scene = "correct";
      definitions = [{
        id = "correct";
        label = "语音纠错";
        prompt = "你是语音识别后处理器。纠正同音字、错别字、标点和明显识别错误,严格保留原意和输入语言,不改变语气,不回答问题,不补充内容。";
        provider_id = ai.default_small.provider.id;
        model = ai.default_small.model.id;
        # Recent Vinput history records sent to the LLM; 0 avoids extra latency and data sharing.
        context_lines = 0;
        count = 1;
        timeout_ms = 8000;
      }];
    };
    yqExtraArgs = "-p json -o json";
    preOnChange = ''
      if [[ ! -e .config/vinput/config.json ]]; then
        run ${pkgs.coreutils}/bin/install -Dm600 \
          ${vinput}/share/fcitx5-vinput/default-config.json .config/vinput/config.json
      fi
      # yq-merge matches arrays by index; move managed entries first without losing others.
      run ${pkgs.yq-go}/bin/yq -p json -o json -i '
        (.asr.providers // []) as $providers |
        .asr.providers = (
          ([$providers[] | select(.id == "sherpa-onnx")] +
            [{"id": "sherpa-onnx"}] | unique_by(.id)) +
          [$providers[] | select(.id != "sherpa-onnx")]
        ) |
        (.llm.providers // []) as $llmProviders |
        .llm.providers = (
          ([$llmProviders[] | select(.id == "${ai.default_small.provider.id}")] +
            [{"id": "${ai.default_small.provider.id}"}] | unique_by(.id)) +
          [$llmProviders[] | select(.id != "${ai.default_small.provider.id}")]
        ) |
        (.scenes.definitions // []) as $scenes |
        .scenes.definitions = (
          ([$scenes[] | select(.id == "correct")] +
            [{"id": "correct"}] | unique_by(.id)) +
          [$scenes[] | select(.id != "correct")]
        )
      ' .config/vinput/config.json
    '';
  };

  systemd.user.services.vinput-daemon = {
    Unit = {
      Description = "Vinput Voice Input Daemon";
      After = [ "pipewire.service" ];
      X-Restart-Triggers = [ "${model}" ];
    };
    Service = {
      Type = "dbus";
      BusName = "org.fcitx.Vinput";
      ExecStart = "${vinput}/bin/vinput-daemon";
    };
    Install.WantedBy = [ "default.target" ];
  };
}
{ pkgs }: let
  modelId = "model.sherpa-onnx.x-asr-960ms-streaming-zipformer-transducer-zh-en-punct-int8";
  archive = pkgs.fetchurl {
    url = "https://github.com/k2-fsa/sherpa-onnx/releases/download/asr-models/sherpa-onnx-x-asr-960ms-streaming-zipformer-transducer-zh-en-punct-int8-2026-06-05.tar.bz2";
    hash = "sha256-CpK3mL1oAcMzx86K6/W6dpv+fz81EWmaZ4N7IohChgM=";
  };
  registry = pkgs.fetchurl {
    url = "https://raw.githubusercontent.com/xifan2333/vinput-registry/5b39b073ac1b740aaba0bf104f47202bc9285da1/registry/models.json";
    hash = "sha256-LpCZ4fDCsAK3dT1HuW1CDgwaPsVTrdKGptROjPodyac=";
  };
in pkgs.runCommand "vinput-x-asr-960ms-int8-2026-06-05" {
  nativeBuildInputs = [ pkgs.gnutar pkgs.bzip2 pkgs.jq pkgs.sentencepiece ];
  passthru = { inherit modelId; };
} ''
  mkdir -p $out
  tar -xjf ${archive} --strip-components=1 -C $out
  # Vinput expects this vocabulary, but the archive only includes the SentencePiece model.
  spm_export_vocab --model=$out/bpe.model --output_format=vocab > $out/bpe.vocab
  jq -e --arg id '${modelId}' '
    .items[] | select(.id == $id) | .vinput_model
  ' ${registry} > $out/vinput-model.json
''
let
  pkgs = import <nixpkgs> {};
  inherit (pkgs) lib;
  sharedArgs = {
    ai.default_small = {
      provider = {
        id = "jw2-deepseek";
        api = "https://example.test/v1";
        api_key = "test-key";
      };
      model.id = "deepseek-flash";
    };
  };
  hm = import <home-manager/modules> {
    inherit pkgs;
    configuration = {
      imports = [ ../. ../../../yq-merge ../../../cachix-push.nix ];
      _module.args = sharedArgs;
      home = { stateVersion = "25.11"; username = "dummy"; homeDirectory = "/dummy"; };
    };
  };
  cfg = hm.config;
  vinput = builtins.filter (p: lib.getName p == "fcitx5-vinput") cfg.i18n.inputMethod.fcitx5.addons;
  daemon = cfg.systemd.user.services.vinput-daemon or {};
in lib.debug.throwTestFailures { failures = lib.runTests {
  test-addon = {
    expr = builtins.length vinput;
    expected = 1;
  };
  test-cli-and-gui-package = {
    expr = vinput != [] && builtins.elem (builtins.head vinput) cfg.home.packages;
    expected = true;
  };
  test-daemon = {
    expr = {
      type = daemon.Service.Type or null;
      bus = daemon.Service.BusName or null;
      after = daemon.Unit.After or [];
      wantedBy = daemon.Install.WantedBy or [];
    };
    expected = {
      type = "dbus";
      bus = "org.fcitx.Vinput";
      after = [ "pipewire.service" ];
      wantedBy = [ "default.target" ];
    };
  };
  test-daemon-executable = {
    expr = vinput != [] && (daemon.Service.ExecStart or []) == [ "${builtins.head vinput}/bin/vinput-daemon" ];
    expected = true;
  };
  test-unsupported-system = let
    unsupported = import <home-manager/modules> {
      pkgs = import <nixpkgs> { system = "riscv64-linux"; };
      configuration = {
        imports = [ ./. ../../../yq-merge ../../../cachix-push.nix ];
        _module.args = sharedArgs;
        home = { stateVersion = "25.11"; username = "dummy"; homeDirectory = "/dummy"; };
      };
    };
  in {
    expr = {
      addons = unsupported.config.i18n.inputMethod.fcitx5.addons;
      daemon = unsupported.config.systemd.user.services ? vinput-daemon;
    };
    expected = { addons = []; daemon = false; };
  };
  test-managed-model = {
    expr = let
      model = cfg.xdg.dataFile."vinput/models/sherpa-onnx/x-asr-960ms-streaming-zipformer-transducer-zh-en-punct-int8".source or null;
    in model != null && (let
      manifest = builtins.fromJSON (builtins.readFile (model + "/vinput-model.json"));
    in manifest.backend == "sherpa-streaming"
      && manifest.runtime == "online"
      && manifest.language == "zh_en"
      && !(manifest.model ? sense_voice)
      && lib.all (file: builtins.pathExists (model + "/${file}")) [
        manifest.model.tokens manifest.model.bpe_vocab
        manifest.model.transducer.encoder manifest.model.transducer.decoder manifest.model.transducer.joiner
      ]);
    expected = true;
  };
  test-sensevoice-no-longer-managed = {
    expr = cfg.xdg.dataFile ? "vinput/models/sherpa-onnx/sense-voice-zh-en-ja-ko-yue-int8";
    expected = false;
  };
  test-selected-provider = {
    expr = cfg.yq-merge.".config/vinput/config.json".expr.asr.active_provider or null;
    expected = "sherpa-onnx";
  };
  test-llm-provider = {
    expr = cfg.yq-merge.".config/vinput/config.json".expr.llm.providers or null;
    expected = [{
      id = "jw2-deepseek";
      base_url = "https://example.test/v1";
      api_key = "test-key";
    }];
  };
  test-correction-scene = let
    scenes = cfg.yq-merge.".config/vinput/config.json".expr.scenes;
    scene = builtins.head scenes.definitions;
  in {
    expr = {
      active = scenes.active_scene;
      inherit (scene) id provider_id model context_lines count timeout_ms;
      hasPrompt = scene.prompt != "";
    };
    expected = {
      active = "correct";
      id = "correct";
      provider_id = "jw2-deepseek";
      model = "deepseek-flash";
      context_lines = 0;
      count = 1;
      timeout_ms = 8000;
      hasPrompt = true;
    };
  };
  test-model-selection-triggers-activation = {
    expr = lib.hasInfix "model.sherpa-onnx.x-asr-960ms-streaming-zipformer-transducer-zh-en-punct-int8"
      (cfg.home.file.".config/vinput/config.json".text or "");
    expected = true;
  };
  test-config-merge = {
    expr = if !(cfg.home.file ? ".config/vinput/config.json") then false else let
      file = cfg.home.file.".config/vinput/config.json";
      result = pkgs.runCommand "test-vinput-config-merge" { nativeBuildInputs = [ pkgs.jq ]; } ''
        export HOME=$TMPDIR/home
        mkdir -p "$HOME/.config/vinput"
        cd "$HOME"
        cp ${pkgs.writeText "vinput-settings.json" file.text} ${file.target}
        run() { "$@"; }
        apply() {
          ${file.onChange}
        }
        apply
        test -w .config/vinput/config.json
        jq -e '.asr.active_provider == "sherpa-onnx" and
          .asr.providers[0].model == "model.sherpa-onnx.x-asr-960ms-streaming-zipformer-transducer-zh-en-punct-int8" and
          .scenes.active_scene == "correct" and
          .scenes.definitions[0].model == "deepseek-flash"' .config/vinput/config.json
        for providers in \
          '[{"id":"cloud","type":"command","env":{"TOKEN":"keep"}}]' \
          '[{"id":"cloud","type":"command","env":{"TOKEN":"keep"}},{"id":"sherpa-onnx","type":"local","timeout_ms":27000,"model":"model.sherpa-onnx.sense-voice-zh-en-ja-ko-yue-int8"}]'; do
          jq -n --argjson providers "$providers" \
            '{global:{capture_device:"keep-mic"},asr:{active_provider:"cloud",providers:$providers},llm:{providers:[{id:"custom-llm",base_url:"https://custom.test",api_key:"keep-llm"}]},scenes:{active_scene:"custom",definitions:[{id:"custom",prompt:"keep",provider_id:"cloud",model:"custom-model"},{id:"__raw__",count:0}]}}' \
            > .config/vinput/config.json
          apply
          apply
          jq -e '.global.capture_device == "keep-mic" and
            .asr.active_provider == "sherpa-onnx" and
            ([.asr.providers[] | select(.id == "cloud")][0].env.TOKEN == "keep") and
            ([.asr.providers[] | select(.id == "sherpa-onnx")] | length == 1) and
            ([.asr.providers[] | select(.id == "sherpa-onnx")][0].model ==
              "model.sherpa-onnx.x-asr-960ms-streaming-zipformer-transducer-zh-en-punct-int8") and
            ([.llm.providers[] | select(.id == "custom-llm")][0].api_key == "keep-llm") and
            ([.llm.providers[] | select(.id == "jw2-deepseek")] | length == 1) and
            .scenes.active_scene == "correct" and
            ([.scenes.definitions[] | select(.id == "custom")][0].prompt == "keep") and
            ([.scenes.definitions[] | select(.id == "__raw__")] | length == 1) and
            ([.scenes.definitions[] | select(.id == "correct")] | length == 1)' .config/vinput/config.json
        done
        jq -e '[.asr.providers[] | select(.id == "sherpa-onnx")][0].timeout_ms == 27000' .config/vinput/config.json
        echo ok > $out
      '';
    in builtins.readFile result == "ok\n";
    expected = true;
  };
  test-existing-addons = {
    expr = lib.all (p: builtins.elem p cfg.i18n.inputMethod.fcitx5.addons) [
      pkgs.qt6Packages.fcitx5-chinese-addons pkgs.fcitx5-pinyin-zhwiki
      pkgs.fcitx5-mozc-ut pkgs.fcitx5-hangul
    ];
    expected = true;
  };
}; }
2022.05.11

安装deb包,以飞书为例

太长不看

  • nix文件: https://github.com/xieby1/nix_config/blob/main/usr/gui/feishu.nix
  • 使用方法:
    home.packages = with pkgs; [
      (callPackage ./feishu.nix {})
    ];
    

参考nixpkgs/pkgs/applications/networking/instant-messengers/skypeforlinux/default.nix

测试环境

nix-build -E "with import {}; callPackage ./default.nix {}"

权限问题

nix-build遇到dpkg -x解压失败。 但是手动执行dpkg -x一切正常。

https://unix.stackexchange.com/questions/138188/easily-unpack-deb-edit-postinst-and-repack-deb

确认是权限问题的实验

是s权限的问题。 nix-build下不能添加s权限。 原因未知

复现方法

touch $out/miao
chmox +s $out/miao
ls -l $out/miao

解决方法,使用fakeroot.

补全库

使用ldd脚本,获取所有elf所需的库,挨个添加进rpath即可。

桌面

application/.desktop menu/.menu // 负责图标

firefox-apps

Comparison of chromium-based browsers and firefox

  • list windows: wmctrl -l
  • list windows properties: xprop -name <WIN_NAME> [PROP]

second instance of chrome ignores --class

  • bing: chrome wm_class new instance
    • https://superuser.com/questions/1457060/how-can-you-start-two-chrome-windows-with-different-wm-class-attributes
      • https://issues.chromium.org/issues/40172351
      • 目前看来最好的方法:--user-data-dir
      • firefox类似,用不同的profile

https://superuser.com/questions/1770285/custom-firefox-profiles-with-different-wm-class-and-icons

set WM_CLASS

  • https://stackoverflow.com/questions/36650865/set-wm-class-with-wnck-xprop-or-something-else 能正常设置kitty的WM_CLASS,但是为什么chrome不行?

所以选择firefox!

{ config, pkgs, ... }: {
  imports = [
    ./module.nix
    ./single-tab.nix
  ];

  firefox-apps = [{
    name = "ms-todo";
    url = "https://to-do.live.com/";
    desktopEntryExtras = {
      name = "Microsoft To Do";
    };
  }{
    name = "ms-calendar";
    url = "https://outlook.live.com/calendar";
    desktopEntryExtras = {
      name = "Microsoft Calendar";
      genericName = "outlook calendar mail";
    };
  }{
    name = "webweixin";
    url = "https://wx.qq.com";
    desktopEntryExtras = {
      name = "网页微信";
      genericName = "weixin";
    };
  }{
    # TODO: move to cheatsheet.nix
    name = "my_cheatsheet_html";
    url = "${config.home.homeDirectory}/Docs/Tech/my_cheatsheet/index.html";
    desktopEntryExtras = {
      name = "Cheatsheet HTML";
      genericName = "cheatsheet";
      icon = builtins.toFile "cheatsheet.svg" ''
        <svg width="64" height="64" xmlns="http://www.w3.org/2000/svg">
          <rect width="100%" height="100%" rx="20%" ry="20%" fill="#666666"/>
          <text x="50%" y="50%" text-anchor="middle" dominant-baseline="middle" font-size="18" font-weight="bold" fill="#F5F5F5">
            <tspan x="50%" dy="-0.6em">CS</tspan>
            <tspan x="50%" dy="1.2em">html</tspan>
          </text>
        </svg>
      '';
    };
  }{
    name = "bing_dict";
    url = "https://cn.bing.com/dict";
    desktopEntryExtras = {
      name = "Bing Dict";
      genericName = "dictionary";
    };
  }{
    name = "riyucidian";
    url = "https://www.mojidict.com";
    desktopEntryExtras = {
      name = "日语词典";
    };
  }{
    name = "devdocs";
    url = "https://devdocs.io";
    desktopEntryExtras = {
      name = "DevDocs";
    };
  }(let
    metacubexd = builtins.fetchTarball "https://github.com/MetaCubeX/metacubexd/archive/gh-pages.zip";
  in {
    name = "clash";
    url = "${metacubexd}/index.html";
    desktopEntryExtras = {
      icon = "${metacubexd}/pwa-192x192.png";
    };
  }){
    name = "ai";
    url = "https://web.chatboxai.app";
    desktopEntryExtras = {
      name = "AI Chatbox";
    };
  }{
    name = "deepseek";
    url = "https://chat.deepseek.com";
    desktopEntryExtras = {
      name = "DeepSeek";
    };
  }{
    name = "doubao";
    url = "https://www.doubao.com/chat";
    desktopEntryExtras = {
      name = "豆包";
    };
  }{
    name = "spotify";
    url = "https://open.spotify.com/search";
    desktopEntryExtras = {
      name = "Spotify (Search)";
    };
  }{
    name = "syncthing";
    url = "http://127.0.0.1:8384";
    icon = "${pkgs.syncthing}/share/icons/hicolor/scalable/apps/syncthing.svg";
  }{
    name = "emojidb";
    url = "https://emojidb.org";
    desktopEntryExtras = {
      name = "EmojiDB";
    };
  }{
    name = "wangyiyunyinyue-wyyyy";
    url = "https://music.163.com";
    desktopEntryExtras = {
      name = "网易云音乐";
    };
  }{
    name = "sixu";
    url = "https://xieby1.cn/sixu/xby/";
    icon = (import <npins> {input=../../../cli/server/sources.json;}).sixu + /src/app/ui/web/frontend/public/sixu-icon.svg;
  }{
    name = "circle";
    url = "https://xieby1.cn/circle/xby/";
    icon = (import <npins> {input=../../../cli/server/sources.json;}).circle + /src/ui/web/render/public/icon.svg;
  }];
}

firefox module

{ config, pkgs, lib, ... }: let
  singleton = pkgs.writeShellApplication {
    name = "singleton.sh";
    runtimeInputs = with pkgs; [ jq niri ];
    text = builtins.readFile ./singleton.sh;
  };
in {
  options = {
    firefox-apps = lib.mkOption {
      type = lib.types.listOf (lib.types.submodule {
        options = {
          name = lib.mkOption {
            type = lib.types.str;
            default = null;
          };
          url = lib.mkOption {
            type = lib.types.str;
            default = null;
          };
          icon = lib.mkOption {
            type = lib.types.nullOr lib.types.path;
            default = null;
          };
          enableDesktopEntry = lib.mkOption {
            type = lib.types.bool;
            default = true;
          };
          desktopEntryExtras = lib.mkOption {
            type = lib.types.attrs;
            default = {};
            description = "extra settings for desktopEntry, see xdg.desktopEntries.<xxx>";
          };
        };
      });
    };
  };

  config = {
    programs.firefox.profiles = builtins.listToAttrs (
      lib.imap1 (i: firefox-app: {
        name = assert firefox-app.name!=null; firefox-app.name;
        value = {
          id = i;
          extensions.packages = with pkgs.nur.repos.rycee.firefox-addons; [
            # auto open all windows in fullscreen mode
            i-auto-fullscreen
            darkreader
            vimium
            ublock-origin
          ];
          settings = {
            # https://superuser.com/questions/1483037/making-firefox-fullscreen-like-without-actually-maximizing-the-window
            # the full screen hotkey/button will trigger fullscreen like normal, except it won't resize the window.
            "full-screen-api.ignore-widgets" = true;
            # Automatically enable extensions
            "extensions.autoDisableScopes" = 0;
            # https://stackoverflow.com/questions/51081754/cross-origin-request-blocked-when-loading-local-file
            "security.fileuri.strict_origin_policy" = false;
            # enable userChrome.css
            "toolkit.legacyUserProfileCustomizations.stylesheets" = true;
            # disable extensions auto update
            "extensions.update.enabled" = false;
          };
          userChrome = ''
            /* [Disabling the mouseover to reveal the address/toolbar while in fullscreen - old method doesn't work](https://support.mozilla.org/en-US/questions/1324666) */
            /* [prevent firefox from showing the address bar in fullscreen mode](https://support.mozilla.org/en-US/questions/1323320) */
            *|div#fullscr-toggler {display:none!important;}
          '';
        };
      }) config.firefox-apps
    );

    xdg.desktopEntries = let
      firefox-apps-with-desktopEntry = (builtins.filter (firefox-app: firefox-app.enableDesktopEntry) config.firefox-apps);
    in builtins.listToAttrs (
      map (firefox-app: {
        name = assert firefox-app.name!=null; firefox-app.name;
        value = {
          name = firefox-app.name;
          genericName = firefox-app.name;
          exec = assert firefox-app.url!=null;
            "${singleton}/bin/singleton.sh ${firefox-app.name} firefox -P ${firefox-app.name} --name ${firefox-app.name} ${firefox-app.url}";
          icon = if firefox-app.icon != null then firefox-app.icon
          else builtins.fetchurl {
            url = "http://www.google.com/s2/favicons?domain=${firefox-app.url}&sz=128";
            name = "${firefox-app.name}.png";
          };
          settings = {
            StartupWMClass = firefox-app.name;
          };
        } // firefox-app.desktopEntryExtras;
      }) firefox-apps-with-desktopEntry
    );
  };
}
{ pkgs, ... }: let
  name = "firefox-single-tab";
in {
  imports = [
    (import ../extensions/smart-toc.nix name)
  ];
  firefox-apps = [{
    inherit name;
    url = "";
    icon = builtins.toFile "${name}.svg" ''
      <svg width="64" height="64" xmlns="http://www.w3.org/2000/svg">
        <rect width="100%" height="100%" rx="20%" ry="20%" fill="white"/>
        <text x="50%" y="50%" text-anchor="middle" dominant-baseline="middle" font-size="14" font-weight="bold" fill="#6155d2">
          <tspan x="50%" dy="-1em">Firefox</tspan>
          <tspan x="50%" dy="1em">Single</tspan>
          <tspan x="50%" dy="1em">Tab</tspan>
        </text>
      </svg>
    '';
  }];

  home.packages = map (n: (
    # https://superuser.com/questions/1770285/custom-firefox-profiles-with-different-wm-class-and-icons
    pkgs.writeScriptBin n ''
      nohup firefox -P ${name} --name ${name} --new-window "$@" &> /dev/null &
    ''
  )) [name "single-tab"];
}

firefox configurations

{ pkgs, config, ... }:
{
  imports = [
    ./apps
    ./extensions
  ];

  xdg.mimeApps = {
    enable = true;
    defaultApplications = {
      "text/html" = [ "firefox.desktop" ];
      "text/xml" = [ "firefox.desktop" ];
      "application/xhtml+xml" = [ "firefox.desktop" ];
      "application/vnd.mozilla.xul+xml" = [ "firefox.desktop" ];
      "x-scheme-handler/http" = [ "firefox.desktop" ];
      "x-scheme-handler/https" = [ "firefox.desktop" ];
    };
  };

  programs.firefox = {
    enable = true;
    configPath = ".config/mozilla/firefox";
    # If state version ≥ 19.09 then this should be a wrapped Firefox
    package = pkgs.firefox.overrideAttrs (old: {
      # MOZ_USE_XINPUT2=1 allow more smooth (pixel-level) scroll and zoom
      buildCommand = old.buildCommand + ''
        mv $out/bin/firefox $out/bin/firefox-no-xinput2
        makeWrapper $out/bin/firefox-no-xinput2 $out/bin/firefox --set-default MOZ_USE_XINPUT2 1
      '';
    });
    # id is default 0, thus this profile is default
    profiles.xieby1 = {
      settings = {
        # https://superuser.com/questions/1483037/making-firefox-fullscreen-like-without-actually-maximizing-the-window
        # the full screen hotkey/button will trigger fullscreen like normal, except it won't resize the window.
        "full-screen-api.ignore-widgets" = true;
        # Disable `alt` key of toggling menu bar
        "ui.key.menuAccessKeyFocuses" = false;
        "ui.key.menuAccessKey" = -1; # original number 18
        # enable userChrome.css
        "toolkit.legacyUserProfileCustomizations.stylesheets" = true;

        # Bookmark import only triggered when first open firefox.
        # Bookmark exposure only triggered when all firefox instances are closed.
        # As a result, there are so many sync conflicts!
        # # enable bookmarks sync to file
        # "browser.bookmarks.autoExportHTML" = true;
        # "browser.bookmarks.file" = "${config.home.homeDirectory}/Gist/Config/firefox-bookmarks.html";
        # "browser.places.importBookmarksHTML" = true;
      };
      userChrome =
      # [Disabling the mouseover to reveal the address/toolbar while in fullscreen - old method doesn't work](https://support.mozilla.org/en-US/questions/1324666)
      # [prevent firefox from showing the address bar in fullscreen mode](https://support.mozilla.org/en-US/questions/1323320)
      ''
        *|div#fullscr-toggler {display:none!important;}
      '';
    };
  };
}
{ pkgs, ... }: {
  programs.firefox.profiles.xieby1.extensions.packages = [(
    pkgs.nur.repos.rycee.firefox-addons.buildFirefoxXpiAddon {
      pname = "chrome-mask";
      version = "8.0.0";
      addonId = "chrome-mask@overengineer.dev";
      url = "https://addons.mozilla.org/firefox/downloads/file/4618461/chrome_mask-8.0.0.xpi";
      sha256 = "0w11la8sgg9pyw5zl3ki679g3353qxrd14gd0jq9m3i4fx35d250";
      meta = {
        mozPermissions = [ "storage" "tabs" "webRequest" "webRequestBlocking" "<all_urls>" ];
        platforms = pkgs.lib.platforms.all;
      };
    }
  )];
}
{ pkgs, ... }: let
  darkreader = pkgs.nur.repos.rycee.firefox-addons.darkreader;
in {
  programs.firefox = {
    profiles.xieby1 = {
      extensions.packages = [ darkreader ];
    };
  };
  firefox-extensions.xieby1.browser-extension-data."${darkreader.addonId}" = {
    storage = {
      schemeVersion = 2;
      syncSettings = false;
      disabledFor = [
        # markdown-preview-nvim: x.x.x.x:7768
        # markdown_revealjs daemon: x.x.x.x:7782
        "/.*:77[0-9][0-9]/"
        # markdown_revealjs
        "//home/.*/slides/index.html/"
      ];
    };
  };
}
{ pkgs, ... }: {
  # How to self package a firefox extension?
  # 1. Add the addon to firefox manually (by firefox addon store or ...)
  # 2. Get needed info by ~/.mozilla/firefox/xieby1/extensions.json
  imports = [
    ./module.nix

    ./sidebery.nix
    ./darkreader.nix
    ./zeroomega.nix
    (import ./smart-toc.nix "xieby1")
    ./vimium.nix
    ./chrome-mask.nix
  ];

  programs.firefox = {
    profiles.xieby1 = {
      extensions.packages = with pkgs.nur.repos.rycee.firefox-addons; [
        # 😾😾😾 Chinese users cannot use ad block extensions
        # https://discourse.mozilla.org/t/chinese-users-cant-use-ad-blocker-extensions/94823
        ublock-origin
        auto-tab-discard
        refined-github
        furiganaize
        markdownload
      ];
      settings = {
        # Automatically enable extensions
        "extensions.autoDisableScopes" = 0;
        # Disable extension auto update
        "extensions.update.enabled" = false;
      };
    };
  };
}
{ config, pkgs, lib, ... }: {
  options = {
    firefox-extensions = lib.mkOption {
      #      per-profile
      type = lib.types.attrsOf (lib.types.submodule { options = {
        browser-extension-data = lib.mkOption {
          #      per-extension
          type = lib.types.attrsOf (lib.types.submodule { options = {
            storage = lib.mkOption {
              type = lib.types.attrs;
              default = {};
              description = ''
                Attrs that will be converted to json and merged to storage.js
              '';
            };
          };});
          default = {};
        };
        extension-settings = lib.mkOption {
          type = lib.types.mkOptionType {
            name = "attrsRecursiveUpdate";
            description = "attribute set";
            check = lib.isAttrs;
            merge = loc: lib.foldl' (res: def: lib.recursiveUpdate res def.value) { };
            emptyValue = {
              value = { };
            };
          };
          default = {};
          description = ''
            The extension-settings.json
          '';
        };
      };});
      default = {};
      description = ''
        Attrs of firefox-extensions settings

        You may ask: why not using `programs.firefox.profiles.<name>.extensions.settings`?
        Because it do not support partially updating the settings.

        Example:

        firefox-extensions = {
          profile0 = {
            browser-extension-data = {
              darkreader = {
                storage = {
                  schemeVersion = 2;
                  syncSettings = false;
                  disabledFor = [
                    "http://127.0.0.1:7768"
                  ];
                };
              };
            };
            extension-settings = {
              ...
            };
          };
          profile1 = {...};
        };
      '';
    };
  };

  config = {
    yq-merge = (builtins.listToAttrs (lib.flatten (
      lib.mapAttrsToList (profile: per-profile-settings: (
        lib.mapAttrsToList (extensionId: per-extension-settings: {
          name = "${config.programs.firefox.configPath}/${profile}/browser-extension-data/${extensionId}/storage.js";
          value = { generator = builtins.toJSON; expr = per-extension-settings.storage; };
        }) per-profile-settings.browser-extension-data
      )) config.firefox-extensions
    ))) // (
      lib.mapAttrs' (profile: per-profile-settings: {
        name = "${config.programs.firefox.configPath}/${profile}/extension-settings.json";
        value = { generator = builtins.toJSON; expr = ({
          version = 3;
        } // per-profile-settings.extension-settings); };
      }) config.firefox-extensions
    );

    programs.firefox.profiles = lib.mapAttrs (profile: _: {
      settings = {
        "extensions.webextensions.ExtensionStorageIDB.enabled" = false;
      };
    }) config.firefox-extensions;
  };
}
# TIPS (https://github.com/piroor/treestyletab/wiki/How-to-inspect-tree-of-tabs):
# How to start debugger?
# 1. Type about:debugging into the address bar and hit the Enter key.
# 2. Choose "This Firefox" at the left pane.
# 3. Find "Tree Style Tab" from the list and click the Inspect button.
# 4. Then a debugger tab is opened.
#
# How to inspect the sidebar?
# 1. Start the debugger for TST.
# 2. On the top-right corner of the debugger window, there are some buttons, so click the Select an iframe as the currently targeted document button.
# 3. Choose /sidebar/sidebar.html from the list.
#   3.1. If you are opening multiple browser windows with their sidebar, you'll see multiple entries in the list.
#   3.2. /sidebar/sidebar.html items are sorted by the order they are initialized. If you hope to inspect the sidebar in the first browser window, you should choose first /sidebar/sidebar.html item in the list.
# 4. Choose the Inspector tab.
#
# To find CSS selectors for Firefox's own UI (e.g. the Tabs header, not Sidebery):
# 1. Press F12, then F1; enable "Enable browser chrome and add-on debugging toolboxes"
#    and "Enable remote debugging" in DevTools settings.
# 2. Press Ctrl+Alt+Shift+I and accept the Browser Toolbox connection.
# 3. In its Inspector, select the sidebar frame if needed, then use the element
#    picker on the UI you want to style.
# 4. Read the element's id/class (e.g. id="sidebar-panel-header" gives
#    #sidebar-panel-header) and test your rule in the Styles pane.

{ pkgs, ... }: let
  sidebery = pkgs.nur.repos.rycee.firefox-addons.sidebery;
in {
  programs.firefox = {
    profiles.xieby1 = {
      extensions.packages = [ sidebery ];
      # transparent floating sidebar
      # Why not use it?
      # Because: I tried two ways to adjust the height of sidebar dynamically, but all failed:
      # * user.js cannot inject js code
      # * css counter cannot used in height
      #
      #settings = {
      #  "browser.tabs.allow_transparent_browser" = true;
      #};
      #userChrome = ''
      #  #sidebar-box {
      #    height: 90%;
      #    top: 5%;
      #    right: 0;
      #    position: absolute;
      #    z-index: 99;
      #  }
      #  #browser,
      #  tabbox#tabbrowser-tabbox,
      #  #tabbrowser-tabpanels,
      #  #sidebar-box,
      #  #sidebar,
      #  window#webextpanels-window {
      #    background-color: transparent !important;
      #    background-image: none !important;
      #  }
      #'';
      #userContent = ''
      #  @-moz-document regexp("^moz-extension://.*/sidebar/sidebar.html") {
      #    :root {
      #      background-color: transparent !important;
      #    }
      #    #root.root {
      #      --frame-bg: transparent !important;
      #      --toolbar-bg: black !important;
      #      --frame-el-bg: black !important;
      #    }
      #  }
      #'';
      settings = {
        "sidebar.position_start" = false; # sidebar on the right
      };
      userChrome = /*css*/ ''
        /* Completely Remove Firefox Tab Bar */
        /* https://bricep.net/completely-remove-firefox-tab-bar/ */
        #TabsToolbar { visibility: collapse !important; }

        /* Show hide this part of sidebar #2169: https://github.com/mbnuqw/sidebery/discussions/2169 */
        #sidebar-panel-header { display: none; }

        #sidebar-button { display: none; }
        #sidebar-splitter { display: none; }
        #sidebar-box {
          width: 13vw !important;
          min-width: 8em !important;
          max-width: 15em !important;
          padding: 0 !important;
        }
      '';
    };
  };

  firefox-extensions.xieby1 = {
    extension-settings = {
      commands = {
        # toggle sidebery
        _execute_sidebar_action = { precedenceList = [{
           id = sidebery.addonId;
           installDate = 0;
           value = { shortcut = "F1"; };
           enabled = true;
        }];};
        search = { precedenceList = [{
          id = sidebery.addonId;
          installDate = 0;
          value = { shortcut = "F2"; };
          enabled = true;
        }];};
        up_shift = { precedenceList = [{
          id = sidebery.addonId;
          installDate = 0;
          value = { shortcut = "Alt+Shift+Left"; };
          enabled = true;
        }];};
        down_shift = { precedenceList = [{
          id = sidebery.addonId;
          installDate = 0;
          value = { shortcut = "Alt+Shift+Right"; };
          enabled = true;
        }];};
        rm_tab_on_panel = { precedenceList = [{
          id = sidebery.addonId;
          installDate = 0;
          value = { shortcut = "Alt+Shift+Delete"; };
          enabled = true;
        }];};
        rm_tabs_above_in_panel.precedenceList = [{
          id = sidebery.addonId;
          installDate = 0;
          value.shortcut = "Alt+Shift+Comma";
          enabled = true;
        }];
        rm_tabs_below_in_panel.precedenceList = [{
          id = sidebery.addonId;
          installDate = 0;
          value.shortcut = "Alt+Shift+Period";
          enabled = true;
        }];
        switch_to_next_tab = { precedenceList = [{
          id = sidebery.addonId;
          installDate = 0;
          value = { shortcut = "Alt+Shift+Down"; };
          enabled = true;
        }];};
        switch_to_prev_tab = { precedenceList = [{
          id = sidebery.addonId;
          installDate = 0;
          value = { shortcut = "Alt+Shift+Up"; };
          enabled = true;
        }];};
        switch_to_tab_0.precedenceList = [{
          id = sidebery.addonId;
          installDate = 0;
          value.shortcut = "Alt+Shift+PageUp";
          enabled = true;
        }];
        switch_to_last_tab.precedenceList = [{
          id = sidebery.addonId;
          installDate = 0;
          value.shortcut = "Alt+Shift+PageDown";
          enabled = true;
        }];
      };
    };
  };
  firefox-extensions.xieby1.browser-extension-data."${sidebery.addonId}" = {
    storage = {
      sidebarCSS = /*css*/ ''
        #root.root {
          /* make vertical line more clear */
          /* original: --tabs-lvl-opacity: 0.16 */
          --tabs-lvl-opacity: 0.8;
        }
        @media (prefers-color-scheme: dark) {
          #root.root {
            --tabs-activated-shadow: 0 0 0 1px white;
          }
        }
        @media (prefers-color-scheme: light) {
          #root.root {
            --tabs-activated-shadow: 0 0 0 1px black;
          }
        }

        /* make sure the top tab shadow (--tabs-activated-shadow) is not clipped */
        /* Why not using border?
           Because border will add size to the div, thus changing the layout.
           As a result, the vertical line is not aligned.
        */
        .AnimatedTabList { padding-top: 1px; }

        /* compact fav margin */
        .Tab[data-pin="false"] .fav {
          /* original: 0 var(--tabs-inner-gap)0 calc(var(--tabs-inner-gap) + 2px); */
          margin: 0;
        }
      '';
    };
  };
}
profile:
{ pkgs, lib, ... }: let
  smart-toc = pkgs.nur.repos.rycee.firefox-addons.buildFirefoxXpiAddon {
    pname = "smart-toc";
    version = "0.11.25";
    addonId = "{40289693-01fe-4740-91ae-07344bf5b09b}";
    url = "https://addons.mozilla.org/firefox/downloads/file/4485577/smart_toc-0.11.25.xpi";
    sha256 = "17jpqy2qs3qc1m9l4kbqw14m5bkwfzb253wpf1x1b5p9q6sap8w8";
    meta = with lib; {
      mozPermissions = [
        "activeTab"
        "scripting"
        "storage"
        "tabs"
        "*://*/*"
        "file:///*"
      ];
      platforms = platforms.all;
    };
  };
in {
  programs.firefox = {
    profiles.${profile} = {
      extensions.packages = [ smart-toc ];
    };
  };
  firefox-extensions.${profile} = {
    extension-settings = {
      commands = {
        toggle = {precedenceList = [{
          id = smart-toc.addonId;
          installDate = 0;
          value = { shortcut = "Alt+E"; };
          enabled = true;
        }];};
      };
    };
  };
}
{ config, pkgs, lib, ... }: let
  inherit (pkgs.nur.repos.rycee.firefox-addons) vimium;
in {
  programs.firefox = {
    profiles.xieby1 = {
      extensions.packages = [
        vimium
      ];
    };
  };

  home.file.vimium_sql = let
    # retrieve json:
    # sqlite3 storage-sync-v2.sqlite "SELECT data FROM storage_sync_data WHERE ext_id='{d7742d87-e61d-4b78-b8a1-b469842139fa}';"
    json = lib.generators.toJSON {} {
      keyMappings = ''
        unmap f
        unmap F
        map s LinkHints.activateMode
        map S LinkHints.activateModeToOpenInNewTab
      '';
      exclusionRules = [{
        passKeys = "";
        pattern = "*:77[0-9][0-9]*";
      }];
      settingsVersion = lib.removePrefix "vimium-" vimium.name;
    };
    relDir = "${config.programs.firefox.profilesPath}/xieby1";
    absDir = "${config.home.homeDirectory}/${relDir}";
    relTarget = "${relDir}/browser-extension-data/${vimium.addonId}/sql";
    absTarget = "${config.home.homeDirectory}/${relTarget}";
  in {
    text = /*sql*/ "UPDATE storage_sync_data SET data = '${json}' WHERE ext_id = '${vimium.addonId}';";
    target = relTarget;
    onChange = /*bash*/ ''
      if [[ -e ${absDir}/storage-sync-v2.sqlite ]]; then
        echo ⛁ updating vimium settings in ${absDir}/storage-sync-v2.sqlite
        ${pkgs.sqlite}/bin/sqlite3 ${absDir}/storage-sync-v2.sqlite < ${absTarget}
      else
        echo ⛃ next time update vimium settings in ${absDir}/storage-sync-v2.sqlite
        rm ${absTarget}
      fi
    '';
  };
}
{ config, pkgs, ... }: let
  inherit (pkgs.nur.repos.rycee.firefox-addons) zeroomega;

  # A fixed proxy profile pointing at 127.0.0.1:<port>.
  # ZeroOmega reads these from browser.storage.local as `+<name>` keys.
  fixedProfile = name: port: {
    inherit name;
    profileType = "FixedProfile";
    fallbackProxy = {
      scheme = "http";
      host = "127.0.0.1";
      inherit port;
    };
  };
in {
  programs.firefox = {
    profiles.xieby1 = {
      extensions.packages = [ zeroomega ];
    };
  };
  firefox-extensions.xieby1 = {
    browser-extension-data."${zeroomega.addonId}" = {
      storage = {
        schemaVersion = 2;

        # --- active profile + rule-list refresh ---
        "-startupProfileName" = "auto switch";
        "-quickSwitchProfiles" = [];
        # > 0 enables refreshing rule-list profiles on startup (minutes).
        "-downloadInterval" = 1440;

        # --- proxy servers ---
        "+nix" = fixedProfile "nix" config.proxyPort;
        "+tailscale" = fixedProfile "tailscale"
          config.my.tailscale.instances.official.httpPort;

        # --- gfwlist rule list: listed domains -> nix, everything else -> direct ---
        "+gfwlist" = {
          name = "gfwlist";
          profileType = "RuleListProfile";
          format = "AutoProxy";
          sourceUrl = "https://raw.githubusercontent.com/gfwlist/gfwlist/master/gfwlist.txt";
          matchProfileName = "nix";     # normal rules = proxy
          defaultProfileName = "direct"; # @@ rules + fallback = direct
        };

        # --- active profile: tailscale CGNAT 100.64.0.0/10 -> tailscale, else gfwlist ---
        "+auto switch" = {
          name = "auto switch";
          profileType = "SwitchProfile";
          defaultProfileName = "gfwlist";
          rules = [{
            condition = {
              conditionType = "IpCondition";
              ip = "100.64.0.0";
              prefixLength = 10;
            };
            profileName = "tailscale";
          } {
            condition = {
              conditionType = "HostWildcardCondition";
              pattern = "*.tailff7a5.ts.net";
            };
            profileName = "tailscale";
          }];
        };
      };
    };
  };
}

Advanced screenshot: flameshot

{ pkgs, ... }: {
  home.packages = [
    pkgs.flameshot
  ];
  home.file.autostart_flameshot = {
    source = "${pkgs.flameshot}/share/applications/org.flameshot.Flameshot.desktop";
    target = ".config/autostart/org.flameshot.Flameshot.desktop";
  };
  systemd.user.tmpfiles.rules = [
    "L? %h/.config/flameshot/flameshot.ini - - - - %h/Gist/Config/flameshot.ini"
  ];
}
{ pkgs, ... }: {
  fonts.fontconfig.enable = true;
  # list font names: `fc-list -f '%{family[0]}\n' | sort -u`
  fonts.fontconfig.defaultFonts = {
    emoji = [
      "Noto Color Emoji"
      "Noto Emoji"
    ];
    monospace = [
      "DejaVu Sans Mono"
      "Noto Sans Mono CJK SC"
      "FiraCode Nerd Font Mono"
    ];
    sansSerif = [
      "DejaVu Sans"
      "Noto Sans CJK SC"
      "FiraCode Nerd Font"
    ];
    serif = [
      "DejaVu Serif"
      "Noto Serif CJK SC"
      "FiraCode Nerd Font"
    ];
  };

  home.packages = with pkgs; [
    # vim vista need nerd fonts
    # https://github.com/liuchengxu/vista.vim/issues/74
    # https://github.com/liuchengxu/space-vim/wiki/tips#programming-fonts
    # available nerd fonts: nixpkgs/pkgs/data/fonts/nerdfonts/shas.nix
    ## use non-variable noto font for feishu and other old electron apps
    ## for more details see: https://github.com/NixOS/nixpkgs/issues/171976
    noto-fonts-cjk-sans
    noto-fonts-cjk-serif
    noto-fonts-color-emoji
    nerd-fonts.fira-code
    (noto-fonts.override { variants = [ "NotoSansSymbols2" ]; })
  ];
}

KDE Connect

{ pkgs, ... }: {
  home.packages = [
    pkgs.kdePackages.kdeconnect-kde
  ];

Auto startup KDE Connect after Gnome GUI login.

  home.file.kde_connect_indicator = {
    source = "${pkgs.kdePackages.kdeconnect-kde}/share/applications/org.kde.kdeconnect.nonplasma.desktop";
    target = ".config/autostart/org.kde.kdeconnect.nonplasma.desktop";
  };
}
{ pkgs, config, ... }: {
  systemd.user.services.low-battery-notify = {
    Unit = {
      Description = "Low battery notification";
      # Only run this service on machines that have a battery.
      # See `man 5 systemd.unit` for details on ConditionPathExistsGlob.
      ConditionPathExistsGlob = "/sys/class/power_supply/*";
    };
    Service = {
      Type = "oneshot";
      # https://unix.stackexchange.com/questions/60778/how-can-i-get-an-alert-when-my-battery-is-about-to-die-in-linux-mint
      ExecStart = pkgs.writeShellScript "low-battery-notify.sh" ''
        STATE_FILE="${config.home.homeDirectory}/.local/state/low-battery-notified"
        mkdir -p "$(dirname "$STATE_FILE")"

        battery_level=$(${pkgs.acpi}/bin/acpi -b | grep -P -o '[0-9]+(?=%)' | head -1)
        if [ -z "$battery_level" ]; then
          exit 0
        fi

        if [ "$battery_level" -le 20 ]; then
          if [ ! -f "$STATE_FILE" ]; then
            ${pkgs.libnotify}/bin/notify-send --urgency=critical --expire-time=0 \
              "⚠️ Battery low" "🔋 Battery level is $battery_level%!"
            touch "$STATE_FILE"
          fi
        else
          if [ -f "$STATE_FILE" ]; then
            rm -f "$STATE_FILE"
          fi
        fi
      '';
    };
  };

  systemd.user.timers.low-battery-notify = {
    Unit = {
      Description = "Check battery level every 10 minutes";
      # Only activate this timer on machines that have a battery.
      # See `man 5 systemd.unit` for details on ConditionPathExistsGlob.
      ConditionPathExistsGlob = "/sys/class/power_supply/*";
    };
    Timer = {
      # The syntax of OnCalendar: `man systemd.time`
      OnCalendar = "*:0/10"; # every 10 minutes
    };
    Install.WantedBy = [ "timers.target" ];
  };
}
# https://nixos.org/manual/nixos/stable/#sec-writing-modules
# refers to syncthing module

# list options:
#   home-manager option xdg.mime.types.\"*\"
#   nixos option
{ config
, lib
, pkgs
, ...
}:
with lib;
let
  cfg = config.xdg.mime.types;
in
{
  options = {
    xdg.mime.types = mkOption {
      default = {};
      description = "Set MIME types and default applications.";
      example = ''
        xdg.mime.types.dot = {
          name = "graphviz-dot";
          type = "text/graphviz-dot";
          pattern = "*.dot";
          defaultApp = "xdot.desktop";
        };
      '';
      type = types.attrsOf (types.submodule ({name, ...}:
      {
        options = {
          name = mkOption {
            type = types.str;
            default = name;
            description = "The name of the xml file.";
          };
          type = mkOption {
            type = types.str;
            default = "";
            description = "The mime-type.";
          };
          pattern = mkOption {
            type = types.str;
            default = "";
            description = "The glob pattern.";
          };
          defaultApp = mkOption {
            type = types.str;
            default = "";
            description = "Default application for opening this MIME type.";
          };
        };
      }));
    };
  };

  # builtins.mapAttrs (n: v: {wang=v.miao;}) {file1={miao=1;}; file2={miao=2;};}
  # => {file1={wang=1;}; file2={wang=2;};}
  config = {
    home.file = builtins.mapAttrs (n: v: {
      text = ''
        <?xml version="1.0"?>
        <mime-info xmlns='http://www.freedesktop.org/standards/shared-mime-info'>
          <mime-type type="${v.type}">
            <glob pattern="${v.pattern}"/>
          </mime-type>
        </mime-info>
      '';
      target = ".local/share/mime-types/${v.name}.xml";
      onChange = ''
        ${pkgs.xdg-utils}/bin/xdg-mime install ~/.local/share/mime-types/${v.name}.xml
        ${pkgs.xdg-utils}/bin/xdg-mime default ${v.defaultApp} ${v.type}
      '';
    }) cfg;
  };
}

rustdesk, the remote desktop app

{ config, pkgs, stdenv, lib, ... }:
{
  home.packages = [

The new version of rustdesk is rustdesk-flutter, which is cached in official nix binary cache.

    pkgs.rustdesk-flutter
  ];

Auto startup rustdesk after Gnome GUI login.

  # home.file.autostart_rustdesk_desktop = {
  #   source = "${pkgs.rustdesk-flutter}/share/applications/rustdesk.desktop";
  #   target = ".config/autostart/rustdesk.desktop";
  # };
}

Terminal Comparison

  • gnome-terminal
    • Pros
    • Cons
      • Wrong window size, when window is tiled (e.g. use gTile)
      • Icon display incorrectly (e.g. Vim-vista)
      • It's hard to hide top bar
  • alacritty
    • Pros
      • Esay configurable
      • Icon display correctly (e.g. Vim-vista)
      • input method fcitx works
    • Cons
      • Not native tab support https://github.com/alacritty/alacritty/issues/3129 The developer(s?) with poor attitude
        • Compromise: tabbed
      • Alacritty is not work with espanso https://github.com/federico-terzi/espanso/issues/787 https://github.com/federico-terzi/espanso/issues/1088 In espanso auto mode, alacritty definitely will be stucked. In clipboard, alacritty may be stucked.
      • emoji display poorly.
  • kitty
    • Cons
      • do not support search
        • https://github.com/kovidgoyal/kitty/issues/718
  • hyper
    • Cons
      • scroll speed is too fast!
  • ghostty
    • Cons
      • Tab title stays on Neovim's filename after exiting Neovim opened from LazyGit; Kitty restores LazyGit's title. Ghostty parses but does not implement title push/pop (CSI 22/23): ghostty#2668 is still open; last updated 2024-11-16 (nearly two years ago as of 2026-11-04).
{ ... }: {
  imports = [
    ./kitty
    ./ghostty
  ];
}
{ config, lib, pkgs, ... }:
let
  ghostty = pkgs.ghostty.overrideAttrs (old: {
    patches = (old.patches or []) ++ [ ./title-stack.patch ];
  });
in {
  cachix_packages = [ ghostty ];

  programs.ghostty = {
    enable = true;
    package = ghostty;
    settings = {
      # Exposes --ghostty-fg and --ghostty-bg for the GTK tab CSS below.
      window-theme = "ghostty";
      gtk-wide-tabs = false;
      gtk-single-instance = false;
      font-size = (import ~/Gist/Config/terminal-font-size.nix).${lib.trim (builtins.readFile /etc/hostname)} or 14;
      font-family = config.fonts.fontconfig.defaultFonts.monospace;
      # Make bar cursors easier to see in zsh and Neovim insert modes.
      adjust-cursor-thickness = 4;
      gtk-custom-css = "${builtins.toFile "ghostty.css" ''
        headerbar {
          min-height: 10px;
          padding: 0;
          margin: 0;
        }

        tabbar tabbox {
          min-height: 10px;
          padding: 0;
          margin: -4px 0;
        }

        tabbar tabbox tab {
          padding: 0;
          margin: 0;
        }

        tabbar tabbox tab:not(:selected) {
          color: var(--ghostty-fg);
          background-color: var(--ghostty-bg);
        }

        tabbar tabbox tab:selected {
          color: var(--ghostty-bg);
          background-color: var(--ghostty-fg);
        }
      ''}";
      keybind = [
        "ctrl+shift+,=move_tab:-1"
        "ctrl+shift+.=move_tab:1"
        "ctrl+shift+[=goto_split:previous"
        "ctrl+shift+]=goto_split:next"
      ];
    };
  };

  programs.neovim.initLua = /*lua*/''
    -- [Linux tmux: scrolling distance with the mouse wheel #8875](https://github.com/ghostty-org/ghostty/discussions/8875)
    vim.opt.mousescroll = "ver:1,hor:1"
  '';
}

kitty

{ config, pkgs, stdenv, lib, ... }:
{
  # Terminal Comparsion
  # * gnome-terminal
  #   * Pros
  #   * Cons
  #     * Wrong window size, when window is tiled (e.g. use gTile)
  #     * Icon display incorrectly (e.g. Vim-vista)
  #     * It's hard to hide top bar
  # * alacritty
  #   * Pros
  #     * Esay configurable
  #     * Icon display correctly (e.g. Vim-vista)
  #     * input method fcitx works
  #   * Cons
  #     * Not native tab support
  #       https://github.com/alacritty/alacritty/issues/3129
  #       The developer(s?) with poor attitude
  #       * Compromise: tabbed
  #     * Alacritty is not work with espanso
  #       https://github.com/federico-terzi/espanso/issues/787
  #       https://github.com/federico-terzi/espanso/issues/1088
  #       In espanso auto mode, alacritty definitely will be stucked.
  #       In clipboard, alacritty may be stucked.
  #     * emoji display poorly.
  # * kitty
  #   * Pros
  #     * Esay configurable
  #   * Cons
  #     * Icon display incorrectly (e.g. Vim-vista)
  #     * input method support solved by fcitx5
  # * hyper
  #   * Cons
  #     * scroll speed is too fast!

  imports = [
    ./search.nix
    ./kitty-scrollback-nvim.nix
  ];

  programs.kitty = {
    enable = true;
    environment = {
      "TERM" = "xterm";
    };
    font = {
      name = "";
      # My zsh does not export HOSTNAME, so `builtins.getEnv "HOSTNAME"` does not work.
      # Therefore, I use /etc/hostname here.
      size = (import ~/Gist/Config/terminal-font-size.nix).${pkgs.lib.trim (builtins.readFile /etc/hostname)} or 14;
    };
    settings = {
      allow_remote_control = "yes";
      listen_on = "unix:/tmp/mykitty";
      shell_integration = "enabled";

      hide_window_decorations = "yes";
      cursor_blink_interval = "0.8";
      remember_window_size = "no";
      initial_window_width = "80c";
      initial_window_height = "20c";

      # Note that this is only used for high precision scrolling devices on platforms such as macOS and Wayland.
      touch_scroll_multiplier = "5.0";

      # tab
      tab_bar_edge = "top";
      tab_bar_style = "separator";
      # tab_separator = " ┇"; This is default, a space before the vertical line
      active_tab_foreground   = "#e2e2e3";
      active_tab_background   = "#2c2e34";
      active_tab_title_template = "🐱{fmt.fg.red}{bell_symbol}{activity_symbol}{fmt.fg.tab}{title}";
      inactive_tab_foreground = "#2c2e34";
      inactive_tab_background = "#e2e2e3";

      # tango dark
      background              = "#2c2e34";
      foreground              = "#e2e2e3";
      cursor                  = "#e2e2e3";
      color0                  = "#2c2e34";
      color8                  = "#555753";
      color1                  = "#cc0000";
      color9                  = "#ef2929";
      color2                  = "#4e9a06";
      color10                 = "#8ae234";
      color3                  = "#c4a000";
      color11                 = "#fce94f";
      color4                  = "#3465a4";
      color12                 = "#729fcf";
      color5                  = "#75507b";
      color13                 = "#ad7fa8";
      color6                  = "#06989a";
      color14                 = "#34e2e2";
      color7                  = "#e2e2e3";
      color15                 = "#eeeeec";
      # selection_foreground    = "#2c2e34";
      # selection_background    = "#e2e2e3";
    };
    extraConfig = ''
      map ctrl+= change_font_size all +2.0
      map ctrl+shift+= change_font_size all +1.0
      map ctrl+- change_font_size all -2.0
      map ctrl+shift+- change_font_size all -1.0
      map ctrl+0 change_font_size all 0

      map ctrl+shift+t new_tab_with_cwd !neighbor
      map ctrl+shift+n new_os_window_with_cwd

      # disable opening of URLs with a plain click
      mouse_map left click ungrabbed no_op

      #: asks which tab to move the window into
      map f2 detach_window ask


      action_alias launch_window launch --cwd=current
      # Window layout
      enabled_layouts splits

      # Split and Create a new window
      map alt+s launch_window --location=hsplit
      map alt+v launch_window --location=vsplit
    '';
  };
}
{ pkgs, ... }: {
  programs.neovim = {
    plugins = [{
      plugin = pkgs.vimUtils.buildVimPlugin {
        name = "kitty-scrollback.nvim";
        src = pkgs.vimPlugins.kitty-scrollback-nvim;
        postPatch = ''
          # Move status icons from top-right to bottom-left.
          substituteInPlace lua/kitty-scrollback/windows.lua \
            --replace-fail 'row = 0,' 'row = vim.o.lines - 2,' \
            --replace-fail 'col = vim.o.columns,' 'col = 0,'
        '';
      };
      type = "lua";
      config = /*lua*/''
        require('kitty-scrollback').setup({{
          callbacks = {
            after_ready = function()
              -- Disable the auto quit all after `"+y`:
              -- by clearing the autocommand that quits after yanking to clipboard
              vim.api.nvim_clear_autocmds({ group = 'KittyScrollBackNvimTextYankPost' })
            end,
          },
        }})
      '';
    }];
  };
  programs.kitty.extraConfig = ''
    # kitty-scrollback.nvim Kitten alias
    action_alias kitty_scrollback_nvim kitten '${pkgs.vimPlugins.kitty-scrollback-nvim}/python/kitty_scrollback_nvim.py'
    # Browse scrollback buffer in nvim
    map kitty_mod+h kitty_scrollback_nvim
    # Browse output of the last shell command in nvim
    map kitty_mod+g kitty_scrollback_nvim --config ksb_builtin_last_cmd_output
    # Show clicked command output in nvim
    mouse_map ctrl+shift+right press ungrabbed combine : mouse_select_command_output : kitty_scrollback_nvim --config ksb_builtin_last_visited_cmd_output
  '';
}
{ pkgs, ... }: let
  kitty-kitten-search = pkgs.runCommand "kitty-kitten-search" {
    src = pkgs.fetchFromGitHub {
      owner = "trygveaa";
      repo = "kitty-kitten-search";
      rev = "0760138fad617c5e4159403cbfce8421ccdfe571";
      hash = "sha256-egisza7V5dWplRYHIYt4bEQdqXa4E7UhibyWJAup8as=";
    };
  } ''
    mkdir $out
    cp $src/scroll_mark.py $out/scroll_mark.py
    sed 's/typing/typing_compat/' $src/search.py > $out/search.py
  '';
in {
  home.file.kitty_search = {
    source = "${kitty-kitten-search}/search.py";
    target = ".config/kitty/search.py";
  };
  home.file.kitty_scroll_mark = {
    source = "${kitty-kitten-search}/scroll_mark.py";
    target = ".config/kitty/scroll_mark.py";
  };
  programs.kitty = {
    extraConfig = ''
      map ctrl+shift+f launch --location=hsplit --allow-remote-control kitty +kitten search.py @active-kitty-window-id
    '';
  };
}
{ pkgs, lib, ... }: {
  home.packages = [ pkgs.warpd ];
  home.file.autostart_warpd = {
    target = ".config/autostart/warpd.desktop";
    text = ''
      [Desktop Entry]
      Type=Application
      Name=warpd
      Exec=${pkgs.warpd}/bin/warpd
    '';
  };

  # 为什么不用gnome快捷键?
  # * 一次性warpd启动比warpd后台运行慢
  # 为什么用gnome快捷键
  # * warpd没办法正确识别M-k键?或者是gnome抢了?要M-kk才行
  # dconf.settings."org/gnome/settings-daemon/plugins/media-keys".custom-keybindings = [
  #   "/org/gnome/settings-daemon/plugins/media-keys/custom-keybindings/warpd-hint/"
  #   "/org/gnome/settings-daemon/plugins/media-keys/custom-keybindings/warpd-normal/"
  # ];
  # dconf.settings."org/gnome/settings-daemon/plugins/media-keys/custom-keybindings/warpd-hint" = {
  #   binding="<Super>k";
  #   command = "warpd --hint";
  #   name="warpd-hint";
  # };
  # dconf.settings."org/gnome/settings-daemon/plugins/media-keys/custom-keybindings/warpd-normal" = {
  #   binding="<Alt>k";
  #   command = "warpd --normal";
  #   name="warpd-normal";
  # };
  home.file.warpd_config = {
    target = ".config/warpd/config";
    # Available options see `warpd --list-options`.
    # Available modifiers (according to warpd source code):
    # * alt: A-
    # * super/meta: M-
    # * shift: S-
    # * ctrl: C-
    # Available X11 key names by removing "XK_" prefix in ${pkgs.xorg.xorgproto}/include/X11/keysymdef.h
    text = lib.generators.toKeyValue {mkKeyValue=lib.generators.mkKeyValueDefault {} ": ";} {
      activation_key = "A-M-z"; # 一只手按A-M-z比A-M-c更方便!
      buttons = "q w e";
      left  = "Left";
      up    = "Up";
      right = "Right";
      down  = "Down";
      scroll_up   = "S-Up";
      scroll_down = "S-Down";
    };
  };
}

Wayland

virtualisation.waydroid.enable = true;

尝试使用weston,消息来源参考:

  • https://github.com/waydroid/waydroid/issues/470
    • https://wiki.archlinux.org/title/Waydroid

wayland images: /var/lib/waydroid/images/

weston --scale=2

# 在weston里
waydroid show-full-ui

weston快捷键参考man weston-bindings

# based on https://github.com/lucasew/nixcfg/blob/49d44c1a655f1c20d7354ecea942c78704067d50/pkgs/wrapWine.nix
{ pkgs ? import <nixpkgs> {} }:
let
  inherit (builtins) length concatStringsSep;
  inherit (pkgs) lib cabextract
    writeShellScriptBin symlinkJoin;
  inherit (lib) makeBinPath;
in
{ is64bits ? false
, wine ? if is64bits then pkgs.wineWowPackages.stable else pkgs.wine
, wineFlags ? ""
, executable
, chdir ? null
, name
, tricks ? [ ]
, setupScript ? ""
, firstrunScript ? ""
, home ? ""
, regfile ? null
}:
let
  wineBin = "${wine}/bin/wine${if is64bits then "64" else ""}";
  requiredPackages = [
    wine
    cabextract
  ];
  PATH = makeBinPath requiredPackages;
  NAME = name;
  WINEARCH =
    if is64bits
    then "win64"
    else "win32";
  WINE_NIX = "$HOME/.wine-nix";
  WINEPREFIX = "${WINE_NIX}/${name}";
  setupHook = ''
    ${wine}/bin/wineboot
  '';
  tricksHook =
    if (length tricks) > 0 then
      let
        tricksStr = concatStringsSep " " tricks;
        tricksCmd = ''
          ${pkgs.winetricks}/bin/winetricks ${tricksStr}
        '';
      in
      tricksCmd
    else "";
  run = writeShellScriptBin name ''
    export APP_NAME="${NAME}"
    export WINEARCH=${WINEARCH}
    export WINE_NIX=${WINE_NIX}
    export PATH=$PATH:${PATH}
    export WINEPREFIX="${WINEPREFIX}"
    export EXECUTABLE="${executable}"
    mkdir -p "$WINE_NIX"
    ${setupScript}
    if [ ! -e "$EXECUTABLE" ] # if the executable does not exist
    then
      ${if regfile!=null
        then ''${wineBin} regedit /C ${regfile}''
        else ""
      }
      ${setupHook}
      ${tricksHook}
      ${firstrunScript}
    else # no automatically run after installation!
      ${if chdir != null
        then ''cd "${chdir}"''
        else ""}
      if [ ! "$REPL" == "" ]; # if $REPL is setup then start a shell in the context
      then
        bash
        exit 0
      fi

      ${wineBin} ${wineFlags} "$EXECUTABLE" "$@"
    fi
  '';
  clean = writeShellScriptBin "${name}-clean" ''
    read -p "Are you sure you want to clean ${WINEPREFIX}? <y/N> " prompt
    if [[ $prompt =~ [yY](es)* ]]; then
      rm ${WINEPREFIX} -rf
    fi
  '';
  winecfg = writeShellScriptBin "${name}-cfg" ''
    export WINEARCH=${WINEARCH}
    WINEPREFIX=${WINE_NIX}/${name} winecfg $@
  '';
  _wine = writeShellScriptBin "${name}-wine" ''
    export WINEARCH=${WINEARCH}
    WINEPREFIX=${WINE_NIX}/${name} ${wineBin} $@
  '';
in
symlinkJoin {
  inherit name;
  paths = [run clean winecfg _wine];
}

XColor

Why use XColor instead of gcolor3 or eyedropper? Because they do not support zoom: e.g. https://github.com/FineFindus/eyedropper/issues/79

{ pkgs, ... }: {
  home.packages = [(
    let
      name = "xcolor-sleep";
      # [Error when launching xcolor from the Activities overview: Could not grab pointer #38](https://github.com/Soft/xcolor/issues/38)
      exec = pkgs.writeShellScript name ''
        for ((n=0; n<3; n++)); do
          ${pkgs.xcolor}/bin/xcolor -s && break
          sleep 0.2
        done
      '';
    in
    pkgs.runCommand name {} ''
      mkdir -p $out
      ${pkgs.lndir}/bin/lndir -silent ${pkgs.xcolor} $out
      rm $out/share/applications/XColor.desktop
      sed 's,^Exec.*,Exec=${exec},' ${pkgs.xcolor}/share/applications/XColor.desktop > $out/share/applications/XColor.desktop
    ''
  )];
}

xdot, the dot (graphviz) viewer

{ config, pkgs, stdenv, lib, ... }:
let

Add a xdot.desktop for my xdot.

  myxdot = pkgs.symlinkJoin {
    name = "myxdot";
    paths = [
      pkgs.xdot
      (pkgs.makeDesktopItem {
        name = "xdot";
        desktopName = "xdot";
        exec = "xdot %U";
        icon = builtins.toFile "cheatsheet.svg" ''
          <svg width="64" height="64" xmlns="http://www.w3.org/2000/svg">
            <rect width="100%" height="100%" rx="20%" ry="20%" fill="#F5F5F5"/>
            <text x="50%" y="50%" text-anchor="middle" dominant-baseline="middle" font-size="18" font-weight="bold" fill="#333333">
              xdot
            </text>
          </svg>
        '';
  })];};
in {
  home.packages = [
    myxdot
  ];

Open *.dot files with xdot.desktop by default.

  xdg.mime.types.dot = {
    name = "graphviz-dot";
    type = "text/graphviz-dot";
    pattern = "*.dot";
    defaultApp = "xdot.desktop";
  };
}

Xingyao 14 audio

On techrevo (MECHREVO XINGYAO Series-P916F-STX, Realtek ALC256 subsystem 1d05:e004), the default HiFi/UCM profile selects AMD ACP-PDM capture, which produces a saturated constant signal. The BIOS also leaves the second speaker pin 0x1b disconnected, causing thin, quiet playback.

Home Manager routing and mixer

The host-scoped WirePlumber rule disables ACP for the Realtek card, exposing its working HDA PCM. A hardware-checked user service enables Master, Speaker and Capture at 0 dB whenever WirePlumber starts or restarts. PipeWire controls listening volume.

Select these defaults once; WirePlumber saves them:

  • Input: alsa_input.pci-0000_c1_00.6.capture.0.0
  • Output: alsa_output.pci-0000_c1_00.6.playback.0.0

The output node explicitly uses audio.channels = 2 and audio.position = [ "FL" "FR" ]. This is required with the patched driver: raw ALSA enumeration otherwise negotiates four channels, placing the shared speaker DAC on channels 3/4 while stereo audio reaches channels 1/2, resulting in silence. With two-channel PCM playback, both speaker and headphone DACs receive the stereo stream. The input configuration is unaffected by this output-only rule.

ACP profile/port management is bypassed; ALSA headphone auto-mute was verified separately on this machine.

Driver fix and power saving

The companion NixOS module applies a small patch to the configured Xanmod kernel on techrevo. It registers pin 0x1b as an internal speaker (0x90170121) and restricts it to DAC 0x02, shared with pin 0x14. The quirk matches PCI subsystem 1d05:e004 and checks the ALC256 codec and codec subsystem before applying. The driver then owns initialization and restoration of both speaker paths.

Normal boot uses this patch, masks the old xingyao-speakers.service, and omits its resume command. The codec keeps power/control=auto, sleeps while idle and restores full speaker sound on playback. The kernel version string is unchanged; use /run/booted-system/kernel to identify the actual kernel build.

For an idle/wake check, inspect /sys/bus/hdaudio/devices/hdaudioC<card>D0/power/runtime_status before reading the codec dump, because reading registers wakes the chip. Pause playback and recording, then allow up to 35 seconds for PipeWire to close the PCM and the codec's 10-second autosuspend timer to expire. Expect runtime_status=suspended and power/control=auto. During subsequent playback, verify stereo PCM, speaker DAC 0x02 on channel 0, and pins 0x14 and 0x1b output-enabled and unmuted.

Hardware verification covered full sound after repeated codec idle/wake cycles, recognizable microphone recording, wired headphones with speaker auto-mute, speaker restoration after unplugging, actual laptop suspend/resume, and microphone recording after resume. The kernel was boot-tested; the stereo rule was then activated and verified across a WirePlumber restart and laptop suspend/resume.

Fallback

The xingyao-speakers-workaround boot entry uses the unpatched kernel and the previously tested userspace workaround. Its system service checks board, codec, subsystem, DAC selection and EAPD, resolves the codec device from Generic_1, then enables 0x1b with raw HDA verbs. A resume hook restarts the service. It keeps only this codec's power/control=on, because raw verb settings reset after codec autosuspend; this may increase idle power consumption. Stopping that fallback service restores the original pin input/mute state and power/control=auto. Use the fallback boot entry if the patched driver regresses after a kernel update.

References and checks

nix eval -f usr/gui/xingyao-audio/test.nix # on techrevo
nix eval -f sys/gui/xingyao-audio/test.nix
python3 sys/gui/xingyao-audio/test.py
{ pkgs, lib, ... }: let
  amixer = "${pkgs.alsa-utils}/bin/amixer";
  initialize = pkgs.writeShellScript "xingyao-audio" ''
    set -eu
    ${amixer} -q -c Generic_1 sset Master 0dB unmute
    ${amixer} -q -c Generic_1 sset Speaker 0dB unmute
    ${amixer} -q -c Generic_1 sset Capture 0dB cap
  '';
  checkHardware = pkgs.writeShellScript "check-xingyao-audio" ''
    test "$(< /sys/class/dmi/id/board_name)" = "XINGYAO Series-P916F-STX" &&
      ${pkgs.gnugrep}/bin/grep -q '^Vendor Id: 0x10ec0256$' /proc/asound/Generic_1/codec#0 &&
      ${pkgs.gnugrep}/bin/grep -q '^Subsystem Id: 0x1d05e004$' /proc/asound/Generic_1/codec#0
  '';
in lib.mkIf (lib.trim (builtins.readFile /etc/hostname) == "techrevo") {
  # This model's UCM profile selects the unusable ACP-PDM capture path.
  xdg.configFile."wireplumber/wireplumber.conf.d/51-xingyao-audio.conf".text = builtins.toJSON {
    "monitor.alsa.rules" = [{
      matches = [{ "device.name" = "alsa_card.pci-0000_c1_00.6"; }];
      actions.update-props."api.alsa.use-acp" = false;
    } {
      matches = [{ "node.name" = "alsa_output.pci-0000_c1_00.6.playback.0.0"; }];
      # Raw four-channel playback leaves the shared speaker DAC on silent channels 3/4.
      actions.update-props = {
        "audio.channels" = 2;
        "audio.position" = [ "FL" "FR" ];
      };
    }];
  };

  # With ACP disabled, hardware switches must be initialized separately.
  systemd.user.services.xingyao-audio = {
    Unit = {
      Description = "Initialize Xingyao 14 ALC256 capture and speakers";
      After = [ "wireplumber.service" ];
      PartOf = [ "wireplumber.service" ];
    };
    Service = {
      Type = "oneshot";
      ExecCondition = "${checkHardware}";
      ExecStart = "${initialize}";
      RemainAfterExit = true;
    };
    Install.WantedBy = [ "wireplumber.service" ];
  };
}
let
  pkgs = import <nixpkgs> {};
  hm = import <home-manager/modules> {
    inherit pkgs;
    configuration = {
      imports = [ ./. ];
      home = { stateVersion = "25.11"; username = "dummy"; homeDirectory = "/dummy"; };
    };
  };
  cfg = hm.config;
  file = cfg.xdg.configFile."wireplumber/wireplumber.conf.d/51-xingyao-audio.conf" or null;
  service = cfg.systemd.user.services.xingyao-audio or {};
in pkgs.lib.debug.throwTestFailures { failures = pkgs.lib.runTests (pkgs.lib.optionalAttrs
  (pkgs.lib.trim (builtins.readFile /etc/hostname) == "techrevo") {
  test-card-rule = {
    expr = if file == null then null else
      builtins.head (builtins.fromJSON file.text)."monitor.alsa.rules";
    expected = {
      matches = [{ "device.name" = "alsa_card.pci-0000_c1_00.6"; }];
      actions.update-props."api.alsa.use-acp" = false;
    };
  };
  test-speaker-stereo-rule = {
    expr = if file == null then [] else builtins.filter
      (rule: rule.matches == [{ "node.name" = "alsa_output.pci-0000_c1_00.6.playback.0.0"; }])
      (builtins.fromJSON file.text)."monitor.alsa.rules";
    expected = [{
      matches = [{ "node.name" = "alsa_output.pci-0000_c1_00.6.playback.0.0"; }];
      actions.update-props = {
        "audio.channels" = 2;
        "audio.position" = [ "FL" "FR" ];
      };
    }];
  };
  test-restart-with-wireplumber = {
    expr = {
      after = service.Unit.After or [];
      partOf = service.Unit.PartOf or [];
      wantedBy = service.Install.WantedBy or [];
      remain = service.Service.RemainAfterExit or false;
    };
    expected = {
      after = [ "wireplumber.service" ];
      partOf = [ "wireplumber.service" ];
      wantedBy = [ "wireplumber.service" ];
      remain = true;
    };
  };
}); }
{ config, lib, ... }: {
  # Manage ~/Gist/.stignore as a real file, not as a Home Manager symlink inside
  # the Syncthing folder. The generated source lives outside ~/Gist, and onChange
  # copies it into place only when the managed content changes. This lets multiple
  # modules contribute ignore patterns while avoiding synced /nix/store symlinks.
  # TODO: make it a more general module
  options.my.syncthing.Gist-stignore = lib.mkOption {
    type = lib.types.listOf lib.types.str;
    default = [ ];
    description = ''
      Syncthing ignore patterns written to ~/Gist/.stignore.
      Patterns are interpreted relative to the ~/Gist Syncthing folder root.
    '';
  };

  config.home.file.".config/my-syncthing/Gist-stignore" = lib.mkIf (config.my.syncthing.Gist-stignore != [ ]) {
    text = lib.concatStringsSep "\n" config.my.syncthing.Gist-stignore;
    onChange = ''
      install -m 0644 ~/.config/my-syncthing/Gist-stignore ~/Gist/.stignore
    '';
  };
}
{ lib, ... }: {
  home.username = "xieby1";
  home.homeDirectory = "/home/xieby1";
  home.stateVersion = "25.05";
  imports = [(
    lib.modules.importApply ../../. {
      enableGraphics = false;
      enableExtendedCLI = false;
      enableServer = true;
    }
  )];
  news.display = "silent";
}
{ config, pkgs, lib, ... }: {
  options = {
    yq-merge = lib.mkOption {
      type = lib.types.attrsOf (
        lib.types.submodule {
          options = {
            expr = lib.mkOption {
              default = null;
              type = lib.types.nullOr lib.types.anything;
              description = "Value to be transformed by `generator` into home.home.<xxx>.text";
            };
            generator = lib.mkOption {
              # Cannot set type to lib.types.functionTo lib.types.lines,
              # or the output will be merged.
              type = lib.types.anything;
            };
            preOnChange = lib.mkOption {
              default = "";
              type = lib.types.lines;
            };
            postOnChange = lib.mkOption {
              default = "";
              type = lib.types.lines;
            };
            yqExtraArgs = lib.mkOption {
              default = "";
              type = lib.types.str;
            };
          };
        }
      );
      default = {};
      description = ''
        Use yq to merge config file.
        The yq-merge."<name>" receive attr same as `home.file`.
      '';
      example = ./test.nix;
    };
  };
  config = {
    home.file = builtins.mapAttrs (old_target: value: rec {
      text = value.generator value.expr;
      target = "${dirOf old_target}/yq-merge.${baseNameOf old_target}";
      onChange = /*bash*/ ''
        ${value.preOnChange}
        if [[ -e ${old_target} ]]; then
          # Operator: `*d` means deeply merge and deeply merge array
          # See: https://mikefarah.gitbook.io/yq/operators/multiply-merge
          # Noted: If the element of array is string, the old array will be overwrite.
          run ${pkgs.yq-go}/bin/yq ea ${value.yqExtraArgs} -i 'select(fileIndex == 0) *d select(fileIndex == 1)' ${old_target} ${target}
        else
          cat ~/${target} > ~/${old_target}
        fi
        ${value.postOnChange}
      '';
    }) config.yq-merge;
  };
}
let
  pkgs = import <nixpkgs> {};
  hm = import <home-manager/modules> {
    inherit pkgs;
    configuration = {
      imports = [../../.];
      home = {stateVersion="25.11"; username="dummy"; homeDirectory="/dummy";};
      # Config to be tested
      yq-merge.".config/miao.json" = {
        generator = builtins.toJSON;
        expr = { miao = "miao miao!"; };
        preOnChange = ''
          echo wang
        '';
        postOnChange = ''
          echo zhi
        '';
      };
    };
  };
in pkgs.lib.debug.throwTestFailures { failures = pkgs.lib.runTests {
  test-target = {
    expr = hm.config.home.file.".config/miao.json".target;
    expected = ".config/yq-merge.miao.json";
  };
  test-text = {
    expr = hm.config.home.file.".config/miao.json".text;
    expected = "{\"miao\":\"miao miao!\"}";
  };
  test-onChange = {
    expr = hm.config.home.file.".config/miao.json".onChange != "";
    expected = true;
  };
  test-preOnChange = {
    expr = pkgs.lib.hasInfix "echo wang" hm.config.home.file.".config/miao.json".onChange;
    expected = true;
  };
  test-postOnChange = {
    expr = pkgs.lib.hasInfix "echo zhi" hm.config.home.file.".config/miao.json".onChange;
    expected = true;
  };
}; }
let
  pkgs = import <nixpkgs> {};
  hm = import <home-manager/modules> {
    inherit pkgs;
    configuration = {
      imports = [../../.];
      home = {stateVersion="25.11"; username="dummy"; homeDirectory="/dummy";};
      # Config to be tested
      yq-merge.".config/env" = {
        generator = pkgs.lib.generators.toKeyValue {};
        expr = { miao = "miao miao!"; wang = "wang~"; };
        yqExtraArgs = "-p props -o props --properties-separator='='";
      };
    };
  };
in pkgs.lib.debug.throwTestFailures { failures = pkgs.lib.runTests {
  test-target = {
    expr = hm.config.home.file.".config/env".target;
    expected = ".config/yq-merge.env";
  };
  test-text = {
    expr = hm.config.home.file.".config/env".text;
    expected = "miao=miao miao!\nwang=wang~\n";
  };
  test-onChange = let
    # TODO: modularize the test-onChange, e.g. create a standalone dummy-home generation function
    dummy-home = pkgs.runCommand "test-onChange" {} ''
      mkdir -p $out/.config
      cd $out
      echo miao=1 > .config/env
      echo zhi=1 >> .config/env
      cat > .config/yq-merge.env <<EOF
      ${hm.config.home.file.".config/env".text}EOF
      run() { "$@"; }
      ${hm.config.home.file.".config/env".onChange}
    '';
  in {
    expr = builtins.readFile (dummy-home + /.config/env);
    expected = ''
      miao=miao miao!
      zhi=1
      wang=wang~
    '';
  };
}; }
let
  pkgs = import <nixpkgs> {};
  hm = import <home-manager/modules> {
    inherit pkgs;
    configuration = {
      imports = [
        ../../.
        # config 1
        {
          yq-merge.".config/miao.json" = {
            generator = builtins.toJSON;
            expr = { wang = "wang wang!"; };
          };
        }
        # config 2
        {
          yq-merge.".config/miao.json" = {
            generator = builtins.toJSON;
            expr = { miao = "miao miao!"; };
            preOnChange = ''
              echo wang
            '';
            postOnChange = ''
              echo zhi
            '';
          };
        }
      ];
      home = {stateVersion="25.11"; username="dummy"; homeDirectory="/dummy";};
    };
  };
in pkgs.lib.debug.throwTestFailures { failures = pkgs.lib.runTests {
  # The `generator` type must not be `lib.types.functionTo lib.types.lines`.
  # If it were, home-manager would merge the generated text from multiple configs.
  # This test verifies that the generator outputs are not merged.
  test-multi-config = {
    expr = hm.config.home.file.".config/miao.json".text;
    expected = "{\"miao\":\"miao miao!\",\"wang\":\"wang wang!\"}";
  };
}; }

nix-on-droid.nix

nix-on-droid.nix是安卓nix-on-droid的入口配置文件。 因为原生termux并不能直接运行nix, 所以nix-on-droid的作者基于termux使用proot搞出来一个能运行nix的termux分支。

nix-on-droid并未自带很多常用linux命令行工具, 因此nix-on-droid.nix主要负责配置那些在linux常用的,但nix-on-droid没有默认提供的命令行工具。 其他命令行工具的配置则复用home-manager的配置./usr。 下面是我的带注解的nix-on-droid.nix代码。

{ pkgs, config, ... }:

{

添加sshd-start命令,用于在安卓上启动sshd服务。 通常安卓上是没有root权限的,无法写/etc/目录的文件, 因此将ssh的tmp目录和配置目录设定到home下面。 这部分内容参考nix-on-droid wiki: SSH access

  imports = [(let
    sshdTmpDirectory = "${config.user.home}/sshd-tmp";
    sshdDirectory = "${config.user.home}/sshd";
    pathToPubKey = "${config.user.home}/.ssh/id_rsa.pub";
    port = 8022;
    sshd-start = pkgs.writeScriptBin "sshd-start" ''
      #!${pkgs.runtimeShell}

      echo "Starting sshd in non-daemonized way on port ${toString port}"
      ${pkgs.openssh}/bin/sshd -f "${sshdDirectory}/sshd_config" -D
    '';
  in {
    environment.packages = with pkgs; [
      sshd-start
    ];
    build.activation.sshd = ''
      $DRY_RUN_CMD mkdir $VERBOSE_ARG --parents "${config.user.home}/.ssh"
      $DRY_RUN_CMD cat ${pathToPubKey} > "${config.user.home}/.ssh/authorized_keys"

      if [[ ! -d "${sshdDirectory}" ]]; then
        $DRY_RUN_CMD rm $VERBOSE_ARG --recursive --force "${sshdTmpDirectory}"
        $DRY_RUN_CMD mkdir $VERBOSE_ARG --parents "${sshdTmpDirectory}"

        $VERBOSE_ECHO "Generating host keys..."
        $DRY_RUN_CMD ${pkgs.openssh}/bin/ssh-keygen -t rsa -b 4096 -f "${sshdTmpDirectory}/ssh_host_rsa_key" -N ""

        $VERBOSE_ECHO "Writing sshd_config..."
        $DRY_RUN_CMD echo -e "HostKey ${sshdDirectory}/ssh_host_rsa_key\nPort ${toString port}\n" > "${sshdTmpDirectory}/sshd_config"

        $DRY_RUN_CMD mv $VERBOSE_ARG "${sshdTmpDirectory}" "${sshdDirectory}"
      fi
    '';
  }) ({

自动配置termux。

    build.activation.termux = ''
      DIR=${config.user.home}/.termux
      mkdir -p $DIR
      symlink() {
        if [[ -e $1 && ! -e $2 ]]; then
          #echo "ln -s $1 $2"
          ln -s $1 $2
        fi
      }
      SRC=${config.user.home}/Gist/Config/termux.properties
      DST=$DIR/termux.properties
      symlink $SRC $DST
      SRC=${config.user.home}/Gist/Config/colors.properties
      DST=$DIR/colors.properties
      symlink $SRC $DST
    '';
  })];

下面是非常直观的软件安装。

  # Simply install just the packages
  environment.packages = with pkgs; [
    # User-facing stuff that you really really want to have
    vim  # or some other editor, e.g. nano or neovim
    # Some common stuff that people expect to have
    diffutils
    findutils
    util-linux
    tzdata
    hostname
    man
    gnugrep
    gnupg
    gnused
    gnutar
    bzip2
    gzip
    xz
    zip
    unzip
    gawk
    openssh
    nettools
    (lib.setPrio # make bintools less prior
      (busybox.meta.priority + 10)
      busybox
    )
  ];

  # Backup etc files instead of failing to activate generation if a file already exists in /etc
  environment.etcBackupExtension = ".bak";

  # Read the changelog before changing this value
  system.stateVersion = "21.11";

导入home-manager的配置文件./usr的配置。 如此操作,所有home-manager的软件和配置都能nix-on-droid中复用。

  home-manager.config = import ./usr;

  nix = {
    # TODO: reuse substituters from sys/default.nix
    substituters = [
      "https://mirrors.ustc.edu.cn/nix-channels/store"
      "https://cache.nixos.org/"
      "https://xieby1.cachix.org"
    ];
    trustedPublicKeys = [
      "cache.nixos.org-1:6NCHdD59X431o0gWypbMrAURkbJ16ZPMQFGspcDShjY="
      "xieby1.cachix.org-1:hVhQjWqdV3oGsSnyXSvzPgmDqcKm+EeKFtqsNK+eRew="
    ];
  };

  user.shell = "${pkgs.zsh}/bin/zsh";
}

起因:local-typst-env将pkgsBuildTarget的方法换成了buildEnv。 仔细一项不对啊,pkgsBuildTarget是buildtime deps,buildEnv(本质是writeClosures)是runtime deps。 为何buildEnv也会生效呢?

仔细看了看,是因为stdenv/setup.sh把propagatedXXX都写入到了$out/nix-support/propagated-xxx。 即将buildtime deps转化为了runtime deps。

TODO:nix如何寻找runtime deps这个我没细看,依稀记得是扫描$out里的所有路径?

  • DONE:去看看为什么stdenv/setup.sh要这么做? 我还看到了不少packages里,为了避免传播错误,显式地rm $out/nix-support/propagated-build-inputs。
  • 我去追踪了写$out/nix-support/propagated-build-inputs的历史, f1166e0bbbc5b (Eelco Dolstra 2006-08-07) 就引入了,所以这算是个是“特性”? 若不想做自动buildtime deps => runtime deps转换,则手动删掉$out/nix-support/propagated-xxx即可?
  • A: 因为stdenv/setup.sh运行的时候,已经获取不到derivation的信息了?所以得把propagated-xxx信息写入到$out/目录里

信息来源:<nixpkgs>/doc/stdenv/stdenv.chapter.md和nixpkgs源码

Describing Dependency

这一部分的内容总结: 说明stdenv里6个描述依赖的变量 depsBuildBuild, nativeBuildInputs, depsBuildTarget, depsHostHost, buildInputs, depsTargetTarget。

Nixpkgs follows the conventions of GNU autoconf. We distinguish between 3 types of platforms when building a derivation: build, host, and target. In summary, build is the platform on which a package is being built, host is the platform on which it will run. The third attribute, target, is relevant only for certain specific compilers and build tools.

Possible dependency types

Dep typeDep’s host platformDep’s target platform
build → *build(none)
build → buildbuildbuild
build → hostbuildhost
build → targetbuildtarget
host → *host(none)
host → hosthosthost
host → targethosttarget
target → *target(none)
target → targettargettarget

所有这些视角是我们要编译的包它看到的,相对它而言的,build、host、target是指它的build、host、target平台

删掉了三个*,看来是

  • build->*被build->host(nativeBuildInputs)代替了
  • host->*被host->target(buildInputs)代替了
  • target->*,*仅包含(none)和target,被target->target代替了
host → targetattribute nameoffset
build --> builddepsBuildBuild-1, -1
build --> hostnativeBuildInputs-1, 0
build --> targetdepsBuildTarget-1, 1
host --> hostdepsHostHost0, 0
host --> targetbuildInputs0, 1
target --> targetdepsTargetTarget1, 1

Propagating Dependency

这一部分的内容总结:

  • 说明stdenv里6个描述直接传递依赖的变量 depsBuildBuildPropagated, propagatedNativeBuildInputs, depsBuildTargetPropagated, depsHostHostPropagated, propagatedBuildInputs, depsTargetTargetPropagated。
  • 说明所有直接+间接(传递闭包)依赖的变量在stdenv/setup里的变量 pkgsBuildBuild, pkgsBuildHost, pkgsBuildTarget, pkgsHostHost, pkgsHostTarget, pkgsTargetTarget。

Propagating Algorithm

总结: Nix文档并未说明这个算法的普适性。(这个等未来有需求了再考虑吧) 这个算法的一些特殊情况确实是符合直觉的。

问题描述

  • X依赖Y,Y依赖Z。其中依赖通过上一节的6个变量描述。这样没啥问题。
  • 若现在X依赖Y,Y传递依赖Z。那X对Z的依赖怎么描述?

符号化上面的问题:

  • X依赖Y <=> dep(h, t, X, Y),其中h和t为X依赖Y的类型所决定的host/target offset,见上一节的表格
    • 例子X.nativeBuildInputs = [Y] => dep(-1, 0, X, Y)
  • X传递依赖Y <=> propagated-dep(h, t, X, Y)
    • 例子X.depsBuildTargetPropagated = [T] => propagated-dep(-1, 1, X, Y)
  • 注:为什么上面的推导符号用的是=>而不是<=>?
    • 因为nix里描述依赖的6+6个变量是描述的直接依赖,而未包含间接(传递得到的)依赖。 即存在dep(h, t, X, Y)但X.xxx = [...]里未包含Y的情况。
      • 你想知道什么变量里记录着所有(直接+间接)依赖? 往下看,在pkgs{Build/Host/Target}{Build/Host/Target}里。 这些变量需要stdenv的setup阶段得到。
  • 则符号化描述:
    • 已知dep(h_xy, t_xy, X, Y), propagated-dep(h_yz, t_yz, Y, Z)
    • 求dep(h_xz, t_xz, X, Z)

nix给出的算法:

  • h_xz = mapOffset(h_xy, t_xy, h_yz)
  • t_xz = mapOffset(h_xy, t_xy, t_yz)

我的逻辑分析

  • 已知:dep(h_xy, t_xy, X, Y)
  • Y视角下3个平台:b_y(-1), h_y(0), t_y(1)到X视角下的平台的映射关系:
    • b_y未知/没有啥逻辑?Y的build平台在X视角下没有任何意义才对。
      • 说人话,用X86-64原生编译的Y1和用AArch64交叉编译出的Y2,对于X都没影响才对。
      • 更进一步思考,Nix里上述两个包Y1和Y2其实是不一样的。这是不是源自于这里?
        • 这个未来再说吧
    • h_y -> h_xy:逻辑解读:字面意思而已。h_xy就是就是y的h(h_y)在X视角下的平台。
    • t_y -> t_xy:逻辑解读:字面意思而已。t_xy就是就是y的t(t_y)在X视角下的平台。

mapOffset(h, t, i)分析

  • nix文档的定义let mapOffset(h, t, i) = i + (if i <= 0 then h else t - 1)
    • 这个公式写这么复杂,实属徒增代码阅读复杂度。其实就是下面3种情况(完全枚举):
    • mapOffset(h_xy, t_xy, -1) = -1 + h_xy
      • b_y -> h_xy - 1
    • mapOffset(h_xy, t_xy, 0) = h_xy
      • h_y -> h_xy
    • mapOffset(h_xy, t_xy, 1) = t_xy
      • t_y -> t_xy
  • 即符合我的逻辑分析。b_y -> h_xy - 1算是一个自然延伸。

See How Propagating Algorithm Runs

上述传递算法的实际运作过程,在stdenv/setup(<nixpkgs>/pkgs/stdenv/generic/setup.sh)中。 核心代码框架精简如下(伪代码用了rust的高亮,实际是bash代码):

#![allow(unused)]
fn main() {
findInputs(pkg, hostOffset, targetOffset) {
  // 往6个pkgsXXX变量中对应的一个里添加pkg
  // eval "$var"'+=("$pkg")'
  pkgs{Build/Host/Target}{Build/Host/Target} += pkg

  for pkgNext in 6个直接传递依赖变量里的包 {
    hostOffsetNext = mapOffset(h, t, relHostOffset)
    targetOffsetNext = mapOffset(h, t, relTargetOffset)
    // 自迭代
    findInputs(pkgNext, hostOffsetNext, targetOffsetNext)
  }
}
}

所以依赖图的遍历过程在stdenv/setup中findInputs函数完成。 遍历后得到所有依赖(直接依赖、间接依赖)放入了6个pkgs{Build/Host/Target}{Build/Host/Target}变量中。 还需要注意的是,依赖传递通过$pkg/nix-support/对应的文件propogate文件实现。

注:6个pkgs{Build/Host/Target}{Build/Host/Target}为数组变量,

  • 若用$pkgs{Build/Host/Target}{Build/Host/Target}则仅显示第一个元素,这是bash的特性
    • 例:$pkgsHostTarget仅为第一个元素
  • 需要用${pkgs{Build/Host/Target}{Build/Host/Target}[@]}才会显示所有元素。
    • 例:${pkgsHostTarget[@]}为所有元素

pkgs.callPackage vs pkgs.<lua>.pkgs.callPackage

  • Regular Lua modules (no pkgs dependencies): use pkgs.<lua>.pkgs.callPackage from pkgs/development/lua-modules/generated-packages.nix

  • Lua modules depending on pkgs packages: use pkgs/top-level/lua-packages.nix

    The callPackage inherited here is still callPackage (from pkgs), for these reasons:

    1. In pkgs/development/interpreters/lua-5/default.nix:

      luaPackagesFun = callPackage ../../../top-level/lua-packages.nix {
        lua = self;
      };
      

      Here callPackage refers to pkgs.callPackage.

    2. luaPackagesFun is then passed to:

      makeScopeWithSplicing' {
        inherit otherSplices;
        f = lib.extends extensions luaPackagesFun;
      }
      

    ⚠️ Caution: The makeScopeWithSplicing' used here comes from pkgs/top-level/splice.nix — it already includes pkgs.newScope and only accepts a single attrset {otherSplices, f, ...}.

    This is easy to confuse with lib/customisation.nix's makeScopeWithSplicing', which accepts two attr parameters.

    Therefore, Lua's makeScopeWithSplicing' call extends the original pkgs scope.

Module

nixpkgs/lib/modules.nix: 从loadModule可以看出,imports可以接受Function、Attr、路径,不能够嵌套List。

Nixpkgs

nixpkgs crossSystem

  • default.nix
    • pkgs/top-level/impure.nix
      • pkgs/top-level/default.nix
        • lib.systems.elaborate crossSystem0;
          • lib/systems/default.nix: elaborate
            • parsed = parse.mkSystemFromString ... args.system; // args.system = crossSystem
              • lib/systems/parse.nix
                • mkSystemFromString = s: mkSystemFromSkeleton (mkSkeletonFromList (lib.splitString "-" s));
                  • mkSkeletonFromList

注意mkSkeletonFromList通过 ${toString (length l)} 实现了一个根据l长度的switch case。

crossSystem的4个域分别为cpu-vendor-kernel-abi

import nixpkgs

import <nixpgks> {} 的加载流程

  • default.nix
    • pkgs/top-level/impure.nix
      • pkgs/top-level/default.nix
        • stdenvStages import pkgs/stdenv/default.nix
        • allPackages import pkgs/top-level/stage.nix
          • allPackages import pkgs/top-level/all-packages.nix
        • boot = import pkgs/stdenv/booter.nix

vim_configurable.override {python = python3} vimUtils.makeCustomizable (vim.override {python = python3}) vimUtils.makeCustomizable (vim.override {python = python3})

似乎是一个浮现override变量的最小集 f = a:{res = a+1;} fo = pkgsMiao.makeOverride f f 2

Zsh Completion in NixOS

Overview

In NixOS, zsh completion functions are discovered through a combination of:

  • The fpath variable configured by the NixOS zsh module
  • The NIX_PROFILES environment variable
  • The environment.pathsToLink NixOS option

How It Works

1. Zsh fpath Configuration

The NixOS zsh module (nixos/modules/programs/zsh/zsh.nix:198-202) injects the following into every interactive zsh shell:

# Tell zsh how to find installed completions.
for p in ${(z)NIX_PROFILES}; do
  fpath=($p/share/zsh/site-functions $p/share/zsh/$ZSH_VERSION/functions $p/share/zsh/vendor-completions $fpath)
done

This tells zsh to search for completion functions under share/zsh/ within each profile directory.

2. NIX_PROFILES

NIX_PROFILES is an environment variable set by NixOS that contains a space-separated list of profile directories, typically including:

  • /run/current-system/sw (system packages)
  • User profiles (e.g., $HOME/.nix-profile)

NixOS does not symlink every file from every installed package into /run/current-system/sw. Instead, it uses a whitelist approach via environment.pathsToLink (nixos/modules/config/system-path.nix:134-141).

The zsh module adds:

environment.pathsToLink = lib.optional cfg.enableCompletion "/share/zsh";

(nixos/modules/programs/zsh/zsh.nix:314)

This ensures that share/zsh/ directories from all packages in environment.systemPackages are symlinked into /run/current-system/sw/share/zsh/, making them discoverable by zsh via fpath.

Why This Matters

Without environment.pathsToLink = ["/share/zsh"]:

  • Packages like git, nix-zsh-completions, etc. would install their completion files in the Nix store
  • But no symlinks would exist at /run/current-system/sw/share/zsh/
  • Zsh would search the paths in fpath and find nothing
  • Tab completion for system packages would not work

Default Paths Linked by NixOS

NixOS links a sensible set of directories by default (nixos/modules/config/system-path.nix:188-205):

environment.pathsToLink = [
  "/bin"
  "/etc/xdg"
  "/etc/gtk-2.0"
  "/etc/gtk-3.0"
  "/lib"
  "/sbin"
  "/share/emacs"
  "/share/hunspell"
  "/share/org"
  "/share/themes"
  "/share/vulkan"
  "/share/kservices5"
  "/share/kservicetypes5"
  "/share/kxmlgui5"
  "/share/systemd"
  "/share/thumbnailers"
];

Note that /share/zsh is not in this default list — it is added by the zsh module only when completion is enabled.

Key Code Locations

FileLinesDescription
nixos/modules/config/system-path.nix134-141environment.pathsToLink option definition
nixos/modules/config/system-path.nix188-205Default pathsToLink values
nixos/modules/programs/zsh/zsh.nix198-202fpath configuration in zsh init
nixos/modules/programs/zsh/zsh.nix314Zsh module adding /share/zsh to pathsToLink
pkgs/build-support/buildenv/default.nix42-45buildEnv pathsToLink parameter documentation

打包/编译32位程序

参考Packaging/32bit Applications。

仅32位

打包使用pkgs.pkgsi686Linux.stdenv.mkDerivation

编译使用pkgs.pkgsi686Linux.gcc

32位且64位

打包使用pkgs.multiStdenv.mkDerivation。

编译使用pkgs.gcc_multi。

Auto Push Packages to Cachix

Objective: Automatically push specific built packages to cachix during home-manager switch/nixos-rebuild switch/nix-shell.

Although there are several existing ways to achieve this:

However, the granularity of these methods is coarse; they push all packages to cachix. Is there a way to allow users to control which packages are pushed?

My Explorations

Possible solutions: Add a wrapper called cachixPackages, which recives the packages to be pushed and cachix information. This cachixPackages is a dummy package whose build stages will push the packages to cachix. However, normal nix packages are not allowed network access during building. To tackle this, like how fetch* series functions are implemented, the fixed-output derivation can be utilized to allow network access.

However, the above method seems not work as below, because cachix needs accesses to some resources beyond nix-build process (such as nix-build's sandbox).

nix-build example.nix
...
cachix: CppStdException e "\ESC[31;1merror:\ESC[0m creating directory '\ESC[35;1m/nix/var\ESC[0m': \ESC[35;1mPermission denied\ESC[0m"(Just "nix::SysError")
result 1
...

Even though I disable the nix-build sandbox by using --no-sandbox, the cachix still does not satisfy as below.

$ nix-build example.nix --no-sandbox
...
cachix: CppStdException e "\ESC[31;1merror:\ESC[0m cannot open connection to remote store '\ESC[35;1mdaemon\ESC[0m': \ESC[35;1m\ESC[31;1merror:\ESC[0m reading from file: \ESC[35;1mConnection reset by peer\ESC[0m\ESC[0m"(Just "nix::Error")
...

If you curious about my demo of cachixPackages and its example, see cachix-package.nix and example.nix.

cachixPackage

This file try to implement a package wrapper, which will automatically push pkg to cachix upon building. However, this method seems not work, due to limited resources in nix-build environment. For more details, see here.

{ cachix
, stdenv
, writeShellScript
}:

{ pkg
, sha256
, cachix_dhall
, cachix_name
, name ? "cachixed"
}:

builtins.derivation {
  inherit name;
  system = builtins.currentSystem;
  builder = writeShellScript "cachix-package-builder" ''
    source ${stdenv}/setup
    echo ${pkg} > $out
    if [[ -f "${cachix_dhall}" ]]; then
      ${cachix}/bin/cachix -c ${cachix_dhall} push ${cachix_name} ${pkg}
      result=$?
      echo result $result
      exit $result
    fi
  '';

  outputHashMode = "flat";
  outputHashAlgo = "sha256";
  outputHash = sha256;
}

Example for cachixPackage

To run the example:

# run with nix-build sandbox
nix-build example.nix
# run without nix-build sandbox
nix-build example.nix --no-sandbox
let
  pkgs = import <nixpkgs> {};
  cachixPackage = import ./cachix-package.nix {inherit (pkgs) cachix stdenv writeShellScript;};
in cachixPackage {
  pkg = pkgs.hello;
  sha256 = "01vm275n169r0ly8ywgq0shgk8lrzg79d1aarshwybwxwffj4q0q";
  cachix_dhall = /home/xieby1/Gist/Config/cachix.dhall;
  cachix_name = "xieby1";
}

备份binary cache

场景

官方binary cache没有的包, 自己花了很长时间编译出来。 值得把编译出来的的包及其依赖全部保存下来。

目前的问题

nix copy --to 备份的/nix/store如何使用?

交叉编译和安装跨平台程序

nixpkgs原生支持x86和arm指令集。 通过对nixpkgs配置可以轻松实现交叉编译, 跨平台程序的安装等功能。

太长不看

  • x86_64上的aarch64交叉编译器

    (with import <nixpkgs> {crossSystem="aarch64-linux";}; stdenv.cc)

  • aarch64的hello应用程序

    (with import <nixpkgs> {localSystem.system="aarch64-linux";crossSystem="aarch64-linux";}; hello)

  • 应用于nix-shell的例子

    shell_cross_platform.nix

目录

简介

nixpkgs1众多输入参数中,包含localSystem和crossSystem2。

  • localSystem

    The system packages will be built on.

    本地系统,即工具链运行的平台。

  • crossSystem

    The system packages will ultimately be run on.

    程序运行的平台。

通过localSystem和crossSystem不同值的组合, 可以实现交叉编译、安装其他架构的原生应用。 下面从localSystem和crossSystem的语法和应用两方面进行介绍。 语法章节从nixpkgs源码的角度出发,介绍其语法的组成。 应用章节围绕一个nix-shell脚本的实际例子, 介绍x86_64平台的交叉编译和安装aarch64架构的原生应用的方法。

localSystem和crossSystem的语法

localSystem和crossSystem由4个维度去刻画一个系统:cpu, vendor, kernel, abi。 localSystem和crossSystem的值为字符串或者{system=字符串;}3。 system字符串为可以包含前述4个维度的1~4个维度。 nix在解析时会将省略的维度按以某些默认值补充完整。 维度之间之间用-分割。 因此system字符串形式上为"cpu-vendor-kernel-abi"。 字符串不同数量的维度及其可用的值, 按匹配优先级由高到低列举如下4,

cpu-vendor-kernel-abi

system字符串cpuvendorkernelabi
"avr"avrnoneunknown
"{cpu}-cygwin"{cpu}windowscygnus
"{cpu}-windows"{cpu}windowsmsvc
"{cpu}-elf"{cpu}unknownnoneelf
"{cpu}-{kernel}"{cpu}{kernel}
"{cpu}-apple-{kernel}"{cpu}apple{kernel}
"{cpu}-linux-gnu"{cpu}linuxgnu
"{cpu}-{vendor}-mingw32"{cpu}{vendor}windows
"{cpu}-{vendor}-wasi"{cpu}{vendor}wasi
"{cpu}-{vendor}-redox"{cpu}{vendor}redox
"{cpu}-{vendor}-mmixware"{cpu}{vendor}mmixware
"{cpu}-{vendor}-netbsd*"{cpu}{vendor}netbsd*
"{cpu}-{vendor}-eabi"{cpu}unknown{kernel}eabi
"{cpu}-{vendor}-eabihf"{cpu}unknown{kernel}eabihf
"{cpu}-{kernel}-elf"{cpu}unknown{kernel}elf
"{cpu}-*-{ghcjs}"{cpu}unknownghcjs
"{cpu}-{vendor}-genode"{cpu}{vendor}genode
"{cpu}-{vendor}-{kernel}-{abi} "{cpu}{vendor}{kernel}{abi}

cpu

cpu字符串可取的值列举如下5,

cpu字符串bitssignificantBytefamilyversionarch
"arm"32littleEndian"arm"
"armv5tel"32littleEndian"arm""5""armv5t"
"armv6m"32littleEndian"arm""6""armv6-m"
"armv6l"32littleEndian"arm""6""armv6"
"armv7a"32littleEndian"arm""7""armv7-a"
"armv7r"32littleEndian"arm""7""armv7-r"
"armv7m"32littleEndian"arm""7""armv7-m"
"armv7l"32littleEndian"arm""7""armv7"
"armv8a"32littleEndian"arm""8""armv8-a"
"armv8r"32littleEndian"arm""8""armv8-a"
"armv8m"32littleEndian"arm""8""armv8-m"
"aarch64"64littleEndian"arm""8""armv8-a"
"aarch64_be"64bigEndian"arm""8""armv8-a"
"i386"32littleEndian"x86""i386"
"i486"32littleEndian"x86""i486"
"i586"32littleEndian"x86""i586"
"i686"32littleEndian"x86""i686"
"x86_64"64littleEndian"x86""x86-64"
"mips"32bigEndian"mips"
"mipsel"32littleEndian"mips"
"mips64"64bigEndian"mips"
"mips64el"64littleEndian"mips"
"mmix"64bigEndian"mmix"
"m68k"32bigEndian"m68k"
"powerpc"32bigEndian"power"
"powerpc64"64bigEndian"power"
"powerpc64le"64littleEndian"power"
"powerpcle"32littleEndian"power"
"riscv32"32littleEndian"riscv"
"riscv64"64littleEndian"riscv"
"s390"32bigEndian"s390"
"s390x"64bigEndian"s390"
"sparc"32bigEndian"sparc"
"sparc64"64bigEndian"sparc"
"wasm32"32littleEndian"wasm"
"wasm64"64littleEndian"wasm"
"alpha"64littleEndian"alpha"
"msp430"16littleEndian"msp430"
"avr"8"avr"
"vc4"32littleEndian"vc4"
"or1k"32bigEndian"or1k"
"js"32littleEndian"js"
cpuTypes

cpu之间的兼容性(具有传递性和自反性)如下6,

vendor

vendor字符串可取值"apple", "pc"(windows), "w64"(MinGW-w64), "none", "unknown"(default)。

kernel

kernel字符串可取值如下表7,

kernel字符串execFormatfamilies
"macos"machodarwin
"darwin"↑↑
"ios"machodarwin
"watchos"↑↑
"tvos"↑↑
"freebsd"elfbsd
"linux"elf
"netbsd"elfbsd
"none"unknown
"openbsd"elfbsd
"solaris"elf
"wasi"wasm
"redox"elf
"windows"pe
"win32"↑↑
"ghcjs"unknown
"genode"elf
"mmixware"unknown

abi

abi字符串可取的值列举如下8,

abi字符串floatabiNote
"cygnus"
"msvc"
"eabi"softfor ARM, PowerPC
"eabihf"hardfor ARM, PowerPC
"elf"
"androideabi"
"android"not 32-bit
"gnueabi"soft
"gnueabihf"hard
"gnu"not 32-bit
"gnuabi64"64
"musleabi"soft
"musleabihf"hard
"musl"
"uclibceabihf"soft
"uclibceabi"hard
"uclibc"
"unknown"

localSystem和crossSystem的应用

aarch64交叉工具链和程序的详细例子

以x86为本地指令集,localSystem和crossSystem的组合有以下效果

↓crossSystem↓ →localSystem→"x86_64-linux""aarch64-linux"
"x86_64-linux"通常情况
"aarch64-linux"交叉编译aarch64原生aarch64应用

因此基于这3种组合,可以在同一个shell环境中配置出3种软件, 代码见[cross_platform.nix]({{ site.repo_url }}/scripts/shell/cross_platform.nix)。

pkgs_arm_cross软件包的stdenv.cc为x86平台的arm交叉编译器。 nixpkgs channel只包含了原生x86应用和原生arm应用。 交叉编译的arm应用和原生arm应用的derivation不一样。 因此使用pkgs_arm_cross中的应用, 则会使用交叉编译器从源码开始编译arm应用, 而不是直接拉取nixpkgs channel的原生arm应用。

pkgs_arm_native软件包包含原生arm软件包。 从这个软件包拉取的应用和在arm平台的拉取到的应用一致。 例如figlet将直接从nix channel中拉取。

pkgs即x86原生的软件包。

shell_cross_platform.nix使用例子,

# 创建一个新的shell环境,包含stdenv.cc, figlet, qemu
$ nix-shell shell_cross_platform.nix

# 使用交叉编译工具链的c编译器
$ aarch64-unknown-linux-gnu-gcc helloworld.c -o helloworld
$ file helloworld
helloworld: ELF 64-bit LSB executable, ARM aarch64, version 1 (SYSV), dynamically linked, interpreter /nix/store/01kw0gb38phviarfv3fca49dpqh0qwlx-glibc-aarch64-unknown-linux-gnu-2.33-123/lib/ld-linux-aarch64.so.1, for GNU/Linux 2.6.32, with debug_info, not stripped

# arm原生应用
$ file `command -v figlet`
/nix/store/4f70f04bvd664n00jlnzccyzxd35lykw-figlet-2.2.5/bin/figlet: ELF 64-bit LSB executable, ARM aarch64, version 1 (SYSV), dynamically linked, interpreter /nix/store/rjc27shzir243n1w3127w713fijamf6v-glibc-2.33-123/lib/ld-linux-aarch64.so.1, for GNU/Linux 2.6.32, not stripped

# 直接执行figlet会出错
$ figlet
bash: /nix/store/4f70f04bvd664n00jlnzccyzxd35lykw-figlet-2.2.5/bin/figlet: cannot execute binary file: Exec format error

# 使用QEMU执行figlet即可
$ qemu-aarch64 `command -v figlet` miao!
           _             _
 _ __ ___ (_) __ _  ___ | |
| '_ ` _ \| |/ _` |/ _ \| |
| | | | | | | (_| | (_) |_|
|_| |_| |_|_|\__,_|\___/(_)

mips交叉工具链的例子

[cross_mips.nix]({{ site.repo_url }}/scripts/shell/cross_mips.nix)

crossSystem的传递

  • pkgs/top-level/stage.nix:
    • pkgsCross = lib.mapAttrs (n: crossSystem:
        nixpkgsFun { inherit crossSystem; })
        lib.systems.examples;
      
  • 其中pkgs/top-level/default.nix: nixpkgsFun = newArgs: import ./. (args // newArgs);
  • 也就是说lib.systems.examples的每个元素作为crossSystem传递给了pkgs/top-level/default.nix
  • pkgs/top-level/default.nix:
    • 首先crossSystem = lib.systems.elaborate crossSystem0
    • 接下来是推导
    • pkgs = boot stages;
    • pkgs = boot (stdenvStages {inherit crossSystem ...});
    • pkgs = boot (import ../stdenv {inherit crossSystem ...})
  • pkgs/stdenv/default.nix:
    • pkgs = boot (import ./cross {inherit crossSystem ...})
  • pkgs/stdenv/cross/default.nix:
    • pkgs = boot (lib.init bootStages ++ [(...) (..crossSystem..) (..crossSystem..)])
    • 包含了若干个stages,包括本地的bootStages的前几个stages、和crossSystem相关的3个stages(其实只有最后两个stages使用了crossSystem)
    • 这里需要搞清楚boot是怎么调用stages的
    • pkgs/top-level/default.nix:
      • boot = import ../stdenv/bo(__raw=false或未定义)oter.nix { inherit lib allPackages; };
      • boot = import ../stdenv/booter.nix { ...; allPackages = newArgs: import ./stage.nix ({inherit lib nixpkgsFun;} // newArgs);};
    • pkgs/stdenv/booter.nix:
      • 注释写了boot的功能,如下: 参数为一个函数数组,每个函数的输入为pkgset,输出要么是pkgset的参数(__raw=false或未定义),要么是pkgsset(__raw=true)。 (这里说的“pkgset的参数”会传给allPackages(是个函数,见上))

        # Type:
        #   [ pkgset -> (args to stage/default.nix) or ({ __raw = true; } // pkgs) ]
        #   -> pkgset
        #
        # In english: This takes a list of function from the previous stage pkgset and
        # returns the final pkgset. Each of those functions returns, if `__raw` is
        # undefined or false, args for this stage's pkgset (the most complex and
        # important arg is the stdenv), or, if `__raw = true`, simply this stage's
        # pkgset itself.
        
    • 所以最终还是得看下面两个使用了crossSystem的stages
  • pkgs/stdenv/cross/default.nix:
    • pkgs = boot (lib.init bootStages ++ [(...) ❶(..crossSystem..) ❷(..crossSystem..)])

    • ❶

        # Build tool Packages
        (vanillaPackages: {
          ...
          stdenv = assert ...;
            vanillaPackages.stdenv.override { targetPlatform = crossSystem; };
          ...
        })
      

      输入是vanillaPackages,输出是buildPackages的参数(为生成下一级的输入pkgset即buildPackages)。 因此,这一级(即buildPackages,pkgsCross..buildPackages)的3个平台为:

      buildhosttarget
      localSystemlocalSystemcrossSystem

      因此这一级的包是用来构建各种交叉工具链的包。

      注:nixpkgs里也有叫buildPackages的包,定义位于pkgs/top-level/stage.nix: buildPackages是pkgsBuildHost的别名,其中pkgs。

    • ❷

      # Run Packages
      (buildPackages: let
        ...
        stdenNoCC = adaptStdenv (buildPackages.stdenv.override (old: rec {
          buildPlatform = localSystem;
          hostPlatform = crossSystem;
          targetPlatform = crossSystem;
          ...
        }));
      in {
        ...
        stdenv = let
          baseStdenv = stdenNoCC.override {
            cc = ... buildPackages.gcc;
          }
        in ... baseStdenv;
        ...
      })
      

      这一级输入是buildPackages,输出就是我们平时pkgsCross.的包集合了。 这一级(即pkgsCross.)的3个平台为

      buildhosttarget
      localSystemcrossSystemcrossSystem

      其中要注意的是,pkgsCross..stdenv.cc就是pkgsCross..buildPackages.gcc。

引用

1

nixpkgs版本2022.01.20, commit hash: 7e149abe9db1509fa974bb2286f862a761ca0a07

2

nixpkgs/pkgs/top-level/default.nix

3

nixpkgs/lib/systems/default.nix: elaborate

4

nixpkgs/lib/systems/parse.nix: mkSkeletonFromList

5

nixpkgs/lib/systems/parse.nix: cpuTypes

6

nixpkgs/lib/systems/parse.nix: isCompatible

7

nixpkgs/lib/systems/parse.nix: kernels

8

nixpkgs/lib/systems/parse.nix: abis

安装NixOS

安装过程采用官方安装文档。 若已安装NixOS,则可跳过该步骤,直接看安装我的配置。

准备镜像

QEMU:

# 下载minimal ISO镜像:https://nixos.org/download.html
# 创建qemu硬盘(大小32GB)
qemu-img create -f qcow2 <output/path/to/nix.qcow2> 32G
# 将ISO安装到qemu硬盘
qemu-system-x86_64 -display gtk,window-close=off -vga virtio -device e1000,netdev=net0 -netdev user,id=net0,hostfwd=tcp::5556-:22,smb=/home/xieby1/ -m 4G -smp 3 -enable-kvm -hda </path/to/nix.qcow2> -cdrom </path/to/nixos-minial.iso> -boot d &

物理机:

# 暂时未探究命令行连接wifi的方法
# 所以目前使用gnome版ISO,而非minimal ISO。
# 下载gnome ISO镜像:https://nixos.org/download.html
# 启动U盘制作
sudo dd if=<path/to/nixos.iso> of=</dev/your_usb>
sync
# 重启进入U盘系统
# 注:需要在BIOS中取消secure boot,否则U盘无法启动。

分区

进入ISO系统后,创建分区。 一共需要3个分区:启动分区,操作系统分区,swap分区。 QEMU和物理机单系统需要创建这3个分区。 物理机双系统中启动分区已有,只需创建剩下2个分区。

QEMU:

sudo bash
parted /dev/sda -- mklabel msdos
parted /dev/sda -- mkpart primary 1MiB -8GiB
parted /dev/sda -- mkpart primary linux-swap -8GiB 100%

物理机单系统:

parted /dev/sda -- mklabel gpt
parted /dev/sda -- mkpart primary 512MiB -8GiB
parted /dev/sda -- mkpart primary linux-swap -8GiB 100%
parted /dev/sda -- mkpart ESP fat32 1MiB 512MiB
parted /dev/sda -- set 3 esp on

物理机双系统:

注:用disk创建的文件系统,权限不对,安装完后会有各种奇怪的问题。 因此推荐命令行操作,或者disk之后再执行下一节的指令。

还未探索parted详细用法,目前使用disk软件可视化分区。

  • 创建Ext4分区,取名为nixos
  • 创建Other->swap分区

文件系统

mkfs.ext4 -L nixos /dev/<系统分区>
mkswap -L swap /dev/<swap分区>
swapon /dev/<swap分区>
mkfs.fat -F 32 -n boot /dev/<启动分区>      # 物理机单系统
mount /dev/disk/by-label/nixos /mnt
mkdir -p /mnt/boot                          # 物理机单系统&双系统
mount /dev/disk/by-label/boot /mnt/boot     # 物理机单系统&双系统

基础配置

  • 生成配置文件
nixos-generate-config --root /mnt
  • 修改/mnt/etc/nixos/configuration.nix,
    • 修改名字networking.hostName
    • 启用代理
      • QEMU中宿主机器的ip为10.0.2.2
      • 安装过程中需要借助别的计算机或宿主机的的代理服务
      • 部署完我的nixos配置后,将会有clash服务,可以用虚拟机的代理服务
      • networking.proxy.default = "http://user:password@proxy:port/";
      • networking.proxy.noProxy = "127.0.0.1,localhost,internal.domain";
    • (QEMU和物理机单系统)取消以下注释以开启grub支持
      • boot.loader.grub.device = "/dev/sda";
    • 取消防火墙,以便kdeconnect正常运行
      • networking.firewall.enable = false;
    • (物理机双系统)自动探测操作系统启动项
      • boot.loader.grub.useOSProber = true;
    • 添加用户
      • users.users.xieby1
    • 添加软件
      • environment.systemPackages = with pkgs; [vim git];

最后

nixos-install
reboot

重启之后,进入NixOS。

How To Config Linux Kernel in Nix

Basic configuration tricks referring to nixos.wiki: Linux Kernel.

The Override System in Kernel

What do the pkgs.linux.override, pkgs.linux.overrideAttrs override?

To answer these questions, we need first to explore how kernel derivation is generated. When we type pkgs.linux, how this derivation is generated by nix?

* pkgs.linux
* pkgs/top-level/all-packages:
  * linuxPackages.kernel;
  * (linuxPackages = linuxKernel.packageAliases.linux_default).kernel;
  * (linuxPackages = (linuxKernel = recurseIntoAttrs (callPackage ./linux-kernels.nix { });).packageAliases.linux_default).kernel;
  * (recurseIntoAttrs (callPackage ./linux-kernels.nix { });).packageAliases.linux_default.kernel;
* pkgs/top-level/linux-kernels.nix:
  * packages.linux_6_6.kernel;
  * (recurseIntoAttrs (vanillaPackages // rtPackages // rpiPackages // { ... })).linux_6_6.kernel
  * (recurseIntoAttrs ({...; linux_6_6 = recurseIntoAttrs (packagesFor kernels.linux_6_6);...} // rtPackages // rpiPackages // { ... })).linux_6_6.kernel
  * (packagesFor kernels.linux_6_6).kernel
  * ((kernel_: {kernel = kernel_;}) kernels.linux_6_6).kernel
  * kernels.linux_6_6
  * ❶callPackage ../os-specific/linux/kernel/mainline.nix {
      branch = "6.6";
      kernelPatches = [
        kernelPatches.bridge_stp_helper
        kernelPatches.request_key_helper
      ];
    };
* pkgs/os-specific/linux/kernel/mainline.nix
  * buildLinux args'
  * ❷buildLinux ((builtins.removeAttrs args [ "branch" ])
    // {
      inherit src version;

      modDirVersion = lib.versions.pad 3 version;
      extraMeta.branch = branch;
    }
    // (args.argsOverride or { }))
  * (callPackage pkgs/os-specific/linux/kernel/generic.nix {}) args'
  * overridableKernel args'
  * (lib.makeOverridable ({...}: kernel.overrideAttrs (...))) args'
  * kernel.overrideAttrs (...)
  * ❸((callPackage ./manual-config.nix { inherit lib stdenv buildPackages; }) (basicArgs // { ... })).overrideAttrs (...)

因此

  • ❶ override is applied to pkgs/os-specific/linux/kernel/mainline.nix
  • ❷ argsOverride in override (old: {argsOverride = {...} }) is applied to pkgs/os-specific/linux/kernel/generic.nix
  • ❸ overrideAttrs is applied to pkgs/os-specific/linux/kernel/manual-config.nix

2026.04.27: By forge+kimi2.6

Lua LSP Not Auto-Attaching: Root Cause Analysis

Symptom

When opening a .lua file directly from the command line (nvim main.lua), the Lua LSP (emmylua_ls) did not attach automatically, even after waiting. However, running :e inside Neovim caused the LSP to attach immediately.

How the Cause Was Found

1. Verified the obvious first

  • emmylua_ls binary was present and executable in the nix wrapper PATH.
  • vim.lsp.config('emmylua_ls') was registered with correct settings.
  • vim.lsp.enable('emmylua_ls') was called in the active init file.
  • Running nvim main.lua in headless mode showed 0 clients attached initially.
  • Running :e and then checking showed emmylua_ls attached.

This confirmed the issue was specifically about startup timing, not missing configuration or a broken LSP binary.

2. Isolated the config with a minimal reproducer

Created a minimal init.lua that only did vim.lsp.config(...) + vim.lsp.enable(...) and tested it with nvim -u /tmp/minimal_init.lua main.lua. In this minimal setup, the LSP attached correctly.

This proved the issue was caused by something else in the user's full configuration.

3. Bisected the vimscript config

The user's init.lua is generated by home-manager, which sources a large vimscript block (extraConfig) before running the Lua block (extraLuaConfig).

By sourcing chunks of the vimscript config incrementally, the trigger was isolated to a single line in the vimscript block.

4. Identified the exact trigger

The trigger was syntax on in the vimscript extraConfig.

Root Cause

syntax on sources Neovim's runtime/syntax/syntax.vim, which contains:

" runtime/syntax/syntax.vim:26
filetype on
" ...
" runtime/syntax/syntax.vim:43-44
if !s:did_ft
  doautoall filetypedetect BufRead
endif

doautoall filetypedetect BufRead fires FileType for all already-existing buffers during init.lua sourcing.

Because home-manager places extraConfig (vimscript) before extraLuaConfig (Lua), the startup sequence becomes:

  1. Buffer main.lua is created during startup.
  2. syntax on triggers doautoall filetypedetect BufRead.
  3. FileType lua fires for main.lua.
  4. The nvim.lsp.enable autocmd does not exist yet, so nothing attaches.
  5. Later, vim.lsp.enable('emmylua_ls') runs in the Lua section.
  6. runtime/lua/vim/lsp.lua:635 checks vim.v.vim_did_enter == 1. It is 0 during init, so the doautoall catch-up is skipped.
  7. The FileType autocmd is created, but only fires for future FileType events.
  8. main.lua is permanently missed until :e re-triggers FileType.

Why :e Fixed It

:e re-triggers BufRead -> FileType for the current buffer. By then, vim.lsp.enable() has already been called, the nvim.lsp.enable autocmd exists, and the LSP attaches normally.

Why Removing syntax on Is the Correct Fix

Neovim's startup code in src/nvim/main.c:454-462 is explicitly designed to enable syntax after init.lua finishes:

source_startup_scripts(&params);
// ...
filetype_maybe_enable();
// Sources syntax/syntax.vim. We do this *after* the user startup scripts
// so that users can disable syntax highlighting with `:syntax off` if they wish.
syn_maybe_enable();

By putting syntax on in init.lua, you fight against Neovim's design:

  • It is redundant — Neovim enables syntax automatically after init.
  • It is harmful — it causes premature FileType events before Lua config runs.

References

  • runtime/syntax/syntax.vim:26,43-44
  • runtime/lua/vim/lsp.lua:610-637
  • src/nvim/main.c:454-462
  • src/nvim/syntax.c:3195-3202

Note on the "Neovim Bug" Misconception

This behavior is sometimes described as a "Neovim 0.11 bug" (e.g. issue #32910), but issue #32910 is actually an unrelated PR about codeAction/resolve support. The real issue here is a configuration ordering problem caused by syntax on in init, not a bug in vim.lsp.enable() itself.

Nix让你的团队成员不再受环境问题困扰

注:左下角菜单里可切换全屏

# Why do I need to enable home-manager systemd when username == root?
# Because I want to home-manager to manage the http and https ports.
# Only root can do it directly. So I need to run systemd under root.
let
  npinsed = import ~/.config/nixpkgs/npins;
  pkgs = import npinsed.nixpkgs {};
in pkgs.applyPatches {
  name = "home-manager-patched";
  src = npinsed.home-manager;
  postPatch = ''
    sed -i 's/mkIf (cfg.enable && config.home.username != "root")/mkIf cfg.enable/' modules/systemd.nix
  '';
}

See all fhs-shell scripts on [Github repo: scripts/fhs-shell]({{ site.repo_url }}/scripts/fhs-shell)

#!/usr/bin/env -S nix-shell --keep miao
{ pkgs ? import <nixpkgs> {} }:
(pkgs.buildFHSUserEnv {
  name = "dynamoRIO";
  targetPkgs = pkgs: with pkgs; [
    (hiPrio gcc)
    snappy
    zlib
    zlib.dev
    lz4
    lz4.dev
    libunwind
    libunwind.dev
  ];
  profile = ''
    export CC=gcc
    export CXX=g++
  '';
}).env
#!/usr/bin/env -S nix-shell --keep miao
let
  pkgs = import <nixpkgs> {};
  fhs = pkgs.buildFHSUserEnv {
    name = "hello";
    targetPkgs = p: with p; [
      hello
    ];
    profile = ''
      export MIAO=1
    '';
  };
in
  fhs.env
#!/usr/bin/env -S nix-shell --keep miao
{ pkgs ? import <nixpkgs> {} }:
let
  pin = builtins.derivation {
    name = "pin-3.25";
    system = builtins.currentSystem;
    src = pkgs.fetchurl {
      url = "https://software.intel.com/sites/landingpage/pintool/downloads/pin-3.25-98650-g8f6168173-gcc-linux.tar.gz";
      hash = "sha256-Q8D0QSNLDly2XK+XFOYdMxbx5N33eGVzESGTCgWGX6E=";
    };
    builder = pkgs.writeShellScript "pin-builder" ''
      # make mkdir and tar and other useful tools added to PATH
      source ${pkgs.stdenv}/setup
      mkdir -p $out
      # strip leading directory
      tar -xf $src --strip-components=1 --directory=$out
    '';
  };
in
(pkgs.buildFHSUserEnv {
  name = "pin";
  targetPkgs = pkgs: with pkgs; [
  ];
  profile = ''
    PATH+=":${pin}"
  '';
}).env
#!/usr/bin/env -S nix-shell --keep miao
{ pkgs ? import <nixpkgs> {} }:
let
  zigenv = import /home/xieby1/Codes/nix-zig-stdenv {
    target = "x86_64-unknown-linux-musl";
  };
  noPrefixStaticStdenvCC = pkgs.runCommand "linkCC" {} ''
    mkdir -p $out/bin
    for file in ${pkgs.pkgsStatic.stdenv.cc}/bin/*; do
      ln -s $file $out/bin/''${file##*-}
    done
  '';
in
(pkgs.buildFHSUserEnv {
  name = "spec";
  targetPkgs = pkgs: with pkgs; [
    # (hiPrio zigenv.pkgs.stdenv.cc)
    # (hiPrio clangStdenv.cc)
    # (hiPrio gcc)
    # (hiPrio pkgsStatic.stdenv.cc)
    # noPrefixStaticStdenvCC
    gfortran
    # uclibc
    # musl
    # musl.dev
    glibc.static
    glibc.dev
  ];
}).env
#!/usr/bin/env -S nix-shell --keep miao
# https://ryantm.github.io/nixpkgs/builders/special/fhs-environments/

{ pkgs ? import <nixpkgs> {} }:

(pkgs.buildFHSUserEnv {
  name = "simple-x11-env";
  targetPkgs = pkgs: (with pkgs;
    [ udev
      alsa-lib
    ]) ++ (with pkgs.xorg;
    [ libX11
      libXcursor
      libXrandr
    ]);
  multiPkgs = pkgs: (with pkgs;
    [ udev
      alsa-lib
    ]);
  runScript = "bash";
}).env
#!/usr/bin/env -S nix-shell --keep miao
# based on https://github.com/nix-community/nix-environments
#   git commit: 40d9d98bab7750bb5a1a9a3b5bcc1c91a652f3be
{ pkgs ? import <nixpkgs> {} }:
let
  name = "xilinx-fhs";
  h_content = builtins.toFile "h_content" ''
    # ${pkgs.lib.toUpper "${name} usage"}

    **Commands**

    * Show this help: `h`
    * Start Vitis HLS IDE: `vitis_hls`
    * Start Vitis HLS REPL: `vitis_hls -i`

    **Files**

    * Vitis HLS Doc: `2022.vitis_hls.ug1399.pdf`
    * Local command doc: `Xilinx/Vitis/2022.2/doc/eng/man/`
    * TODO: `ug871-vivado-high-level-synthesis-tutorial.pdf`
    * TODO: `ug902-vivado-high-level-synthesis.pdf`

    **Examples**

    * [Vitis HLS examples](https://github.com/Xilinx/Vitis-HLS-Introductory-Examples)
    * Run an example: `vitis_hls -f run_hls.tcl`
  '';
  _h_ = pkgs.writeShellScriptBin "h" ''
    ${pkgs.glow}/bin/glow ${h_content}
  '';
in
(pkgs.buildFHSUserEnv {
  inherit name;
  targetPkgs = pkgs: with pkgs; [
    _h_

    bash
    coreutils
    zlib
    lsb-release
    stdenv.cc.cc
    ncurses5
    xorg.libXext
    xorg.libX11
    xorg.libXrender
    xorg.libXtst
    xorg.libXi
    xorg.libXft
    xorg.libxcb
    xorg.libxcb
    # common requirements
    freetype
    fontconfig
    glib
    gtk2
    gtk3
    # vitis_hls gcc needs
    glibc.dev

    # to compile some xilinx examples
    opencl-clhpp
    ocl-icd
    opencl-headers

    # from installLibs.sh
    graphviz
    (lib.hiPrio gcc)
    unzip
    nettools
  ];
  multiPkgs = null;
  profile = ''
    export LC_NUMERIC="en_US.UTF-8"
    source ~/Xilinx/Vitis_HLS/*/settings64.sh
    h
  '';
}).env

See all fhs-shell scripts on [Github repo: scripts/pkgs]({{ site.repo_url }}/scripts/pkgs)

# TODO: 7z need dynamical link 7z.so
#   but static compilation prevents this behavior?
{pkgs ? import <nixpkgs> {}}:
let cross = import /home/xieby1/Codes/nix-zig-stdenv {
  inherit pkgs;
  target = "x86_64-unknown-linux-musl";
};
in
cross.pkgs.p7zip.overrideAttrs (old: {
  postPatch = old.postPatch + ''
    sed -i '/CC=/d' makefile.machine
    sed -i '/CXX=/d' makefile.machine
  '';
})
2022.04.19

在NixOS上使用Android程序

TLDR: 使用Android Studio提供的Android Emulator体验最好,其次是使用QEMU+x86Android。

Anbox & Waydroid

Anbox & Waydroid属于将Android runtime移植到Linux上的项目。 都需要安装内核模块。

Anbox已未维护。

Waydroid需要Wayland支持。目前我还采用X11。

qemu + x86 Android

虚拟机,没有找到图形和音频的加速方法。基本可用的程度。

  • vanilla x86 android: OK
  • lineageOS: OK
    • same to vanilla x86 android
    • wechat not work
  • phoenixOS: stuck in booting
# 安装在运行命令后添加-cdrom </path/to/iso> -boot -d
# 运行命令
qemu-system-x86_64 -m 4G -smp 3 -hda ~/Img/andx64_vcm141r5.qcow2 -enable-kvm -display gtk,window-close=off -device AC97

注:-vga virtio不能启动图形界面,原因未探索。

Google Android Emulator

使用nix提供的emulate-app.nix直接运行Google Android Emulator (魔改的QEMU)。

模拟器闪退无法启动,暂时没有尝试去解决。

参考

使用的nix脚本见android.nix

获取apk package和activity

aapt已经淘汰,现在使用的是aapt2,run by nix-alien。 例子,

nix-alien aapt2 dump badging </path/to/apk>

avdmanager找不到镜像

Error: Package path is not valid. Valid system image paths are:ository...

相关问题

从pkgs/development/mobile/androidenv/compose-android-packages.nix看, platformVersions, systemImageTypes, abiVersions需要和 pkgs/development/mobile/androidenv/repo.json 中的emulator项中的数据匹配。

看repo.json,而不是看sdkmanager --list,不一定有,但能看到已安装。

不匹配,在nix-build中不会报错,运行过程报上面的错误。

模拟器闪退

和问题类似GH: androidenv.emulateApp fails to start emulator (libvulkan.so.1: full) #121146

报错内容,没解决

cannot add library /nix/store/yz1p6cw09h3im4z7wmx7nshi054fzhw4-emulator-30.8.4/libexec/android-sdk/emulator/qemu/linux-x86_64/lib64/vulkan/libvulkan.so: failed
added library /nix/store/yz1p6cw09h3im4z7wmx7nshi054fzhw4-emulator-30.8.4/libexec/android-sdk/emulator/lib64/vulkan/libvulkan.so
emulator: WARNING: Ignoring invalid http proxy: Bad format: invalid port number (must be decimal)
Device state has been reached
LLVM ERROR: Cannot select: intrinsic %llvm.x86.sse41.pblendvb

debug 方法

参考https://nixos.wiki/wiki/Nixpkgs/Create_and_debug_packages#How_to_install_from_the_local_repository

使用本地nixpkgs,修改,nix-shell看变量 例子:

nix-shell -E 'with import "/home/xieby1/temp-nixpkgs" {config.android_sdk.accept_license = true;}; (androidenv.composeAndroidPackages {includeSystemImages =true; platformVersions=["16"];}).androidsdk'

nix expression调用关系

  • emulate-app.nix
    • compose-android-packages.nix
      • tools.nix
        • tools/26.nix
          • deploy-androidpackage.nix

PCI bus not available for hda

https://stackoverflow.com/questions/69297141/android-11-emulator-gives-pci-bus-not-available-for-hda

修改./result/bin/run-test-emulator添加-qemu -machine virt到Launch the emulator的指令后

/nix/store/0q68cfq7rnbw752l89fkxf425v1pb2r6-androidsdk/libexec/android-sdk/emulator/emulator -avd device -no-boot-anim -port $port $NIX_ANDROID_EMULATORFLAGS -qemu -machine virt &

Google Android Studio

使用Android Studio的AVD安装Android emulator最省心。

可以使用微信(公众号闪退),语音视频流畅,小游戏流畅。

redroid

暂时没成功

文档并未提供和各个参数相关的源文件?

#!/usr/bin/env nix-build

# https://nixos.wiki/wiki/Android
#  Building Android applications with the Nix package manager: https://sandervanderburg.blogspot.com/2014/02/reproducing-android-app-deployments-or.html
let
  # current nixpkgs-unstable
  pkgs = import (with import <nixpkgs> {}; fetchFromGitHub {
    owner = "NixOS";
    repo = "nixpkgs";
    rev = "1c851e8c92b76a00ce84167984a7ec7ba2b1f29c";
    hash = "sha256-vRxti8pOuXS0rJmqjbD8ueEEFXWSK22ISHoCWkhgzzg=";
  }){
    config.android_sdk.accept_license = true;
    config.allowUnfree = true;
  };
in pkgs.androidenv.emulateApp {
  name = "androidEmuApp";
  app = pkgs.fetchurl {
    url = "https://github.com/SimpleMobileTools/Simple-Calendar/releases/download/6.13.5/calendar-release.apk";
    sha256 = "12vzcd6klnk38b55szmd5a8ydc70fk6aak31qvlild83jy9z21zk";
  };
  enableGPU = false;
  # get these info by `pkgs/development/mobile/androidenv/repo.json`
  # see if installed `sdkmanager --list`
  platformVersion = "32";
  abiVersion = "x86";
  systemImageType = "google_apis";

  package = "com.simplemobiletools.calendar.pro";

  avdHomeDir = "$HOME/.android";
  sdkExtraArgs = {
    includeSystemImages = true;
  };
}
let
  pkgs = import <nixpkgs> {};
  squashfuse-with-headers = pkgs.pkgsStatic.squashfuse.overrideAttrs (old: {
    src = pkgs.fetchurl {
      url = "https://github.com/vasi/squashfuse/archive/e51978c.tar.gz";
      hash = "sha256-9UQCmtMNj73k5FQMV0uM3G04uU3wJamNhVGpRB8H00E=";
    };
    postInstall = ''
      mkdir -p $out/include/squashfuse
      cp *.h $out/include/squashfuse
    '';
  });
  srcRev = "c1ea7509bc179a05d907baca64f41875662f35f2";
in pkgs.stdenv.mkDerivation {
  name = "appimage-runtime";
  src = pkgs.fetchFromGitHub {
    owner = "AppImage";
    repo = "type2-runtime";
    rev = "${srcRev}";
    sha256 = "1gr853iz1x6pgyav3w1kqaaaz2ybbx67dcg74kj54yrwlakrh165";
  };
  nativeBuildInputs = with pkgs; [
    pkg-config
  ];
  buildInputs = (with pkgs.pkgsStatic; [
    squashfuse-with-headers
    fuse
    zstd
    zlib

    lz4.out
    lzo
    lzma.out
  ]) ++ (with pkgs; [
    glibc.static
  ]);
  sourceRoot = "source/src/runtime";
  buildPhase = ''
    export CFLAGS="-std=gnu99 -s -Os -D_FILE_OFFSET_BITS=64 -DGIT_COMMIT=\"${srcRev}\" -T data_sections.ld -ffunction-sections -fdata-sections -Wl,--gc-sections -static"
    export LIBS="-lsquashfuse -lsquashfuse_ll -lzstd -lz -llz4 -llzo2 -llzma"
    $CC -I${squashfuse-with-headers}/include/squashfuse -I${pkgs.pkgsStatic.fuse}/include/fuse -o runtime-fuse2.o -c $CFLAGS runtime.c
    $CC $CFLAGS runtime-fuse2.o $LIBS -lfuse -o runtime-fuse2
  '';
  installPhase = ''
    mkdir -p $out/bin
    cp runtime-fuse2 $out/bin/
  '';
}

# in pkgs.mkShell {
#   name = "appimage-runtime";
#   packages = (with pkgs.pkgsStatic; [
#     squashfuse-with-headers
#     fuse
#     zstd
#     zlib

#     lz4.out
#     lzo
#     lzma.out
#   ]) ++ (with pkgs; [
#     glibc.static
#     pkg-config
#   ]);
# }

# in (pkgs.buildFHSUserEnv {
#   name = "appimage-runtime-fhs";
#   targetPkgs = pkgs: (with pkgs.pkgsStatic; [
#     squashfuse-with-headers
#     fuse
#     zstd
#     zlib

#     lz4.out
#     lzo
#     lzma.out
#   ]) ++ (with pkgs; [
#     glibc.static
#     pkg-config
#   ]);
# }).env
let
  hm_aarch64 = import <home-manager/modules> {
    configuration = ~/.config/home-manager/home.nix;
    pkgs = import <nixpkgs> {
      localSystem.system="aarch64-linux";
      crossSystem="aarch64-linux";
    };
  };
  pkgs = import <nixpkgs> {};
in
  # TODO: only push minimal config
  builtins.filter (e: ! pkgs.lib.hasInfix "niri" e )
  hm_aarch64.config.cachix_packages
#!/usr/bin/env -S nix-build -o coremarks
{pkgs ? import <nixpkgs> {}}:
let
  # function mkCoremark
  mkCoremark = {
    pkgs ? import <nixpkgs> {},
    stdenv ? pkgs.stdenv,
    simple ? false,
  }:
  let
    name = "coremark";
    variant = pkgs.lib.concatStrings [
      "${stdenv.targetPlatform.config}"
      # TODO: all zig-env are static?
      # (if stdenv.targetPlatform.isStatic then ".static" else "")
      (if simple then ".simple" else "")
    ];
  in
  stdenv.mkDerivation {
    inherit name;
    src = pkgs.fetchFromGitHub {
      owner = "eembc";
      repo = "coremark";
      rev = "d26d6fdcefa1f9107ddde70024b73325bfe50ed2";
      sha256 = "0kd6bnrnd3f325ypxzn0w5ii4fmc98h16sbvvjikvzhm78y60wz3";
    };
    preBuild = ''
      # no float point insts
      export CFLAGS="-DHAS_FLOAT=0"

      # simple assumes CC = gcc, this is a bug!
      sed -i '/CC =/d' simple/core_portme.mak
      ${if simple
        then "export PORT_DIR=simple"
        else ""}
    '';
    buildFlags = ["compile"];
    installPhase = ''
      mkdir -p $out/bin
      mv coremark.exe $out/bin/${name}.${variant}.exe
    '';
  };
  zig-env-src = pkgs.fetchFromGitHub {
    owner = "Cloudef";
    repo = "nix-zig-stdenv";
    rev = "6de72ec32ecf0cfb9ad9dab5a8400d532e17f8c5";
    hash = "sha256-hQHOzjkHWO5YxQb3mgZJOfyIuvbiLFocVCMK/A9HTic=";
  };
in
pkgs.symlinkJoin {
  name = "coremarks";
  paths = [
    # x86_64 linux
    (mkCoremark {
      inherit (import zig-env-src {
        target = "x86_64-unknown-linux-gnu";
      }) stdenv;
    })
    # x86_64 linux static
    (mkCoremark {
      inherit (import zig-env-src {
        target = "x86_64-unknown-linux-musl";
      }) stdenv;
    })
    # aarch64 linux
    (mkCoremark {
      inherit (import zig-env-src {
        target = "aarch64-unknown-linux-gnu";
      }) stdenv;
    })
    # aarch64 linux static
    (mkCoremark {
      inherit (import zig-env-src {
        target = "aarch64-unknown-linux-musl";
      }) stdenv;
    })
    # riscv64 linux
    # (mkCoremark {
    #   inherit (import zig-env-src {
    #     target = "riscv64-unknown-linux-gnu";
    #   }) stdenv;
    # })
    # riscv64 linux static
    (mkCoremark {
      inherit (import zig-env-src {
        target = "riscv64-unknown-linux-musl";
      }) stdenv;
    })
    # x86_64 windows
    (mkCoremark {
      inherit (import zig-env-src {
        target = "x86_64-w64-mingw32";
      }) stdenv;
      simple = true;
    })
    # x86_64 darwin can only compiled on x86_64/aarch64 darwin
    #   https://github.com/NixOS/nixpkgs/issues/165804
    # while it is possible compile manually inside darling
    #(mkCoremark {
    #  stdenv = pkgs.pkgsCross.x86_64-darwin.stdenv;
    #})
  ];
}
#!/usr/bin/env -S nix-env -i -f
# xieby1: 2022.05.16
with (import <nixpkgs> {crossSystem = "mips-linux";}); {
  gdb = lib.lowPrio buildPackages.gdb;
  gcc = lib.lowPrio buildPackages.gcc;
}
#!/usr/bin/env nix-build
let
  pkgs = import (builtins.fetchTarball {
    url = "https://github.com/NixOS/nixpkgs/archive/e60c3e2abb8ae9df3d89820c706cc736fad01ff7.tar.gz";
    sha256 = "0vyjpf1jw4cvw7kfbk055faq08q4swz6v1h2mf9zw4r8frhqa73w";
  }) {};
in
pkgs.pkgsCross.aarch64-multiplatform.pkgsStatic.glib
let
  pkgs = import <nixpkgs> {};
  name = "etxlauncher";
  etxlauncher = pkgs.stdenv.mkDerivation {
    inherit name;
    src = ~/Downloads/ETXLauncher-12.0.4.7508-SP4-linux-x64.tar.gz;
    installPhase = ''
      mkdir -p $out
      cp -r * $out/
    '';
  };
  desktop = pkgs.makeDesktopItem {
    inherit name;
    desktopName = "ETX Client Launcher 12";
    exec = "${name} %u -gui";
    comment = "ETX Client Launcher";
    icon = "${etxlauncher}/icons/etxlauncher.128.png";
    categories = ["Application" "Network"];
    mimeTypes = ["x-scheme-handler/etx12"];
    noDisplay = true;
  };
in pkgs.buildFHSEnvBubblewrap {
  inherit name;
  runScript = pkgs.writeShellScript name ''
    export LD_LIBRARY_PATH=${pkgs.lib.makeLibraryPath [
      pkgs.gtk2
      pkgs.gdk-pixbuf
      pkgs.glib
      pkgs.libkrb5
      pkgs.libx11
      pkgs.libxext
      pkgs.gtk3
    ]}
    ${etxlauncher}/bin/etxlauncher $@
  '';
  # TODO: mime
  # xdg-mime default etxlauncher.desktop x-scheme-handler/etx12
  extraInstallCommands = ''
    mkdir -p $out/share/applications
    cp ${desktop}/share/applications/* $out/share/applications
  '';
  extraBwrapArgs = ["--bind $HOME/.local/share/${name} $HOME"];
  chdirToPwd = false;
}
#!/usr/bin/env -S nix-build -o fhs_helloworld

# xieby1: 2022.11.17
# inspired by
#   https://discourse.nixos.org/t/derivation-that-builds-standard-linux-binaries/21557/4
#   https://github.com/NixOS/nixpkgs/compare/master...ElvishJerricco:nixpkgs:run-in-fhs
# TODO-1:
#   I have copy all dependencies to a directory (ld-linux-x86-64.so.2, libc.so)
#   But result cannot run in chroot, error message is `cannot find libc.so`.
# TODO-2:
#   I didn't find a proper package/bundle tool
#   * nix-bundle: not work
#   * appimage: depends on libfuse.so, cannot run directly on nixos

{ pkgs ? import <nixpkgs> {} }:
let
  name = "helloworld";
  fhsEnv = pkgs.buildFHSUserEnv {
    name = "${name}-fhs";
    targetPkgs = pkgs: with pkgs; [
      gcc
      # gcc-unwrapped binutils-unwrapped
      glibc
      glibc.dev
    ];
    # refer to https://discourse.nixos.org/t/using-a-raw-gcc-inside-buildfhsuserenv/12864
    runScript = (pkgs.writeShellScript "${name}-fhsbuilder" ''
      # For gcc-unwrapped and binutils-unwrapped
      # export LIBRARY_PATH=/usr/lib
      # export C_INCLUDE_PATH=/usr/include
      # export CPLUS_INCLUDE_PATH=/usr/include
      # export CMAKE_LIBRARY_PATH=/usr/lib
      # export CMAKE_INCLUDE_PATH=/usr/include
      ## TODO: not work? have to add gcc -Wl,--dynamic-linker=/usr/lib64/ld-linux-x86-64.so.2 ?
      # export LDFLAGS=--dynamic-linker=/usr/lib64/ld-linux-x86-64.so.2

      # For gcc
      export NIX_LDFLAGS="--dynamic-linker=/usr/lib64/ld-linux-x86-64.so.2"
      gcc $src -o $out
    '');
  };
in
builtins.derivation {
  inherit name;
  system = builtins.currentSystem;
  src = builtins.toFile "${name}.c" ''
    #include <stdio.h>
    int main(void) {
      printf("Hello, world! \n");
      return 0;
    }
  '';
  builder = "${fhsEnv}/bin/${fhsEnv.name}";
}
let
  name = "perl";
  pkgs = import <nixpkgs> {};
  fhsEnv = pkgs.buildFHSUserEnv {
    name = "${name}-fhs";
    targetPkgs = pkgs: with pkgs; [
      gnumake
    ];
    runScript = (pkgs.writeShellScript "${name}-fhsbuilder" ''
      ls
      cd $src/tools/src
      ls
      DOPERL=1 ./buildtools
    '');
  };
in builtins.derivation {
  inherit name;
  system = builtins.currentSystem;
  src = /home/xieby1/Codes/spec2000;
  builder = "${fhsEnv}/bin/${fhsEnv.name}";
}
let
 pkgs = import <nixpkgs> {};
in
pkgs.stdenv.mkDerivation {
  name = "herdtool7";
  src = pkgs.fetchFromGitHub {
    owner = "herd";
    repo = "herdtools7";
    rev = "7c36d32e7e0dd546296ddd05c5279ae42665a4cf";
    hash = "sha256-gGxM2JYZwbtveQu3PRMKvr4XePJA0jtQK9WUEpCTn8c=";
  };
  buildInputs = [
    pkgs.which
    pkgs.ocamlPackages.ocaml
    pkgs.ocamlPackages.findlib
    pkgs.ocamlPackages.dune_3
    pkgs.ocamlPackages.menhir
    pkgs.ocamlPackages.menhirLib
    pkgs.ocamlPackages.zarith
  ];
  makeFlags = [
    "PREFIX=$(out)"
  ];
}
#!/usr/bin/env -S nix-build -o nix-binary-tarballs

Nix official installer (new)

Use nix (>2.18) binary-tarball script, which has not been merged into mainline nixpkgs.

See nix-binary-tarballs.nix for current nix binary-tarball script.

let
  pkgs = import <nixpkgs> {};
  nix_src = pkgs.fetchFromGitHub {
    owner = "NixOS";
    repo = "nix";
    rev = "d0c7da131fb64526bc72144949b6955c25367d92";
    hash = "sha256-Z4RlluZjNXH5BdJiXoe0k43Ry9ptK3jHAsKjlQ3jVZg=";
  };
in pkgs.symlinkJoin {
  name = "nix-binary-tarballs";
  paths = [
    (pkgs.callPackage "${nix_src}/scripts/binary-tarball.nix" {})
    (pkgs.callPackage "${nix_src}/scripts/binary-tarball.nix" {
      nix    = pkgs.pkgsCross.riscv64.nix;
      system = pkgs.pkgsCross.riscv64.nix.stdenv.system;
    })
    (pkgs.callPackage "${nix_src}/scripts/binary-tarball.nix" {
      nix    = pkgs.pkgsCross.loongarch64-linux.nix;
      system = pkgs.pkgsCross.loongarch64-linux.nix.stdenv.system;
    })
  ];
}
#!/usr/bin/env -S nix-build -o nix-binary-tarballs

Nix official installer

The binaryTarball function is extracted from nix-2.18's flake.nix

Noted: Although the latest nix has seperate binaryTarball as a independent file, current unstable nixpkgs still use nix-2.18, which embed binaryTarball function in nix/flake.nix. If reuse the binaryTarball file in new nix, then this script can be hugely simplified, e.g. nix-binary-tarballs-new.nix. As long as, new nix is merged to mainline nixpkgs, I will deprecate this script and adopt the new script.

let
  pkgs = import <nixpkgs> {};
  binaryTarball =
    { nix
    , buildPackages
    , cacert
    }:
    let
      installerClosureInfo = buildPackages.closureInfo { rootPaths = [ nix cacert ]; };
    in buildPackages.runCommand "nix-binary-tarball-${nix.version}" {
      #nativeBuildInputs = lib.optional (system != "aarch64-linux") shellcheck;
      meta.description = "Distribution-independent Nix bootstrap binaries for ${nix.stdenv.system}";
    } ''
      cp ${installerClosureInfo}/registration $TMPDIR/reginfo
      cp ${nix.src}/scripts/create-darwin-volume.sh $TMPDIR/create-darwin-volume.sh
      substitute ${nix.src}/scripts/install-nix-from-closure.sh $TMPDIR/install \
        --subst-var-by nix ${nix} \
        --subst-var-by cacert ${cacert}
    
      substitute ${nix.src}/scripts/install-darwin-multi-user.sh $TMPDIR/install-darwin-multi-user.sh \
        --subst-var-by nix ${nix} \
        --subst-var-by cacert ${cacert}
      substitute ${nix.src}/scripts/install-systemd-multi-user.sh $TMPDIR/install-systemd-multi-user.sh \
        --subst-var-by nix ${nix} \
        --subst-var-by cacert ${cacert}
      substitute ${nix.src}/scripts/install-multi-user.sh $TMPDIR/install-multi-user \
        --subst-var-by nix ${nix} \
        --subst-var-by cacert ${cacert}
    
      if type -p shellcheck; then
        # SC1090: Don't worry about not being able to find
        #         $nix/etc/profile.d/nix.sh
        shellcheck --exclude SC1090 $TMPDIR/install
        shellcheck $TMPDIR/create-darwin-volume.sh
        shellcheck $TMPDIR/install-darwin-multi-user.sh
        shellcheck $TMPDIR/install-systemd-multi-user.sh
    
        # SC1091: Don't panic about not being able to source
        #         /etc/profile
        # SC2002: Ignore "useless cat" "error", when loading
        #         .reginfo, as the cat is a much cleaner
        #         implementation, even though it is "useless"
        # SC2116: Allow ROOT_HOME=$(echo ~root) for resolving
        #         root's home directory
        shellcheck --external-sources \
          --exclude SC1091,SC2002,SC2116 $TMPDIR/install-multi-user
      fi
    
      chmod +x $TMPDIR/install
      chmod +x $TMPDIR/create-darwin-volume.sh
      chmod +x $TMPDIR/install-darwin-multi-user.sh
      chmod +x $TMPDIR/install-systemd-multi-user.sh
      chmod +x $TMPDIR/install-multi-user
      dir=nix-${nix.version}-${nix.stdenv.system}
      fn=$out/$dir.tar.xz
      mkdir -p $out/nix-support
      echo "file binary-dist $fn" >> $out/nix-support/hydra-build-products
      tar cvfJ $fn \
        --owner=0 --group=0 --mode=u+rw,uga+r \
        --mtime='1970-01-01' \
        --absolute-names \
        --hard-dereference \
        --transform "s,$TMPDIR/install,$dir/install," \
        --transform "s,$TMPDIR/create-darwin-volume.sh,$dir/create-darwin-volume.sh," \
        --transform "s,$TMPDIR/reginfo,$dir/.reginfo," \
        --transform "s,$NIX_STORE,$dir/store,S" \
        $TMPDIR/install \
        $TMPDIR/create-darwin-volume.sh \
        $TMPDIR/install-darwin-multi-user.sh \
        $TMPDIR/install-systemd-multi-user.sh \
        $TMPDIR/install-multi-user \
        $TMPDIR/reginfo \
        $(cat ${installerClosureInfo}/store-paths)
    '';
in pkgs.symlinkJoin {
  name = "nix-binary-tarballs";
  paths = [
    # local nix installer
    (pkgs.callPackage binaryTarball {})
    # riscv64 nix installer
    (pkgs.callPackage binaryTarball {nix=pkgs.pkgsCross.riscv64.nix;})
    # loongarch64 nix installer
    (pkgs.callPackage binaryTarball {nix=pkgs.pkgsCross.loongarch64-linux.nix;})
  ];
}

🐳Nix Docker🐋 for Multiple ISAs

This script is inspired by https://github.com/nix-community/docker-nixpkgs/images/nix

currently: this riscv64 nix docker can nix-env -iA nixpkgs.hello/tmux and so on, which is completely built from source including toolchains (stdenv) in x86/aarch64/riscv64/...

{ pkgs ? import <nixpkgs> {}
, pkgsCross ? pkgs
, useTmux ? true
}:
let
  name = "nix-docker-${pkgsCross.stdenv.system}";
  image = pkgs.dockerTools.buildImageWithNixDb {
    inherit name;
    copyToRoot = pkgs.buildEnv {
      name = "image-root";
      paths = (with pkgsCross; [
        bashInteractive
        cacert
        coreutils
        file
        gitMinimal
        gnutar
        nix
        openssh
        vim
        wget
      ]
      ++ lib.optional useTmux (tmux.override {withSystemd=false;})
      ) ++ [
        ./imageFiles
      ];
    };
    extraCommands = ''
      # for /usr/bin/env
      mkdir usr
      ln -s bin usr/bin

      # make sure /tmp exists
      mkdir -m 1777 tmp

      # need a HOME
      mkdir -vp root
    '';
    config = {
      Cmd = if useTmux
        then [ "/bin/tmux" ]
        else [ "/bin/bash" ];
      Env = [
        "NIX_BUILD_SHELL=/bin/bash"
        "PAGER=cat"
        "PATH=/bin"
        "SSL_CERT_FILE=${pkgs.cacert}/etc/ssl/certs/ca-bundle.crt"
        "USER=root"
      ];
    };
  };
in pkgs.writeShellScriptBin name ''
  command -v podman &> /dev/null || echo "podman not found TODO: install" || exit 1

  outName="$(basename ${image})"
  outHash=$(echo "$outName" | cut -d - -f 1)
  imageName=localhost/${name}:$outHash

  # check whether image has been loaded
  podman images $imageName | grep ${name} | grep $outHash &> /dev/null
  # image has not been loaded, then load it
  if [[ $? != 0 ]]; then
    podman load -i ${image}
  fi

  BINFMTS=""
  for binfmt in /run/binfmt/*; do
      BINFMTS+=" -v $(realpath $binfmt):$binfmt"
  done

  containerName=${name}-$outHash
  # run container
  OPTS=(
    "--name=$containerName"
    "$BINFMTS"
    "--network=host"
    "-it"
    "$imageName"
  )
  eval "podman run ''${OPTS[@]}"
  podman commit $containerName $imageName
  podman rm $containerName
''
#!/usr/bin/env nix-build

Instantiatio of nix dockers

For more details, see default.nix

{ pkgs ? import <nixpkgs> {}
, ...
}: [

x86_64 docker

  (import ./. {inherit pkgs; pkgsCross=pkgs.pkgsCross.gnu64;})

aarhc64 docker

  (import ./. {inherit pkgs; pkgsCross=pkgs.pkgsCross.aarch64-multiplatform;})

riscv64 docker

  (import ./. {inherit pkgs; pkgsCross=pkgs.pkgsCross.riscv64;})
]
let
  flake-compat = import (builtins.fetchTarball {
    url = "https://github.com/edolstra/flake-compat/archive/0f9255e01c2351cc7d116c072cb317785dd33b33.tar.gz";
    sha256 = "0m9grvfsbwmvgwaxvdzv6cmyvjnlww004gfxjvcl806ndqaxzy4j";
  });
  nix2nvchad = flake-compat {
    src=  builtins.fetchTarball {
      url = "https://github.com/nix-community/nix4nvchad/archive/360ff667893eab066b3db906a856de2956fc710e.tar.gz";
      sha256 = "01gvcg7nhzpizp4yzvww2x42i1ifsb7sygfwmqzrshqz47p1ir5y";
    };
  };
in nix2nvchad.defaultNix.packages."${builtins.currentSystem}".default
#!/usr/bin/env nix-build
# xieby1: 2022.05.24
# build static qemu (current version 6.1.1) into ./result/
# $ nix-build <this-file> -A qemu
# build static qemu-3.1.0 into ./result/
# $ nix-build <this-file> -A qemu31
# build and install static qemu
# $ nix-env -i -f <this-file> -A qemu
# build and install static qemu-3.1.0
# $ nix-env -i -f <this-file> -A qemu31
let
  # https://lazamar.co.uk/nix-versions
  pinnedPkgsForQemu31Src = builtins.fetchTarball {
    name = "nixos-20.03-with-qemu-3.1.0";
    url = "https://github.com/NixOS/nixpkgs/archive/81d4e65891f92e8e72c244da663c83c1e40dc919.tar.gz";
    sha256 = "0dk1k1zqy2bnp9gsy9mdxk0idkazyvnmqrj2jpbwzfnhjzpmzq1w";
  };
  pinnedPkgsSrc = builtins.fetchTarball {
    name = "nixos-static-qemu";
    url = "https://github.com/nixos/nixpkgs/archive/e7d63bd0d50df412f5a1d8acfa3caae75522e347.tar.gz";
    sha256 = "132pc4f9ixisyv4117p2jirmlyl6sd76bfaz33rhlcwakg7bhjm7";
  };
  pkgsForQemu31 = import pinnedPkgsForQemu31Src {};
  pkgs = import pinnedPkgsSrc {};
  mypkgs = import pinnedPkgsSrc {
    overlays = [(self: super: {

      cdparanoiaIII = super.pkgsStatic.cdparanoiaIII.overrideAttrs (old: {
        preConfigure = old.preConfigure + ''
          cp ${super.gnu-config}/config.sub configure.sub
          cp ${super.gnu-config}/config.guess configure.guess
        '';
        # Makefile needs this to compile static
        STATIC="TRUE";
        buildPhase = ''
          make lib
          make cdparanoia
        '';
        preInstallPhases = ["preInstallPhase"];
        preInstallPhase = ''
          sed -i '/so/d' Makefile
        '';
      });

      liburing = super.pkgsStatic.liburing.overrideDerivation (old: {
        configureFlags = "";
        ENABLE_SHARED = 0;
      });

      # p11-kit cannot be used as a static library
      # https://github.com/p11-glue/p11-kit/issues/355
      p11-kit = super.pkgsMusl.p11-kit;
      # gnutls depends on p11-kit
      gnutls = super.pkgsMusl.gnutls;

      pam = super.pkgsStatic.openpam;

      # support both static and shared
      libselinux = (super.pkgsMusl.libselinux.override {
        libsepol = super.pkgsStatic.libsepol;
      }).overrideAttrs (old: {
         makeFlags = old.makeFlags ++ [
           "LIBDIR=$(out)/lib"
         ];
      });

      glib = (super.pkgsStatic.glib.override {
        meson = pkgs.meson;
        ninja = pkgs.ninja;
        pkg-config = pkgs.pkg-config;
        perl = pkgs.perl;
        python3 = pkgs.python3;
        gettext = pkgs.gettext;
        gtk-doc = pkgs.gtk-doc;
        docbook_xsl = pkgs.docbook_xsl;
        docbook_xml_dtd_45 = pkgs.docbook_xml_dtd_45;
        libxml2 = pkgs.libxml2;
      }).overrideAttrs (old: {
        outputs = super.lib.lists.remove "devdoc" old.outputs;
        buildInputs = old.buildInputs ++ [
          super.pkgsStatic.libsepol
        ];
        preBuild = ''
          sed -i "s/get_option('libmount')/get_option('libmount'), static: true/g" ../meson.build
          sed -i "s/get_option('selinux')/get_option('selinux'), static: true/g" ../meson.build
        '';
        # no devdoc from non-static glibc
        # ${pname} & ${version} is correct due to lazy assignment
        postInstall = pkgs.glib.postInstall;
      });

      gtk3 = super.pkgsStatic.gtk3.override {
        trackerSupport = false;
        cupsSupport = false;
        withGtkDoc = false;

        # nativeBuildInputs
        inherit (pkgs) gettext gobject-introspection makeWrapper meson ninja
        pkg-config python3 sassc docbook_xml_dtd_43 docbook-xsl-nons gtk-doc libxml2;
      };

      qemu = ((super.pkgsStatic.qemu.override {
        alsaSupport = false;
        spiceSupport = false;
        sdlSupport = false;
        smartcardSupport = false;
        gtkSupport = false;
        pulseSupport = false;

        # nativeBuildInputs
        makeWrapper = pkgs.makeWrapper;
        python = pkgs.python3;
        pkg-config = pkgs.pkg-config;
        flex = pkgs.flex;
        bison = pkgs.bison;
        meson = pkgs.meson;
        ninja = pkgs.ninja;
        perl = pkgs.perl;
      }).overrideAttrs (old: {
        nativeBuildInputs = old.nativeBuildInputs ++ [
          pkgs.binutils
          # perl as nativeBuildInputs has been added in nixpkgs master
          # while it is backported to nixpkgs 21.11 (nixos 21.11).
          # If without perl as nativeBuildInputs,
          # ./scripts/shaderinclude.pl can not be patchShebangs'ed.
          pkgs.perl # without it cannot patchShebangs
        ];
        # qemu-6.1.1 has contained sigrtminmax patch, can not be patched again
        patches = builtins.filter (
          x: ! super.lib.hasSuffix "sigrtminmax.patch" x
        ) old.patches;
      })).overrideDerivation (old: let
        # qemu configure uses "--static" instead of standard "--disable-shared" and "--enable-static"
        configureFlags_no_DS = super.lib.lists.remove "--disable-shared" old.configureFlags;
        configureFlags_no_DS_no_ES = super.lib.lists.remove "--enable-static" configureFlags_no_DS;
      in {
        configureFlags = configureFlags_no_DS_no_ES ++ [
          "--static"
          # "--target-list-exclude="
          "--target-list=x86_64-softmmu"
        ];
      });

      qemu31 = (((super.callPackage (
        pinnedPkgsForQemu31Src + "/pkgs/applications/virtualization/qemu/default.nix"
      ) {
        inherit (super.darwin.apple_sdk.frameworks) CoreServices Cocoa Hypervisor;
        inherit (super.darwin.stubs) rez setfile;
      }).override {
        # In nixpkgs 20.03, stdenv contains lib attr.
        stdenv = pkgs.pkgsStatic.stdenv // {lib = super.lib;};
        alsaLib = null;
        spiceSupport = false;
        sdlSupport = false;
        smartcardSupport = false;
        gtkSupport = false;
        pulseSupport = false;

        # nativeBuildInputs
        makeWrapper = pkgs.makeWrapper;
        python2 = pkgs.python2;
        pkgconfig = pkgs.pkgconfig;
        flex = pkgs.flex;
        bison = pkgs.bison;
        perl = pkgs.perl;
      }).overrideAttrs (old: {
        nativeBuildInputs = old.nativeBuildInputs ++ [
          # Several issues report ld version >= 2.34 will failed due to
          # PHDR segment not covered by LOAD segment.
          # https://github.com/OpenOrbis/OpenOrbis-PS4-Toolchain/issues/122
          # https://github.com/genodelabs/genode/issues/4003
          # So I downgrade ld version < 2.34.
          # I still do not figure out why the same version ld in
          # qemu 6.1.1 static works correctly?
          pkgsForQemu31.binutils
        ];
      })).overrideDerivation (old: let
        # drop audio configure flag
        configureFlags_no_audio = builtins.filter (
          x: ! super.lib.hasPrefix "--audio-drv-list" x
        ) old.configureFlags;
        # qemu configure uses "--static" instead of standard "--disable-shared" and "--enable-static"
        configureFlags_no_DS = super.lib.lists.remove "--disable-shared" configureFlags_no_audio;
        configureFlags_no_DS_no_ES = super.lib.lists.remove "--enable-static" configureFlags_no_DS;
      in {
        configureFlags = configureFlags_no_DS_no_ES ++ [
          # "--static"
          # "--target-list-exclude="
          "--target-list=x86_64-softmmu"
          "--disable-gnutls"
          "--disable-tools"
        ];
        makeFlags = [
          # "V=1" # qemu Makefile verbose
          # It is neccessary to use ld in binutils, otherwise pc-bios build will fail.
          # In qemu 6.1.1 static, it is using ld in binutils, instead of ld from musl-gcc
          "AR=${pkgs.binutils-unwrapped}/bin/ar"
          "AS=${pkgs.binutils}/bin/as"
          "LD=${pkgs.binutils}/bin/ld"
          "NIX_BINTOOLS=${pkgs.binutils}"
        ];
      });
    })];

  };
in
{
  inherit (mypkgs.pkgsStatic) qemu qemu31;
}
#!/usr/bin/env nix-build
# xieby1: 2022.05.24
# build static qemu (current version 6.1.1) into ./result/
# $ nix-build <this-file> -A qemu
# build static qemu-3.1.0 into ./result/
# $ nix-build <this-file> -A qemu31
# build and install static qemu
# $ nix-env -i -f <this-file> -A qemu
# build and install static qemu-3.1.0
# $ nix-env -i -f <this-file> -A qemu31
let
  pinnedPkgsSrc = builtins.fetchTarball {
    name = "nixos-static-qemu";
    url = "https://github.com/nixos/nixpkgs/archive/e7d63bd0d50df412f5a1d8acfa3caae75522e347.tar.gz";
    sha256 = "132pc4f9ixisyv4117p2jirmlyl6sd76bfaz33rhlcwakg7bhjm7";
  };
  # pkgs = import pinnedPkgsSrc {};
  # mypkgs = import pinnedPkgsSrc {
  pkgs = import <nixpkgs> {};
  mypkgs = import <nixpkgs> {
    overlays = [(self: super: {

      cdparanoiaIII = super.pkgsStatic.cdparanoiaIII.overrideAttrs (old: {
        preConfigure = old.preConfigure + ''
          cp ${super.gnu-config}/config.sub configure.sub
          cp ${super.gnu-config}/config.guess configure.guess
        '';
        # Makefile needs this to compile static
        STATIC="TRUE";
        buildPhase = ''
          make lib
          make cdparanoia
        '';
        preInstallPhases = ["preInstallPhase"];
        preInstallPhase = ''
          sed -i '/so/d' Makefile
        '';
      });

      liburing = super.pkgsStatic.liburing.overrideDerivation (old: {
        configureFlags = "";
        ENABLE_SHARED = 0;
      });

      # p11-kit cannot be used as a static library
      # https://github.com/p11-glue/p11-kit/issues/355
      p11-kit = super.pkgsMusl.p11-kit;
      # gnutls depends on p11-kit
      gnutls = super.pkgsMusl.gnutls;

      pam = super.pkgsStatic.openpam;

      # support both static and shared
      libselinux = (super.pkgsMusl.libselinux.override {
        libsepol = super.pkgsStatic.libsepol;
      }).overrideAttrs (old: {
         makeFlags = old.makeFlags ++ [
           "LIBDIR=$(out)/lib"
         ];
      });

      glib = (super.pkgsStatic.glib.override {
        meson = pkgs.meson;
        ninja = pkgs.ninja;
        pkg-config = pkgs.pkg-config;
        perl = pkgs.perl;
        python3 = pkgs.python3;
        gettext = pkgs.gettext;
        gtk-doc = pkgs.gtk-doc;
        docbook_xsl = pkgs.docbook_xsl;
        docbook_xml_dtd_45 = pkgs.docbook_xml_dtd_45;
        libxml2 = pkgs.libxml2;
      }).overrideAttrs (old: {
        outputs = super.lib.lists.remove "devdoc" old.outputs;
        buildInputs = old.buildInputs ++ [
          super.pkgsStatic.libsepol
        ];
        preBuild = ''
          sed -i "s/get_option('libmount')/get_option('libmount'), static: true/g" ../meson.build
          sed -i "s/get_option('selinux')/get_option('selinux'), static: true/g" ../meson.build
        '';
        # no devdoc from non-static glibc
        # ${pname} & ${version} is correct due to lazy assignment
        postInstall = pkgs.glib.postInstall;
      });

      gtk3 = super.pkgsStatic.gtk3.override {
        trackerSupport = false;
        cupsSupport = false;
        withGtkDoc = false;

        # nativeBuildInputs
        inherit (pkgs) gettext gobject-introspection makeWrapper meson ninja
        pkg-config python3 sassc docbook_xml_dtd_43 docbook-xsl-nons gtk-doc libxml2;
      };

      qemu = ((super.pkgsStatic.qemu.override {
        alsaSupport = false;
        spiceSupport = false;
        sdlSupport = false;
        smartcardSupport = false;
        gtkSupport = false;
        pulseSupport = false;

        # nativeBuildInputs
        makeWrapper = pkgs.makeWrapper;
        python = pkgs.python3;
        pkg-config = pkgs.pkg-config;
        flex = pkgs.flex;
        bison = pkgs.bison;
        meson = pkgs.meson;
        ninja = pkgs.ninja;
        perl = pkgs.perl;
      }).overrideAttrs (old: {
        nativeBuildInputs = old.nativeBuildInputs ++ [
          pkgs.binutils
          # perl as nativeBuildInputs has been added in nixpkgs master
          # while it is backported to nixpkgs 21.11 (nixos 21.11).
          # If without perl as nativeBuildInputs,
          # ./scripts/shaderinclude.pl can not be patchShebangs'ed.
          pkgs.perl # without it cannot patchShebangs
        ];
        # qemu-6.1.1 has contained sigrtminmax patch, can not be patched again
        patches = builtins.filter (
          x: ! super.lib.hasSuffix "sigrtminmax.patch" x
        ) old.patches;
      })).overrideDerivation (old: let
        # qemu configure uses "--static" instead of standard "--disable-shared" and "--enable-static"
        configureFlags_no_DS = super.lib.lists.remove "--disable-shared" old.configureFlags;
        configureFlags_no_DS_no_ES = super.lib.lists.remove "--enable-static" configureFlags_no_DS;
      in {
        configureFlags = configureFlags_no_DS_no_ES ++ [
          "--static"
          # "--target-list-exclude="
          "--target-list=x86_64-softmmu"
        ];
      });
    })];
  };
in
{
  inherit (mypkgs.pkgsStatic.pkgsCross.riscv64) qemu;
}
#!/usr/bin/env nix-build
# xieby1: 2022.05.24
# build static qemu (current version 6.1.1) into ./result/
# $ nix-build <this-file> -A qemu
# build static qemu-3.1.0 into ./result/
# $ nix-build <this-file> -A qemu31
# build and install static qemu
# $ nix-env -i -f <this-file> -A qemu
# build and install static qemu-3.1.0
# $ nix-env -i -f <this-file> -A qemu31
let
  pinnedPkgsSrc = builtins.fetchTarball {
    name = "nixos-static-qemu";
    url = "https://github.com/nixos/nixpkgs/archive/e7d63bd0d50df412f5a1d8acfa3caae75522e347.tar.gz";
    sha256 = "132pc4f9ixisyv4117p2jirmlyl6sd76bfaz33rhlcwakg7bhjm7";
  };
  # pkgs = import pinnedPkgsSrc {};
  # mypkgs = import pinnedPkgsSrc {
  pkgs = import <nixpkgs> {};
  mypkgs = import <nixpkgs> {
    overlays = [(self: super: {

      cdparanoiaIII = super.pkgsStatic.cdparanoiaIII.overrideAttrs (old: {
        preConfigure = old.preConfigure + ''
          cp ${super.gnu-config}/config.sub configure.sub
          cp ${super.gnu-config}/config.guess configure.guess
        '';
        # Makefile needs this to compile static
        STATIC="TRUE";
        buildPhase = ''
          make lib
          make cdparanoia
        '';
        preInstallPhases = ["preInstallPhase"];
        preInstallPhase = ''
          sed -i '/so/d' Makefile
        '';
      });

      liburing = super.pkgsStatic.liburing.overrideDerivation (old: {
        configureFlags = "";
        ENABLE_SHARED = 0;
      });

      # p11-kit cannot be used as a static library
      # https://github.com/p11-glue/p11-kit/issues/355
      p11-kit = super.pkgsMusl.p11-kit;
      # gnutls depends on p11-kit
      gnutls = super.pkgsMusl.gnutls;

      pam = super.pkgsStatic.openpam;

      # support both static and shared
      libselinux = (super.pkgsMusl.libselinux.override {
        libsepol = super.pkgsStatic.libsepol;
      }).overrideAttrs (old: {
         makeFlags = old.makeFlags ++ [
           "LIBDIR=$(out)/lib"
         ];
      });

      glib = (super.pkgsStatic.glib.override {
        meson = pkgs.meson;
        ninja = pkgs.ninja;
        pkg-config = pkgs.pkg-config;
        perl = pkgs.perl;
        python3 = pkgs.python3;
        gettext = pkgs.gettext;
        gtk-doc = pkgs.gtk-doc;
        docbook_xsl = pkgs.docbook_xsl;
        docbook_xml_dtd_45 = pkgs.docbook_xml_dtd_45;
        libxml2 = pkgs.libxml2;
      }).overrideAttrs (old: {
        outputs = super.lib.lists.remove "devdoc" old.outputs;
        buildInputs = old.buildInputs ++ [
          super.pkgsStatic.libsepol
        ];
        preBuild = ''
          sed -i "s/get_option('libmount')/get_option('libmount'), static: true/g" ../meson.build
          sed -i "s/get_option('selinux')/get_option('selinux'), static: true/g" ../meson.build
        '';
        # no devdoc from non-static glibc
        # ${pname} & ${version} is correct due to lazy assignment
        postInstall = pkgs.glib.postInstall;
      });

      gtk3 = super.pkgsStatic.gtk3.override {
        trackerSupport = false;
        cupsSupport = false;
        withGtkDoc = false;

        # nativeBuildInputs
        inherit (pkgs) gettext gobject-introspection makeWrapper meson ninja
        pkg-config python3 sassc docbook_xml_dtd_43 docbook-xsl-nons gtk-doc libxml2;
      };

      qemu = ((super.pkgsStatic.qemu.override {
        alsaSupport = false;
        spiceSupport = false;
        sdlSupport = false;
        smartcardSupport = false;
        gtkSupport = false;
        pulseSupport = false;

        # nativeBuildInputs
        makeWrapper = pkgs.makeWrapper;
        python = pkgs.python3;
        pkg-config = pkgs.pkg-config;
        flex = pkgs.flex;
        bison = pkgs.bison;
        meson = pkgs.meson;
        ninja = pkgs.ninja;
        perl = pkgs.perl;
      }).overrideAttrs (old: {
        nativeBuildInputs = old.nativeBuildInputs ++ [
          pkgs.binutils
          # perl as nativeBuildInputs has been added in nixpkgs master
          # while it is backported to nixpkgs 21.11 (nixos 21.11).
          # If without perl as nativeBuildInputs,
          # ./scripts/shaderinclude.pl can not be patchShebangs'ed.
          pkgs.perl # without it cannot patchShebangs
        ];
        # qemu-6.1.1 has contained sigrtminmax patch, can not be patched again
        patches = builtins.filter (
          x: ! super.lib.hasSuffix "sigrtminmax.patch" x
        ) old.patches;
      })).overrideDerivation (old: let
        # qemu configure uses "--static" instead of standard "--disable-shared" and "--enable-static"
        configureFlags_no_DS = super.lib.lists.remove "--disable-shared" old.configureFlags;
        configureFlags_no_DS_no_ES = super.lib.lists.remove "--enable-static" configureFlags_no_DS;
      in {
        configureFlags = configureFlags_no_DS_no_ES ++ [
          "--static"
          # "--target-list-exclude="
          "--target-list=x86_64-softmmu"
        ];
      });
    })];
  };
in
{
  inherit (mypkgs.pkgsStatic.pkgsCross.riscv64) qemu;
}
#!/usr/bin/env nix-build
# xieby1: 2022.05.24
# build static qemu (current version 6.1.1) into ./result/
# $ nix-build <this-file> -A qemu
# build static qemu-3.1.0 into ./result/
# $ nix-build <this-file> -A qemu31
# build and install static qemu
# $ nix-env -i -f <this-file> -A qemu
# build and install static qemu-3.1.0
# $ nix-env -i -f <this-file> -A qemu31
let
  # https://lazamar.co.uk/nix-versions
  pinnedPkgsForQemu31Src = builtins.fetchTarball {
    name = "nixos-20.03-with-qemu-3.1.0";
    url = "https://github.com/NixOS/nixpkgs/archive/81d4e65891f92e8e72c244da663c83c1e40dc919.tar.gz";
    sha256 = "0dk1k1zqy2bnp9gsy9mdxk0idkazyvnmqrj2jpbwzfnhjzpmzq1w";
  };
  pinnedPkgsSrc = builtins.fetchTarball {
    name = "nixos-static-qemu";
    url = "https://github.com/nixos/nixpkgs/archive/e7d63bd0d50df412f5a1d8acfa3caae75522e347.tar.gz";
    sha256 = "132pc4f9ixisyv4117p2jirmlyl6sd76bfaz33rhlcwakg7bhjm7";
  };
  pkgsForQemu31 = import pinnedPkgsForQemu31Src {};
  pkgs = import pinnedPkgsSrc {};
  mypkgs = import pinnedPkgsSrc {
    overlays = [(self: super: {

      cdparanoiaIII = super.pkgsStatic.cdparanoiaIII.overrideAttrs (old: {
        preConfigure = old.preConfigure + ''
          cp ${super.gnu-config}/config.sub configure.sub
          cp ${super.gnu-config}/config.guess configure.guess
        '';
        # Makefile needs this to compile static
        STATIC="TRUE";
        buildPhase = ''
          make lib
          make cdparanoia
        '';
        preInstallPhases = ["preInstallPhase"];
        preInstallPhase = ''
          sed -i '/so/d' Makefile
        '';
      });

      liburing = super.pkgsStatic.liburing.overrideDerivation (old: {
        configureFlags = "";
        ENABLE_SHARED = 0;
      });

      # p11-kit cannot be used as a static library
      # https://github.com/p11-glue/p11-kit/issues/355
      p11-kit = super.pkgsMusl.p11-kit;
      # gnutls depends on p11-kit
      gnutls = super.pkgsMusl.gnutls;

      pam = super.pkgsStatic.openpam;

      # support both static and shared
      libselinux = (super.pkgsMusl.libselinux.override {
        libsepol = super.pkgsStatic.libsepol;
      }).overrideAttrs (old: {
         makeFlags = old.makeFlags ++ [
           "LIBDIR=$(out)/lib"
         ];
      });

      glib = (super.pkgsStatic.glib.override {
        meson = pkgs.meson;
        ninja = pkgs.ninja;
        pkg-config = pkgs.pkg-config;
        perl = pkgs.perl;
        python3 = pkgs.python3;
        gettext = pkgs.gettext;
        gtk-doc = pkgs.gtk-doc;
        docbook_xsl = pkgs.docbook_xsl;
        docbook_xml_dtd_45 = pkgs.docbook_xml_dtd_45;
        libxml2 = pkgs.libxml2;
      }).overrideAttrs (old: {
        outputs = super.lib.lists.remove "devdoc" old.outputs;
        buildInputs = old.buildInputs ++ [
          super.pkgsStatic.libsepol
        ];
        preBuild = ''
          sed -i "s/get_option('libmount')/get_option('libmount'), static: true/g" ../meson.build
          sed -i "s/get_option('selinux')/get_option('selinux'), static: true/g" ../meson.build
        '';
        # no devdoc from non-static glibc
        # ${pname} & ${version} is correct due to lazy assignment
        postInstall = pkgs.glib.postInstall;
      });

      gtk3 = super.pkgsStatic.gtk3.override {
        trackerSupport = false;
        cupsSupport = false;
        withGtkDoc = false;

        # nativeBuildInputs
        inherit (pkgs) gettext gobject-introspection makeWrapper meson ninja
        pkg-config python3 sassc docbook_xml_dtd_43 docbook-xsl-nons gtk-doc libxml2;
      };

      qemu = ((super.pkgsStatic.qemu.override {
        alsaSupport = false;
        spiceSupport = false;
        sdlSupport = false;
        smartcardSupport = false;
        gtkSupport = false;
        pulseSupport = false;

        # nativeBuildInputs
        makeWrapper = pkgs.makeWrapper;
        python = pkgs.python3;
        pkg-config = pkgs.pkg-config;
        flex = pkgs.flex;
        bison = pkgs.bison;
        meson = pkgs.meson;
        ninja = pkgs.ninja;
        perl = pkgs.perl;
      }).overrideAttrs (old: {
        nativeBuildInputs = old.nativeBuildInputs ++ [
          pkgs.binutils
          # perl as nativeBuildInputs has been added in nixpkgs master
          # while it is backported to nixpkgs 21.11 (nixos 21.11).
          # If without perl as nativeBuildInputs,
          # ./scripts/shaderinclude.pl can not be patchShebangs'ed.
          pkgs.perl # without it cannot patchShebangs
        ];
        # qemu-6.1.1 has contained sigrtminmax patch, can not be patched again
        patches = builtins.filter (
          x: ! super.lib.hasSuffix "sigrtminmax.patch" x
        ) old.patches;
      })).overrideDerivation (old: let
        # qemu configure uses "--static" instead of standard "--disable-shared" and "--enable-static"
        configureFlags_no_DS = super.lib.lists.remove "--disable-shared" old.configureFlags;
        configureFlags_no_DS_no_ES = super.lib.lists.remove "--enable-static" configureFlags_no_DS;
      in {
        configureFlags = configureFlags_no_DS_no_ES ++ [
          "--static"
          # "--target-list-exclude="
          "--target-list=x86_64-softmmu"
        ];
      });

      qemu31 = (((super.callPackage (
        pinnedPkgsForQemu31Src + "/pkgs/applications/virtualization/qemu/default.nix"
      ) {
        inherit (super.darwin.apple_sdk.frameworks) CoreServices Cocoa Hypervisor;
        inherit (super.darwin.stubs) rez setfile;
      }).override {
        # In nixpkgs 20.03, stdenv contains lib attr.
        stdenv = pkgs.pkgsStatic.stdenv // {lib = super.lib;};
        alsaLib = null;
        spiceSupport = false;
        sdlSupport = false;
        smartcardSupport = false;
        gtkSupport = false;
        pulseSupport = false;

        # nativeBuildInputs
        makeWrapper = pkgs.makeWrapper;
        python2 = pkgs.python2;
        pkgconfig = pkgs.pkgconfig;
        flex = pkgs.flex;
        bison = pkgs.bison;
        perl = pkgs.perl;
      }).overrideAttrs (old: {
        nativeBuildInputs = old.nativeBuildInputs ++ [
          # Several issues report ld version >= 2.34 will failed due to
          # PHDR segment not covered by LOAD segment.
          # https://github.com/OpenOrbis/OpenOrbis-PS4-Toolchain/issues/122
          # https://github.com/genodelabs/genode/issues/4003
          # So I downgrade ld version < 2.34.
          # I still do not figure out why the same version ld in
          # qemu 6.1.1 static works correctly?
          pkgsForQemu31.binutils
        ];
      })).overrideDerivation (old: let
        # drop audio configure flag
        configureFlags_no_audio = builtins.filter (
          x: ! super.lib.hasPrefix "--audio-drv-list" x
        ) old.configureFlags;
        # qemu configure uses "--static" instead of standard "--disable-shared" and "--enable-static"
        configureFlags_no_DS = super.lib.lists.remove "--disable-shared" configureFlags_no_audio;
        configureFlags_no_DS_no_ES = super.lib.lists.remove "--enable-static" configureFlags_no_DS;
      in {
        configureFlags = configureFlags_no_DS_no_ES ++ [
          # "--static"
          # "--target-list-exclude="
          "--target-list=x86_64-softmmu"
          "--disable-gnutls"
          "--disable-tools"
        ];
        makeFlags = [
          # "V=1" # qemu Makefile verbose
          # It is neccessary to use ld in binutils, otherwise pc-bios build will fail.
          # In qemu 6.1.1 static, it is using ld in binutils, instead of ld from musl-gcc
          "AR=${pkgs.binutils-unwrapped}/bin/ar"
          "AS=${pkgs.binutils}/bin/as"
          "LD=${pkgs.binutils}/bin/ld"
          "NIX_BINTOOLS=${pkgs.binutils}"
        ];
      });
    })];

  };
in
{
  inherit (mypkgs.pkgsStatic) qemu qemu31;
}
#!/usr/bin/env nix-build
# TODO
# Ref: ~/Docs/Tech/BT/QEMU/test.md
let
  pkgs = import <nixpkgs> {};
in
pkgs.stdenv.mkDerivation {
  buildInputs = with pkgs; [
    # configure needs
    ninja
    pkg-config
    glib
    # make needs
    glibc.static # TODO: this will cause configure failed
  ];
  buildFlags = [
    "CFLAGS=-O" # override CFLAGS
    "build-tcg-tests-x86_64-linux-user"
  ];
}
# build by version
# nix-build pkgs_qemu.nix -A v1_0
# build by date
# nix-build pkgs_qemu.nix -A d2011_12_01
{ pkgs ? import <nixpkgs> {} }:
let
  pname = "qemu";
in rec {
  v1_0 = let
    version = "1.0";
  in pkgs.gcc49Stdenv.mkDerivation {
    inherit pname version;
    src = pkgs.fetchurl {
      url = "https://download.qemu.org/qemu-${version}.tar.xz";
      sha256 = "0y1018xia238pcqb7ad9v299b478c0838fiayl6qkzyd95gk0xbb";
    };
    buildInputs = with pkgs; [
      zlib
      pkg-config
      glib
      python2
    ];
    patches = [
      ./qemu-v1.0.patch
    ];
    configureFlags = [
      "--target-list=x86_64-linux-user"
      "--disable-docs"
    ];
  };
  d2011_12_01 = v1_0;
}
# https://github.com/NixOS/nixpkgs/issues/185773
{ lib, callPackage, fetchFromGitHub, fetchurl, openssl_1_1 }:

((callPackage (import (fetchFromGitHub {
  owner = "NixOS";
  repo = "nixpkgs";
  rev = "363ef08971726937cd6a63de0efef7f8ba657b18";
  sha256 = "sha256-QRKAn5yLMyohZKsK72Vkd6HQUh3t5tDpFyI/Y7T3ASg=";
}) { }).shellinabox.override) { openssl = openssl_1_1; }).overrideAttrs
({ patches, ... }: {
  patches = patches ++ [
    # OpenSSL 1.1
    (fetchurl {
      url =
        "https://github.com/shellinabox/shellinabox/commit/c32f3d365a0848eb6b3350ec521fcd4d1d098295.patch";
      hash = "sha256-Q8otJUip1YQJb0ZSF89BjSvrCh4PQe4R7Rb7mtm33tk=";
    })
  ];
})
{ pkgs ? import (fetchTarball {
    url = "https://github.com/NixOS/nixpkgs/archive/1dab772dd4a68a7bba5d9460685547ff8e17d899.tar.gz";
    sha256 = "18qwmspcsmi0ryhcg66p9i42qwismm7l0706m39zw5ziq6n11fc9";
  }) {}
, CONFIG ? "XSNoCTopConfig" # "DefaultConfig"
, EMU_THREADS ? "4"
, NUM_CORES ? "1"
, EMU_TRACE ? "fst" # "fst" or "vcd"
, DISABLE_PERF ? "1"
, genRTL ? false
}:
let
  xs-src = (pkgs.fetchFromGitHub {
    owner = "OpenXiangShan";
    repo = "XiangShan";
    rev = "ff4344e4e52d4e58ba1570da9ace0dafaca74de0";
    hash = "sha256-2vaeqiEOGRlEkcSZLzneqwVe1IldhPMK552ydUnKS+s=";
    forceFetchGit = true;
  }).overrideAttrs (old: {
    # NOTE: Why not use leaveDotGit/deepClone here?
    # see pkgs/build-support/fetchgit/nix-prefetch-git:
    # # > # shallow with leaveDotGit will change hashes
    # In other words: If deepClone/leaveDotGit co-exists with fetchSubmodules
    # (here we only fetch selected submodules by NIX_PREFETCH_GIT_CHECKOUT_HOOK)
    # then hash changes every time.
    #
    # old nixpkgs.fetchgit not support preFetch
    # preFetch = ''export NIX_PREFETCH_GIT_CHECKOUT_HOOK="make -C $out init"'';
    NIX_PREFETCH_GIT_CHECKOUT_HOOK="make -C $out init";
  });
  # If you want to use other mill version, uncomment belowing
  # mill = pkgs.mill.overrideAttrs (finalAttrs: previousAttrs: {
  #   version = "0.11.8";
  #   src = pkgs.fetchurl {
  #     url = "https://github.com/com-lihaoyi/mill/releases/download/${finalAttrs.version}/${finalAttrs.version}-assembly";
  #     hash = "sha256-HORTexIzrxbWjcGrS59JqZboxGCzk8wKf3eKMoYGqrI=";
  #   };
  # });
  mill = pkgs.mill;
  mill-with-proxy = pkgs.writeShellScriptBin "mill" ''
    # -i/--interactive/--no-server/--bsp must be passed in as the first argument
    if [[ $1 == -i || $1 == --interactive ||  $1 == --no-server || $1 == --bsp  ]]; then
      FIRST_ARG=$1
      shift
    fi
    ${mill}/bin/mill $FIRST_ARG \
      -D http.proxyHost=$(echo $http_proxy | sed -E 's,(.*://)?([^:/]+):([0-9]*).*,\2,') \
      -D http.proxyPort=$(echo $http_proxy | sed -E 's,(.*://)?([^:/]+):([0-9]*).*,\3,') \
      -D https.proxyHost=$(echo $https_proxy | sed -E 's,(.*://)?([^:/]+):([0-9]*).*,\2,') \
      -D https.proxyPort=$(echo $https_proxy | sed -E 's,(.*://)?([^:/]+):([0-9]*).*,\3,') \
      "$@"
  '';
  # mill deps refer to https://github.com/com-lihaoyi/mill/discussions/1170
  COURSIER_CACHE = pkgs.stdenv.mkDerivation {
    name = "xs-mill-cache";
    src = xs-src;
    nativeBuildInputs = [ mill-with-proxy ];
    impureEnvVars = pkgs.lib.fetchers.proxyImpureEnvVars;
    # [COURSIER_CACHE with relative path cause artifacts download into process sandbox folder](https://github.com/com-lihaoyi/mill/issues/3946)
    # Thus, COURSIER_CACHE uses absolute path like below
    buildPhase = ''
      export COURSIER_CACHE=$PWD/.cache/coursier
      mill __.prepareOffline
    '';
    installPhase = ''
      cp -r $COURSIER_CACHE $out
    '';
    outputHashMode = "recursive";
    outputHash = "sha256-9qL+2W2KSHIV4KxhfY9F+2j1xP8NCW7mC/CO2EWbYh8=";
  };
in pkgs.stdenv.mkDerivation {
  name = "xs";
  src = xs-src;
  nativeBuildInputs = [
    pkgs.makeWrapper
    mill-with-proxy
    pkgs.time
    pkgs.espresso
    pkgs.verilator
    pkgs.sqlite
    pkgs.zlib
    pkgs.zstd
    pkgs.python3
  ];

  postPatch = ''
    patchShebangs scripts/
  ''
  # The .git/ folder format is not stable, thus hard to achieve deterministic.
  # For more information about .git/ and deterministic see the `leaveDotGit` option in
  # [nixpkgs manual: fetchgit](https://nixos.org/manual/nixpkgs/stable/#fetchgit).
  # 1. Clean vcs.version scala lib, which needs the .git/ folder.
  + ''
    find -name build.sc -exec sed -i '/vcs.version/d' {} \;
    sed -i '/def publishVersion/,/^  )$/c\  def publishVersion() = "deterministic-version"' build.sc
    find -name build.sc -exec sed -i 's/def publishVersion =.*vcs.version.*/def publishVersion = "miao"/' {} \;
  ''
  # 2. Clean git related operations in build.sc
  + ''
    sed -i '/def gitStatus:/,/^  }/c\  def gitStatus() = "SHA=${xs-src.rev}\\ndirty=0"' build.sc
    sed -i 's/"git", "ls-files"/"ls", "-1"/' build.sc
    sed -i 's/os.proc("git", "submodule", "status").call().out.text()/""/' build.sc
  ''
  # 3. Clean git in Makefile
  + ''
    sed -i '/@git log/,/rm .__head__/d' Makefile
  '';

  # current version of Chisel (6.6.0) was published against firtool version 1.62.1
  CHISEL_FIRTOOL_PATH = "${(import (pkgs.fetchFromGitHub {
    owner = "NixOS";
    repo = "nixpkgs";
    rev = "771b079bb84ac2395f3a24a5663ac8d1495c98d3";
    sha256 = "0l1l9ms78xd41xg768pkb6xym200zpf4zjbv4kbqbj3z7rzvhpb7";
  }){}).circt}/bin/";
  shellHook = ''
    export NOOP_HOME=$(realpath .)
  '';
  buildPhase = ''
    eval "$shellHook"
    # Q: Why not use COURSIER_CACHE as a variable in mkDerivation
    # A: To prevent COURSIER_CACHE (a read-only path in /nix/store) from affecting LSP metals' behaviour in nix-shell
    export COURSIER_CACHE=${COURSIER_CACHE}
    make emu CONFIG=${CONFIG} EMU_THREADS=${EMU_THREADS} NUM_CORES=${NUM_CORES} EMU_TRACE=${EMU_TRACE} DISABLE_PERF=${DISABLE_PERF} -j $NIX_BUILD_CORES
  '';

  outputs = ["out"] ++ pkgs.lib.optional genRTL "rtl";
  installPhase = ''
    mkdir -p $out/bin
    cp build/emu $out/bin/
    wrapProgram $out/bin/emu --prefix PATH : ${pkgs.lib.makeBinPath [pkgs.spike]}
  '' + pkgs.lib.optionalString genRTL ''
    mkdir -p $rtl
    cp -r build/rtl/* $rtl/
  '';
}

See all fhs-shell scripts on [Github repo: scripts/shell]({{ site.repo_url }}/scripts/shell)

let
  name = "LinkNan";
  pkgs = import <nixpkgs> {};
in pkgs.mkShell {
  inherit name;

  buildInputs = let
    h_content = builtins.toFile "h_content" ''
      # ${pkgs.lib.toUpper "${name} usage tips"}
    '';
    _h_ = pkgs.writeShellScriptBin "h" ''
      ${pkgs.glow}/bin/glow ${h_content}
    '';
    mill_0_11_2 = (import (pkgs.fetchFromGitHub {
      owner = "NixOS";
      repo = "nixpkgs";
      rev = "4ab8a3de296914f3b631121e9ce3884f1d34e1e5";
      hash = "sha256-mQUik6XZea6ZcCkMpUieq1oxlEDE0vqTTRU9RStgtSQ=";
    }){}).mill;
  in [
    _h_
    mill_0_11_2
  ] ++ (with pkgs; [
    xmake
    espresso
    verilator

    # libs
    sqlite
    zlib
    zstd
  ]);

  shellHook = let
    circt_1_62_0 = (import (pkgs.fetchFromGitHub {
      owner = "NixOS";
      repo = "nixpkgs";
      rev = "771b079bb84ac2395f3a24a5663ac8d1495c98d3";
      sha256 = "0l1l9ms78xd41xg768pkb6xym200zpf4zjbv4kbqbj3z7rzvhpb7";
    }){}).circt;
  in ''
    h
    export CHISEL_FIRTOOL_PATH=${circt_1_62_0}/bin/
    export NOOP_HOME=$(realpath .)
  '';
}
let
  pkgs = import <nixpkgs> {};
  ccache_dir = toString ./. + "/.ccache";
  ccache14Stdenv = pkgs.ccacheStdenv.override {
    stdenv = pkgs.gcc14Stdenv;
    extraConfig = ''
      export CCACHE_COMPRESS=1
      export CCACHE_DIR="${ccache_dir}"
      export CCACHE_UMASK=007
      if [ ! -d "$CCACHE_DIR" ]; then
        echo "====="
        echo "Directory '$CCACHE_DIR' does not exist"
        echo "Please create it with:"
        echo "  mkdir -m0770 '$CCACHE_DIR'"
        echo "====="
        exit 1
      fi
      if [ ! -w "$CCACHE_DIR" ]; then
        echo "====="
        echo "Directory '$CCACHE_DIR' is not accessible for user $(whoami)"
        echo "Please verify its access permissions"
        echo "====="
        exit 1
      fi
    '';
  };
  ccacheMkShell = pkgs.mkShell.override {
    stdenv = ccache14Stdenv;
  };
in ccacheMkShell {
  name = "ccache-shell";
  shellHook = ''
    mkdir -m0770 -p ${ccache_dir}
  '';
}
let
  name = "chipyard";
  pkgs = import <nixpkgs> {};
  pkgsCirct1_30_0 = import (builtins.fetchTarball {
      url = "https://github.com/NixOS/nixpkgs/archive/0aca8f43c8dba4a77aa0c16fb0130237c3da514c.tar.gz";
  }) {};

  # currently latest spike
  my-spike = pkgs.spike.overrideAttrs (old: {
    version = "1.1.1-dev";
    src = pkgs.fetchFromGitHub {
      owner = "riscv";
      repo = "riscv-isa-sim";
      rev = "4f916978cd17bd2e83cfca233d0fa40153fda5f4";
      sha256 = "sha256-84YY9YMIa4YO5mVJ0gGMOWnD2/CnpEjIbB9EjA5+Glc=";
    };
  });

  h_content = builtins.toFile "h_content" ''
    # ${pkgs.lib.toUpper "${name} usage tips"}

    The conda cannot gracefully manage the dependencies, e.g. gcc's dynamic libraries.
    Instead, I replace conda with nix to manage the dependencies.

    * Show this help: `h`

    Init Repos

    * edit common.mk:1 `SHELL=bash`
    * `./scripts/init-submodules-no-riscv-tools-nolog.sh`

    Compiling Verilator

    * `make -C sims/verilator`

    Run Verilator

    * `./sims/verilator/simulator-chipyard.harness-RocketConfig <RISCV Executable>`
  '';
  _h_ = pkgs.writeShellScriptBin "h" ''
    ${pkgs.glow}/bin/glow ${h_content}
  '';
in pkgs.mkShell {
  inherit name;
  packages = with pkgs; [
    verilator
    dtc
    jq
    pkgsCirct1_30_0.circt
    my-spike

    _h_
  ];
  shellHook = ''
    export RISCV=${pkgs.pkgsCross.riscv64-embedded.stdenv.cc}

    h
  '';
}
#!/usr/bin/env -S nix-shell --keep miao
# xieby1: 2022.07.03
# let
#   pkgs = import <nixpkgs> {};
# in
# pkgs.mkShell {
#   buildInputs = [
#     pkgs.pkgsCross.mipsel-linux-gnu.stdenv.cc
#   ];
# }

# xieby1: 2022.05.16
let
  pkgs_mips_cross = import <nixpkgs> {
    crossSystem = "mips-linux";
  };
  pkgs = import <nixpkgs> {};
in
pkgs.mkShell {
  buildInputs = (with pkgs_mips_cross; [
    buildPackages.gdb
    buildPackages.gcc
  ]) ++ (with pkgs; [
    qemu
  ]);
}
#!/usr/bin/env -S nix-shell --keep miao
# xieby1: 2022.04.26

let
  pkgs_arm_cross = import <nixpkgs> {
    # get this config on my android
    #   nix repl
    #   builtins.currentSystem
    crossSystem = "aarch64-linux";
  };
  pkgs_arm_native = import <nixpkgs> {
    localSystem = "aarch64-linux";
    crossSystem = "aarch64-linux";
  };
  pkgs = import <nixpkgs> {};
in
pkgs.mkShell {
  buildInputs = with pkgs_arm_cross; [
    # packages for cross compiling, run on local system (x86_64)
    stdenv.cc
    # here stdenv.cc is the same with buildPackages.gcc
  ] ++ (with pkgs_arm_native; [
    # packages run on aarch64
    figlet
  ]) ++ (with pkgs; [
    # packages run on local system (x86_64)
    qemu
  ]);
}
#!/usr/bin/env -S nix-shell --keep miao
{ system ? builtins.currentSystem }:
let
  src = fetchTarball {
    url = "https://github.com/numtide/devshell/archive/9fddc998b4522694caaf4056e93154d2c11752cd.tar.gz";
    sha256 = "0d7ra00843n4iyadhdxcr9m0vcn6fz54hfymms6nbdz0d2pjff06";
  };
  devshell = import src { inherit system; };
in
devshell.mkShell {
  commands = [{
    name = "hello";
    command = "echo hello";
    help = "print hello miao";
  }];
}
#!/usr/bin/env -S nix-shell --keep miao
let
  pkgs = import <nixpkgs> {};
in pkgs.mkShellNoCC {
  name = "gcc11";
  packages = with pkgs; [
    gcc11
  ];
}
#!/usr/bin/env -S nix-shell --keep miao
with import <nixpkgs> {};
# You will get a shell with hello executable,
# and environment variable $name, $miao.
mkShell {
  packages = [
    hello
  ];
  name = "test-env";
  miao = "miao!";
}
let
  pkgs = import <nixpkgs> {};
in pkgs.stdenv.mkDerivation {
  name = "child";
  propagatedBuildInputs = [
    (import ./grandchild.nix)
  ];
  dontUnpack = true;
  buildPhase = "mkdir -p $out";
  installPhase = "touch $out/miao";
}
let
  pkgs = import <nixpkgs> {};
in pkgs.stdenv.mkDerivation {
  name = "grandchild";
  dontUnpack = true;
  propagatedBuildInputs = [
    pkgs.hello
  ];
  buildPhase = "mkdir -p $out";
  installPhase = "touch $out/miao";
}
let
  pkgs = import <nixpkgs> {};
in pkgs.stdenv.mkDerivation {
  name = "parent";
  propagatedBuildInputs = [
    (import ./child.nix)
  ];
  dontUnpack = true;
  buildPhase = "mkdir -p $out";
  installPhase = "touch $out/miao";
}
#!/usr/bin/env -S nix-shell --keep miao
#2022.05.18
# pip install is usable in venv
# e.g.
# $ nix-shell <this_file>
# $ pip install [--user] graphviz2drawio
let
  pkgs = import <nixpkgs> {};
in
pkgs.mkShell {
  propagatedBuildInputs = with pkgs.python3Packages; [
    pip
    venvShellHook
    ipython
    pygame
  ] ++ (with pkgs; [
  ]);
  venvDir = "pygame";
}
# https://nixos.wiki/wiki/Python
# Python virtual environment

# Execute this commands after entering fhs env
# python -m venv .venv
# source .venv/bin/activate

let
  pkgs = import <nixpkgs> {};
in (pkgs.buildFHSUserEnv {
  name = "venv";
  targetPkgs = p: (with p.python3Packages; [
    pip
    virtualenv
    ipython
  ]);
}).env
#!/usr/bin/env -S nix-shell --keep miao
let
  mach-nix = import (builtins.fetchGit {
    url = "https://github.com/DavHau/mach-nix";
    ref = "refs/tags/3.4.0";
  }) {
    pkgs = import <nixpkgs> {};
  };
in
mach-nix.mkPythonShell {
  requirements = ''
    expmcc
  '';
}
#!/usr/bin/env -S nix-shell --keep miao
#2022.05.18
# pip install is usable in venv
# e.g.
# $ nix-shell <this_file>
# $ pip install [--user] graphviz2drawio
let
  pkgs = import <nixpkgs> {};
in
pkgs.mkShell {
  propagatedBuildInputs = with pkgs.python3Packages; [
    pip
    pygraphviz
    venvShellHook
    ipython
  ] ++ (with pkgs; [
    graphviz
  ]);
  venvDir = "venv";
}
#!/usr/bin/env -S nix-shell --keep miao
# lxy's qemu plugins: http://172.17.103.58/lixinyu/qemu_plugins

let
  pkgs = import <nixpkgs> {};
in pkgs.mkShell {
  packages = with pkgs; [
    zlib.dev
    pkg-config
    glib.dev
  ];
  QEMU_DIR = "~/Codes/qemu";
}
#!/usr/bin/env -S nix-shell --keep miao
# --pure: start a pure reproducible shell
# 2022.04.24
# Compile qemu/tests/tcg/x86_64/
# env CFLAGS=-O make -e build-tcg-tests-x86_64-linux-user
{ pkgs ? import <nixpkgs> {} }:
let
  name = "nix";
in
pkgs.mkShell {
  inherit name;
  buildInputs = with pkgs; [
    glibc.static
  ];
  inputsFrom = with pkgs; [
    qemu
  ];
}
let
  name = "riscv-tests";
  pkgs = import <nixpkgs> {};
  h_content = builtins.toFile "h_content" ''
    # ${pkgs.lib.toUpper "${name} compiling tips"}

    * `git submodule update --init --recursive`
    * `autoconf`
    * `./configure`
    * `make -j`
  '';
  _h_ = pkgs.writeShellScriptBin "h" ''
    ${pkgs.glow}/bin/glow ${h_content}
  '';
in pkgs.mkShell {
  inherit name;
  packages = with pkgs; [
    autoconf
    pkgsCross.riscv64-embedded.stdenv.cc

    _h_
  ];
  shellHook = ''
    export RISCV_PREFIX=${pkgs.pkgsCross.riscv64-embedded.stdenv.cc}/bin/riscv64-none-elf-
    h
  '';
}
#!/usr/bin/env -S nix-shell --keep miao
with import <nixpkgs> {};
mkShell {
  packages = [
    dtc
    pkgsCross.riscv64-embedded.stdenv.cc
  ];
  name = "spike";
}
#!/usr/bin/env -S nix-shell --keep miao
# --pure: start a pure reproducible shell
{ pkgs ? import <nixpkgs> {}
}:
pkgs.mkShell {
  name="dev-environment";
  buildInputs = with pkgs; [
    texlive.combined.scheme-full # HUGE SIZE!

    tmux
  ];
  shellHook = ''
    # install texlive permenant
    nix-env -q "texlive.*"
    if [[ ''$? -ne 0 ]]
    then
      nix-env -f '<nixpkgs>' -iA texlive.combined.scheme-full
    fi

    tmux
    exit
  '';
}
#!/usr/bin/env -S nix-shell --keep miao
{pkgs ? import <nixpkgs> {}}:
let
  name = "ucasproposal";
  myTexlive = pkgs.texlive.combine {
    inherit (pkgs.texlive)
    scheme-basic

    xetex
    ctex
    checkcites

    # sty
    newtx
    xstring
    realscripts
    jknapltx
    mathalpha
    caption
    placeins
    enumitem
    listings
    algpseudocodex
    algorithms
    algorithmicx
    chemfig
    mhchem
    float

    # tex
    simplekv

    rsfs
    ;
  };
  myPython = pkgs.python3.withPackages (p: with p; [
    ipython
    matplotlib
    pandas
    numpy
    openpyxl
  ]);
in
pkgs.mkShell {
  inherit name;
  packages = with pkgs; [
    myTexlive
    myPython
    librsvg
  ];
  shellHook = ''
    # env
    export PYTHONPATH=${myPython}/${myPython.sitePackages}
    export debian_chroot=${name}
  '';
}
#!/usr/bin/env -S nix-shell --keep miao
{ pkgsX86 ? import <nixpkgs> {
  localSystem.system="aarch64-linux";
  crossSystem="aarch64-linux";
} }:
pkgsX86.v8
#!/usr/bin/env -S nix-shell --keep miao
#2022.05.18
# pip install is usable in venv
# e.g.
# $ nix-shell <this_file>
# $ pip install [--user] graphviz2drawio
let
  pkgs = import <nixpkgs> {};
in
pkgs.mkShell {
  propagatedBuildInputs = with pkgs.python3Packages; [
    pip
    venvShellHook
    ipython
  ];
  venvDir = "${builtins.getEnv "HOME"}/.venv";
}
#!/usr/bin/env -S nix-shell --keep miao
let
  pkgs = import (builtins.fetchTarball {
    url = "https://github.com/NixOS/nixpkgs/archive/5e15d5da4abb74f0dd76967044735c70e94c5af1.tar.gz";
    sha256 = "0mk86mlxamjxhywdfp5asylqb39z7w18dcy8ds6qvl8gqjrijmq9";
  }) {
    system = "x86_64-linux";
  };
in pkgs.mkShell {
  name = "wine6";
  packages = with pkgs; [
    wine64
  ];
}

shell.nix

这个shell.nix用于创建编译我的nix_config仓库的 GitHub Pages的环境。 GitHub Pages的构建主要由markcode和mdbook这两个工具支持。

  • markcode 是我为了方便在源文件里内嵌文档,写的一个小工具。 它能将源文件中带有特殊标记的注释抽取出,成为markdown文件。 nix_config仓库的几乎所有文档都内嵌在.nix文件中, 并都是通过markcode从.nix文件抽取出来。
  • mdbook 是一个非常纯粹且好用的静态网页生成框架,负责将markdown转换成网页。 因为第一次阅读nix官方文档时就喜欢上了这个文档框架, 所以我也采用的mdbook作为我的nix_config的文档框架。
let
  name = "nix_config";
  pkgs = import <nixpkgs> {};
  markcode = pkgs.callPackage (
    pkgs.fetchFromGitHub {
      owner = "xieby1";
      repo = "markcode";
      rev = "1c414aca28db7f2727f6da118f4e914743780ad0";
      hash = "sha256-B5kmpAIyUihlBqk7oNAdqBmdfCajCmleKBTgLyy0NqU=";
    }
  ) {};
in pkgs.mkShell {
  inherit name;
  buildInputs = with pkgs; [
    mdbook
    markcode
  ];
}