XBFHM2DCPKEYYFOOWMWKHKQ4K5TXGUUBPKYPDC7A577MDFU2LEVQC pkgs: {systemd.user.services.pkgs-update = {enable = true;wantedBy = [ "multi-user.target" ];path = with pkgs; [ coreutils git nix ];script = ''cd /etc/nixosnix flake updategit diff --quiet flake.lock && continuegit add flake.lockgit commit -m "Daily Update at `date -Iseconds`"'';serviceConfig.Type = "oneshot";};systemd.user.timers.pkgs-update = {wantedBy = [ "timers.target" ];timerConfig = {OnCalendar = "daily";Persistent = true;Unit = "pkgs-update.service";};};}
pkgs: {imports = [./backlight-permissions.nix(import ./pkgs-update.nix pkgs)];}
{systemd.services.backlight-permissions = {wantedBy = [ "multi-user.target" ];serviceConfig.Type = "oneshot";script = letglob = "/sys/class/backlight/*/brightness";in ''chown :video ${glob}chmod g+w ${glob}'';};}
{services.keyd = {enable = true;keyboards = {default = {ids = [ "*" ];settings = {main = {capslock = "overload(capslock, esc)";muhenkan = "overload(muhenkan, enter)";henkan = "overload(henkan, delete)";space = "overload(space, space)";rightshift = "capslock";katakanahiragana = "layer(katakanahiragana)";};"capslock:C" = {};"muhenkan:S" = {};"henkan:M" = {space = "C-space";muhenkan = "backspace";};space = {h = "left";j = "down";k = "up";l = "right";u = "pageup";d = "pagedown";b = "C-left";w = "C-right";};};};};};}
util: {programs.wofi = {enable = true;settings = {show = "dmenu";width = 750;height = 400;show_all = false;always_parse_args = true;term = "foot";prompt = "";columns = 3;};style = util.generators.toCss {"*" = {font-family = "\"PlemolJP35 Console NF\"";color = "rgb(53, 185, 171)";background = "transparent";};"#window" = {background = "rgba(0, 0, 0, 0.7)";padding = "10px";border-radius = "10px";border = "1px solid red";};"#input" = {padding = "10px";margin-bottom = "10px";border-radius = "10px";};"#outer-box".padding = "20px";"#img".margin-right = "6px";"#entry" = {padding = "10px";border-radius = "15px";};"#entry:selected".background-color = "#2e3440";"#text".margin = "2px";};};}
pkgs: letlib = pkgs.lib;inherit (builtins) isList hasAttr;inherit (lib.attrsets) mapAttrsToList;inherit (lib.strings) concatStringsSep concatMapStringsSep;inattrs: letkdlGenerator = import ./toKdl.nix pkgs;formatOutput = name: config: letposition =if hasAttr "position" configthen "\tposition x=${toString config.position.x} y=${toString config.position.y}"else "";mode =if hasAttr "mode" configthen "\tmode \"${toString config.mode}\""else "";otherConfig = lib.filterAttrs (k: _: k != "position" && k != "mode") config;otherLines = mapAttrsToList (key: value: "\t${key} \"${toString value}\"") otherConfig;content = lib.filter (s: s != "") ([position mode] ++ otherLines);in''output "${name}" {${concatStringsSep "\n" content}}'';outputNodes =if hasAttr "output" attrsthen concatStringsSep "\n" (mapAttrsToList formatOutput attrs.output)else "";formatWRs = attr:''window-rule {${kdlGenerator.toKDL attr}}'';outputWRs =if hasAttr "window-rule" attrsthen concatStringsSep "\n" (map formatWRs attrs.window-rule)else "";formatSpawnCmd = cmd:"spawn-at-startup "+ concatMapStringsSep " " (arg: "\"${toString arg}\"") (if isList cmdthen cmdelse [cmd]);spawnAtStartupNodes =if hasAttr "spawn-at-startup" attrsthen concatStringsSep "\n" (map formatSpawnCmd attrs.spawn-at-startup)else "";specialAttrs = ["output" "window-rule" "spawn-at-startup" "_extraConfig"];mainAttrs = lib.filterAttrs (k: _: !lib.elem k specialAttrs) attrs;mainConfig = kdlGenerator.toKDL mainAttrs;extraConfig =if hasAttr "_extraConfig" attrsthen attrs._extraConfigelse "";inlib.concatStringsSep "\n\n" (lib.filter (s: s != "") [mainConfig outputNodes outputWRs spawnAtStartupNodes extraConfig])
pkgs: {toKDL = letlib = pkgs.lib;inherit(lib)concatStringsSepmapAttrsToListany;inherit (builtins) typeOf replaceStrings elem;indentStrings = letunlines = lib.splitString "\n";lines = lib.concatStringsSep "\n";indentAll = lines: concatStringsSep "\n" (map (x: " " + x) lines);instringsWithNewlines: indentAll (unlines (lines stringsWithNewlines));sanitizeString = replaceStrings ["\n" ''"''] ["\\n" ''\"''];literalValueToString = element:lib.throwIfNot(elem (typeOf element) ["int""float""string""bool""null"])"Cannot convert value of type ${typeOf element} to KDL literal."(if typeOf element == "null"then "null"else if typeOf element == "bool"thenif elementthen "true"else "false"else if typeOf element == "string"then ''"${sanitizeString element}"''else toString element);convertAttrsToKDL = name: attrs: letchildren =(lib.pipe (attrs._children or []) [(map (child: mapAttrsToList convertAttributeToKDL child))lib.flatten])++ (lib.pipe attrs [(lib.filterAttrs (name: _:!(elem name ["_args""_props""_children"])))(mapAttrsToList convertAttributeToKDL)]);inlib.concatStringsSep " " ([name]++ map literalValueToString (attrs._args or [])++ lib.mapAttrsToList (name: value: "${name}=${literalValueToString value}") (attrs._props or {})++ lib.optional (children != []) ''{${indentStrings children}}'');convertListOfFlatAttrsToKDL = name: list: "${name} ${concatStringsSep " " (map literalValueToString list)}";convertListOfNonFlatAttrsToKDL = name: list: ''${name} {${indentStrings (map (x: convertAttributeToKDL "-" x) list)}}'';convertListToKDL = name: list:if!any (el:elem (typeOf el) ["list""set"])listthen convertListOfFlatAttrsToKDL name listelse convertListOfNonFlatAttrsToKDL name list;convertAttributeToKDL = name: value: letvType = typeOf value;inifelem vType ["int""float""bool""null""string"]then "${name} ${literalValueToString value}"else if vType == "set"then convertAttrsToKDL name valueelse if vType == "list"then convertListToKDL name valueelsethrow ''Cannot convert type `(${typeOf value})` to KDL:${name} = ${toString value}'';inattrs: ''${concatStringsSep "\n" (mapAttrsToList convertAttributeToKDL attrs)}'';}
pkgs:letlib = pkgs.lib;declToString = name: value: " ${name}: ${toString value};";ruleToString = selector: decls:"${selector} {\n" +(lib.concatStringsSep "\n" (lib.mapAttrsToList declToString decls)) +"\n}\n";inattrs: lib.concatStrings (lib.mapAttrsToList ruleToString attrs)
pkgs: {toCss = import ./toCss.nix pkgs;toKdl = import ./toKdl.nix pkgs;toNiriConf = import ./toNiriConf.nix pkgs;}
pkgs: {generators = import ./generators pkgs;}
{programs.foot = {enable = true;settings = {main.font = "PlemolJP35ConsoleNF-Text:size=8";csd.size = 0;colors = {cursor = "111111 cccccc";alpha = 1;foreground = "ffffff";background = "000000";regular0 = "171717";regular1 = "d81765";regular2 = "97d01a";regular3 = "ffa800";regular4 = "16b1fb";regular5 = "ff2491";regular6 = "0fdcb6";regular7 = "ebebeb";bright0 = "979797";bright1 = "ff0000";bright2 = "76b639";bright3 = "e1a126";bright4 = "289cd5";bright5 = "ff2491";bright6 = "0a9b81";bright7 = "f8f8f8";"16" = "fab387";"17" = "f5e0dc";selection-foreground = "cdd6f4";selection-background = "414356";search-box-no-match = "11111b f38ba8";search-box-match = "cdd6f4 313244";jump-labels = "11111b fab387";urls = "89b4fa";};};};}
use std/dirs$env.config.keybindings = [{name: "next_dir",modifier: none,keycode: char_>,mode: vi_normal,event: {send: executehostcommand,cmd: "dirs next"}},{name: "prev_dir",modifier: none,keycode: char_<,mode: vi_normal,event: {send: executehostcommand,cmd: "dirs prev"}}]# change cwddef --env d [q?: string = ~, --skip-nix-shell] {let dir = if ($q | path exists) {$q | path expand} else match $q {'-' => $env.OLDPWD,_ => (zoxide query $q)}if $dir == "" { error make -u { msg: "invalid path" } }cd $dirzoxide add $dirif "NVIM" in $env {send-to-nvim-cmd $env.NVIM $"<cmd>cd ($dir)<CR>"}if $skip_nix_shell {$dir | enter-nix-shell}}def enter-nix-shell []: path -> nothing {path split| skip # skip root dir| generate {|e, acc=""|let a = $acc + "/" + $e{out: $a, next: $a}}| _enter-nix-shell}def _enter-nix-shell []: list<path> -> nothing {let src = if ($in | is-empty) { return } else $inlet car = $src | firstlet cdr = $src | skipif ($car + /shell.nix | path exists) {nix-shell $car --command $"nu -e '($cdr) | _enter-nix-shell'"} else {$cdr | _enter-nix-shell}}def --env mkcd [dir: path] {mkdir $dird $dir}def --wrapped ggrks [...q] {vivaldi https://startpage.com/sp/search?q=($q | str join +)}# $ "/path/to/dir" | path relative-to "/other/path" # "../../path/to/dir"def "path relative-to" [base: path]: path -> path {let target = $in | path expand | path splitlet common = $target | zip $base | take while {|e| $e.0 == $e.1 } | length$base| path expand| path split| skip $common| each { ".." }| append ($target | skip $common)| path join}def "from env" []: [string -> recordlist<string> -> record] {if { describe } == "string" {lines} else ()| parse "{1}={2}"| transpose --as-record --header-row}# for gitdef --env setup-ssh [] {ssh-agent -s| lines| take 2| str replace -r ";.*" ""| from env| load-envssh-add ~/.ssh/id_ed25519}def extract [fname: path] {$fname| path parse| get extension| match $in {.zip => { unzip $fname }.tar.gz => { tar xzvf $fname }.tar.bz2 => { tar xjvf $fname }_ => { error make -u { msg: $"Unsupported file type: ($in)" } }}}def send-to-nvim-cmd [server: path, cmd: string] {nvim --server $server --remote-send $cmd}def --wrapped n [...rest: string] {if "NVIM" in $env {send-to-nvim-cmd $env.NVIM $"<cmd>tabe ($rest | str join ' ')<CR>"return}neovide ...$rest}def normalize-history [] {open $nu.history-path| tr -s ' '| str replace --all --regex ' $' ''| lines | reverse | uniq | reverse| save -f $nu.history-path}def peek-asm [file: path] {clang -O3 -march=native -masm=intel -S -o- $file}def wait-for-process-done [pid: string] {while (ps | get pid | find $pid | is-not-empty) {sleep 10sec}}def on-done [callback: closure,--pid (-p): int = 0,--name (-n): string = ""] {let process = if ($pid == 0) {pidof $name | split words | first} else if ($name != "") {$pid | into string} else {error make -u { msg: "Usage: (-p <int>|-n <string>)" }}wait-for-process-done $processdo $callback}def b []: nothing -> string {let full = cat /sys/class/power_supply/BAT0/energy_full | into intlet now = cat /sys/class/power_supply/BAT0/energy_now | into int$now / $full * 100}def "bl get" [] {let full = cat /sys/class/backlight/amdgpu_bl1/max_brightness | into floatlet now = cat /sys/class/backlight/amdgpu_bl1/brightness | into float$now / $full * 100}def "bl set" [percent: float] {let full = cat /sys/class/backlight/amdgpu_bl1/max_brightness | into float$percent / 100 * $full | into int | save -f /sys/class/backlight/amdgpu_bl1/brightness}def nq [...rest] {nix search nixpkgs ...$rest --json --quiet| from json| transpose| get column1| reject version}def nix-package-query [context: string, --sync] {let cache_name = $"($nu.cache-dir)/nix-pkgs.txt"if not ($nu.cache-dir | path exists) { mkdir $nu.cache-dir }if not ($cache_name | path exists) or $sync {nix search nixpkgs ^ --json| from json| transpose| get column1.pname| tee { save $cache_name }} else {open $cache_name | lines}| collect}def nsh [...pkg: string@nix-package-query] {nix-shell --command nu -p ...$pkg}def rad-subcmd [] {[{ value: "auth", description: "Manage identities and profiles" }{ value: "block", description: "Block repositories or nodes from being seeded or followed" }{ value: "checkout", description: "Checkout a repository into the local directory" }{ value: "clone", description: "Clone a Radicle repository" }{ value: "config", description: "Manage your local Radicle configuration" }{ value: "fork", description: "Create a fork of a repository" }{ value: "help", description: "CLI help" }{ value: "id", description: "Manage repository identities" }{ value: "init", description: "Initialize a Radicle repository" }{ value: "inbox", description: "Manage your Radicle notifications" }{ value: "inspect", description: "Inspect a Radicle repository" }{ value: "issue", description: "Manage issues" }{ value: "ls", description: "List repositories" }{ value: "node", description: "Control and query the Radicle Node" }{ value: "patch", description: "Manage patches" }{ value: "path", description: "Display the Radicle home path" }{ value: "clean", description: "Remove all remotes from a repository" }{ value: "self", description: "Show information about your identity and device" }{ value: "seed", description: "Manage repository seeding policies" }{ value: "follow", description: "Manage node follow policies" }{ value: "unblock", description: "Unblock repositories or nodes to allow them to be seeded or followed" }{ value: "unfollow", description: "Unfollow a peer" }{ value: "unseed", description: "Remove repository seeding policies" }{ value: "remote", description: "Manage a repository's remotes" }{ value: "stats", description: "Displays aggregated repository and node metrics" }{ value: "sync", description: "Sync repositories to the network" }]}def rad-auth-subcmd [] {[{ value: "--alias", description: "When initializing an identity, sets the node alias" }{ value: "--stdin", description: "Read passphrasee from stdin (default: false)" }]}def rad-checkout-subcmd [] {[{ value: "--remote", description: "Remote peer to checkout" }{ value: "--no-confirm", description: "Don't ask for confirmation during checkout" }]}def rad-clone-subcmd [] {[{ value: "--bare", description: "Make a bare repository" }{ value: "--scope", description: "Follow scope: `followed` or `all` (default: all)" }{ value: "--seed", description: "Clone from this seed (may be specified multiple times)" }{ value: "--timeout", description: "Timeout for fetching repository (default: 9)" }]}def rad-config-subcmd [] {[showiniteditgetschemasetunsetpushremove]}def rad-id-subcmd [] {[listupdateeditshowacceptredact]}def rad-init-subcmd [] {[{ value: "--name", description: "Name of the repository" }{ value: "--description", description: "Description of the repository" }{ value: "--default-branch", description: "The default branch of the repository" }{ value: "--scope", description: "Repository follow scope: `followed` or `all` (default: all)" }{ value: "--private", description: "Set repository visibility to *private*" }{ value: "--public", description: "Set repository visibility to *public*" }{ value: "--existing", description: "Setup repository as an existing Radicle repository" }{ value: "--set-upstream", description: "Setup the upstream of the default branch" }{ value: "--setup-signing", description: "Setup the radicle key as a signing key for this repository" }{ value: "--no-confirm", description: "Don't ask for confirmation during setup" }{ value: "--no-seed", description: "Don't seed this repository after initializing it" }{ value: "--verbose", description: "Verbose mode" }]}def rad-inbox-subcmd [] {[listshowclear{ value: "--all", description: "Operate on all repositories" }{ value: "--repo", description: "Operate on the given repository (default: rad .)" }{ value: "--sort-by", description: "Sort by `id` or `timestamp` (default: timestamp)" }{ value: "--reverse", description: "Reverse the list" }{ value: "--show-unknown", description: "Show any updates that were not recognized" }]}def rad-inspect-subcmd [] {[{ value: "--rid", description: "Return the repository identifier (RID)" }{ value: "--payload", description: "Inspect the repository's identity payload" }{ value: "--refs", description: "Inspect the repository's refs on the local device" }{ value: "--sigrefs", description: "Inspect the values of `rad/sigrefs` for all remotes of this repository" }{ value: "--identity", description: "Inspect the identity document" }{ value: "--visibility", description: "Inspect the repository's visibility" }{ value: "--delegates", description: "Inspect the repository's delegates" }{ value: "--policy", description: "Inspect the repository's seeding policy" }{ value: "--history", description: "Show the history of the repository identity document" }]}def rad-issue-subcmd [] {[deleteeditlistopenreactassignlabelcommentshowstatecache{ value: "--repo", description: "Operate on the given repository (default: cwd)" }{ value: "--no-announce", description: "Don't announce issue to peers" }{ value: "--header", description: "Show only the issue header, hiding the comments" }{ value: "--quiet", description: "Don't print anything" }]}def rad-ls-subcmd [] {[{ value: "--private", description: "Show only private repositories" }{ value: "--public", description: "Show only public repositories" }{ value: "--seeded", description: "Show all seeded repositories" }{ value: "--all", description: "Show all repositories in storage" }{ value: "--verbose", description: "Verbose output" }]}def rad-node-subcmd [] {[statusstartstoplogsdebugconnectroutinginventoryeventsconfigdb]}def rad-patch-subcmd [] {[{ value: "list", description: "List patched in the current repository. The default is --open." }{ value: "show", description: "Shows information on the given patch." }{ value: "diff", description: "Outputs the patch diff, using Radicle's diffing tool." }{ value: "edit", description: "Edits a patch revision comment." }{ value: "ready", description: "Mark a patch as ready to review." }{ value: "review", description: "Review a patch. Indicate acceptance or rejection of a patch revision along with a comment." }{ value: "archive", description: "Archive a patch." }{ value: "set", description: "Set the currrent branch upstream to a patch reference." }{ value: "update", description: "Updates a paatch to the current repository HEAD." }{ value: "checkout", description: "Switch to a given patch, by creating a branch that points to the patch head." }{ value: "comment", description: "Comment on a patch revision, optionally replying to an existing comment." }deletelabelredact]}def rad-clean-subcmd [] {[{ value: "--no-confirm", description: "Do not ask for confirmation before removal (default: false)" }]}def rad-self-subcmd [] {[{ value: "--did", description: "Show your DID" }{ value: "--alias", description: "Show your Node alias" }{ value: "--home", description: "Show your Radicle home" }{ value: "--config", description: "Show the location of your configuration file" }{ value: "--ssh-key", description: "Show your public key in OpenSSH format" }{ value: "--ssh-fingerprint", description: "Show your public key fingerprint in OpenSSH format" }]}def rad-seed-subcmd [] {[{ value: "--fetch", description: "Fetch repository after updating seeding policy" }{ value: "--no-fetch", description: "Fetch repository after updating seeding policy" }{ value: "--from", description: "Fetch from the given node (may be specified multiple times)" }{ value: "--timeout", description: "Fetch timeout in seconds (default: 9)" }{ value: "--scope", description: "Peer follow scope for this repository" }{ value: "--verbose", description: "Verbose output" }]}def rad-follow-subcmd [] {[{ value: "--alias", description: "Associate an alias to a followed peer" }{ value: "--verbose", description: "Verbose output" }]}def rad-unfollow-subcmd [] {["--verbose"]}def rad-remote-subcmd [] {[listaddrm]}def rad-sync-subcmd [] {[{ value: "--sort-by", description: "Sort the table by column (options: nid, alias, status)" }{ value: "--fetch", description: "Turn on fetching (default: true)" }{ value: "--announce", description: "Turn on ref announcing (default: true)" }{ value: "--inventory", description: "Turn on inventory announcing (default: false)" }{ value: "--timeout", description: "How many seconds to wait while syncing" }{ value: "--seed", description: "Sync with the given node (may be specified multiple times)" }{ value: "--replicas", description: "Sync with a specific number of seeds" }{ value: "--replicas-max", description: "Sync with an upper bound number of seeds" }{ value: "--verbose", description: "Verbose output" }{ value: "--debug", description: "Print debug information afer sync" }]}extern rad [sub?: string@rad-subcmd]extern "rad auth" [sub?: string@rad-auth-subcmd]extern "rad checkout" [sub?: string@rad-checkout-subcmd]extern "rad clone" [sub?: string@rad-clone-subcmd]extern "rad config" [sub?: string@rad-config-subcmd]extern "rad id" [sub?: string@rad-id-subcmd]extern "rad inbox" [sub?: string@rad-inbox-subcmd]extern "rad inspect" [sub?: string@rad-inspect-subcmd]extern "rad issue" [sub?: string@rad-issue-subcmd]extern "rad ls" [sub?: string@rad-ls-subcmd]extern "rad node" [sub?: string@rad-node-subcmd]extern "rad patch" [sub?: string@rad-patch-subcmd]extern "rad clean" [sub?: string@rad-clean-subcmd]extern "rad self" [sub?: string@rad-self-subcmd]extern "rad seed" [sub?: string@rad-seed-subcmd]extern "rad follow" [sub?: string@rad-follow-subcmd]extern "rad unfollow" [sub?: string@rad-unfollow-subcmd]extern "rad remote" [sub?: string@rad-remote-subcmd]extern "rad sync" [sub?: string@rad-sync-subcmd]
{home.shellAliases = import ./aliases.nix;programs.carapace = {enable = true;enableNushellIntegration = true;};programs.nushell = {enable = true;configFile.source = ./nu/pre.nu;settings = {cursor_shape.vi_insert = "line";cursor_shape.vi_normal = "block";edit_mode = "vi";table.mode = "none";};};programs.starship = {enable = true;enableZshIntegration = true;};programs.zoxide = {enable = true;enableZshIntegration = true;};programs.zsh = {enable = true;autocd = true;autosuggestion.enable = true;enableCompletion = true;syntaxHighlighting.enable = true;history = {ignoreAllDups = true;ignoreSpace = true;size = 100000000;};initContent = ''[ $SHLVL -eq 1 ] && exec nubindkey -v'';};}
# aliases for nushellletsudo = "sudo -E";in {c = "n /etc/nixos/configuration.nix";g = "git";h = "n ~/.config/home-manager/home.nix";hs = "home-manager switch";laz = "lazygit";nix-shell = "nix-shell --command nu";ns = "${sudo} nixos-rebuild switch";rmf = "rm -rf";inherit sudo;}
{ config, pkgs, ... }:{home.packages = with pkgs; [btopcmakefastfetchgnumakellvmPackages_21.bintools-unwrappedllvmPackages_21.clangUseLLVMllvmPackages_21.clang-toolsllvmPackages_21.llvmluajit_2_1lua-language-servermesonninjanixdnodejs_latestpijulripgreprustuptinymistvivaldizvm];}
/*** @file include/testing.h* @brief Define macros for testing* @note Tests not in the test_filter block are always executed*/#pragma once#include "chore.h"#ifdef TEST_MODE#include "ansiesc.h"#include "gene.h"extern int test__success;extern int test__count;#define TEST_HEADER " ■ " ESCBLU "Testing " ESCLR#define ALIGN_COL(name) \do { \int col = 6 - ((int)strlen(TEST_HEADER #name) - 3) / 8; \for (int i = 0; i < col; i++) putchar('\t'); \} while (0)#define PRINT_FAILED(cnt) PRINT("\n └" ESCRED ESBLD "[NG:", cnt, "]\n" ESCLR)#define PRINT_SUCCESS puts("=> " ESCGRN "[OK]" ESCLR)// zig style testing syntax#define test(name) \static void test__test##name(int *); \[[gnu::constructor]] static void test__run##name() { \test__count++; \printf(TEST_HEADER ESBLD #name ESCLR); \int failed = 0; \test__test##name(&failed); \if (failed) { \PRINT_FAILED(failed); \return; \} \ALIGN_COL(name); \PRINT_SUCCESS; \test__success++; \} \static void test__test##name(int *test__failed)#ifdef TEST_FILTER#define test_filter(filter) if (strstr(filter, TEST_FILTER))#else#define test_filter(_) if (0)#endif// generate function parameter#define PMAP(tok, _, ...) \t->tok __VA_OPT__(, RECURSE(PM, AP)(tok##p, __VA_ARGS__))// generate struct member// e.g.) T1 p /* expected */; T2 pp /* arg1 */; T3 ppp /* arg2 */; ...#define SMAP(tok, T1, ...) \T1 tok; \__VA_OPT__(RECURSE(SM, AP)(tok##p, __VA_ARGS__))#define CALL(fn, ...) fn(EVAL(PMAP(pp, __VA_ARGS__)))#define STDEF(...) \struct { \EVAL(SMAP(p, __VA_ARGS__)) \}// if {a, b, c} is passed as a macro parameter, it becomes "{a", "b", "c}", so// it must be received as a variable length argument.#define test_table(name, fn, signature, ...) \test_table_with_cleanup(name, fn, EMP, signature, __VA_ARGS__)#define test_table_with_cleanup(name, fn, cl, signature, ...) \[[gnu::constructor]] static void test__tabletest##name() { \test__count++; \printf(TEST_HEADER ESBLD #name ESCLR); \int failed = 0; \typedef STDEF signature S; \S data[] = __VA_ARGS__; \for (size_t i = 0; i < sizeof data / sizeof(S); i++) { \S *t = data + i; \int *test__failed /* for expecteq */ = &failed; \int pre = failed; \auto result = CALL(fn, CDR signature); \expecteq(t->p, result); \cl(result); \if (pre != failed) PRINT(" at test case ", i); \} \if (failed) { \PRINT_FAILED(failed); \return; \} \ALIGN_COL(name); \PRINT_SUCCESS; \test__success++; \}// disable main function somewhere#define main test__dummymain#define expect(cond) \do { \if (cond) break; \puts("\n ├┬ Unexpected result at " HERE); \printf(" │└─ `" #cond "` " ESCRED ESBLD " [NG]" ESCLR); \(*test__failed)++; \} while (0)#define expecteq(expected, actual) \do { \typeof(actual) const lhs = expected; \auto const rhs = actual; \if (eq(lhs, rhs)) break; \puts("\n ├┬ Expected equal at " HERE); \printf(" │├─ " ESCGRN "Expected" ESCLR ": "); \printanyf(lhs); \printf("\n │└─ " ESCRED "Actual" ESCLR ": "); \printanyf(rhs); \printf(ESCRED ESBLD " [NG]" ESCLR); \(*test__failed)++; \} while (0)#define expectneq(unexpected, actual) \do { \typeof(actual) const lhs = unexpected; \auto const rhs = actual; \if (!eq(lhs, rhs)) break; \int __llen = (int)strlen(#unexpected); \int __rlen = (int)strlen(#actual); \int __lpad = more(0, __rlen - __llen); \int __rpad = more(0, __llen - __rlen); \puts("\n ├┬ Unexpected equality at " HERE); \printf(" │├─ Left side: `" #unexpected "` ─"); \for (int __i = 0; __i < __lpad; __i++) printf("─"); \puts("┐"); \printf(" │└─ Right side: `" #actual "` ─"); \for (int __i = 0; __i < __rpad; __i++) printf("─"); \printf("┴─➤ "); \printanyf(lhs); \printf(ESCRED ESBLD " [NG]" ESCLR); \(*test__failed)++; \} while (0)#else// --gc-sections#define test(name) \[[gnu::unused]] static void test__dum##name(int *test__failed)#define test_table(...)#define test_filter(filter)#define expect(cond) \do { \_ = cond; \_ = test__failed; \} while (0)#define expecteq(lhs, rhs) \do { \_ = lhs; \_ = rhs; \_ = test__failed; \} while (0)#define expectneq(lhs, rhs) \do { \_ = lhs; \_ = rhs; \_ = test__failed; \} while (0)#endif
/*** @file src/testing.c*/#include "testing.h"#undef main#ifdef TEST_MODEint test__success;int test__count;int main() {PRINT("\n" ESCBLU "Passed" ESCLR ": ", test__success, "/", test__count, "\n");// pre-commit: make test || exit 1return test__count - test__success;}test (testing_test) {expect(1 + 1 == 2);expecteq(3, 3);expectneq(1, 10);test_filter("testing test") {expect(false);expect(1 + 1 == 1);expecteq(5, 3);expecteq(3, 3 + 3);expectneq(3 + 7, 50 / 5 + 6 * 0);expect(false);}}#endif
/*** @file include/gene.h* @brief Define macros for generic programming*/#pragma once#include "def.h"#include <stddef.h>#define overloadable [[clang::overloadable]]#define DEF_PRIM(T) \overloadable void printany(T); \overloadable void printanyf(T); \overloadable bool eq(T, T);#define DEF_GEN(T) DEF_PRIM(T) DEF_PRIM(T *)#define TYPES bool, char, int, size_t, long, long long, double#define PRIM_TYPES void *#define APPLY_ADDSUB(M) M(Add, +) M(Sub, -)#define APPLY_ARTHM(M) APPLY_ADDSUB(M) M(Mul, *) M(Div, /)#define APPLY_LTGT(M) M(Lt, <) M(Gt, >)MAP(DEF_GEN, TYPES)MAP(DEF_PRIM, PRIM_TYPES)#define _PRINTREC(first, ...) \printany(first); \__VA_OPT__(RECURSE(_PRINT, REC)(__VA_ARGS__))#define PRINT(...) \do { EVAL(_PRINTREC(__VA_ARGS__)) } while (0)
/*** @file src/gene.c* @brief Define generic functions*/#include "gene.h"#include "mathdef.h"#include "testing.h"constexpr double eps = 1e-5;static bool doubleEq(double a, double b) {if (fabs(b) < eps) return fabs(a) < eps; // prevent 0-div when b is near 0if (a < 0 != b < 0) return false; // mis signedreturn fabs(a / b - 1.0) < eps; // cmp based on ratios}static bool complexEq(comp a, comp b) {return doubleEq(creal(a), creal(b)) && doubleEq(cimag(a), cimag(b));}test_table(double_eq, doubleEq, (bool, double, double),{{ true, 1.0, 1.0},{ true, 1e-10, 0},{ true, 1e100, 1e100 + 1e10},{false, 0, 1},{false, NAN, NAN},{false, NAN, 1e10},{false, INFINITY, INFINITY},{false, INFINITY, 1e100},})test_table(complex_eq, complexEq, (bool, comp, comp),{{ true, 0, 0},{ true, 1 + 3i, 1.0 + 3.0i},{ true, 1.0 + 1e-10 + 3i, 1 + 3i},{false, 0, 1},{false, 3 + 5i, -1 + 3i},})#pragma clang attribute push(overloadable, apply_to = function)void printany(int x) {printf("%d", x);}void printany(size_t x) {printf("%zu", x);}void printany(double x) {printf("%lf", x);}void printany(char *x) {printf("%s", x);}void printany(char x) {printf("%c", x);}void printany(bool x) {printf(x ? "`true`" : "`false`");}void printany(long x) {printf("%ld", x);}void printany(long long x) {printf("%lld", x);}void printany(void *x) {if (x) printf("0x%p", x);else printf("`nullptr`");}void printanyf(int x) {PRINT(x);}void printanyf(size_t x) {PRINT(x, "LU");}void printanyf(double x) {PRINT(x);}void printanyf(char *x) {PRINT("\"", x, "\"");}void printanyf(char x) {PRINT("'", x, "'");}void printanyf(bool x) {PRINT(x);}void printanyf(long x) {PRINT(x, "L");}void printanyf(long long x) {PRINT(x, "LL");}void printanyf(void *x) {PRINT(x);}#define EQ_DIRECTLY(T) \bool eq(T x, T y) { \return x == y; \}MAP(EQ_DIRECTLY, int, size_t, char, bool, void *)bool eq(double x, double y) {return doubleEq(x, y);}bool eq(comp x, comp y) {return complexEq(x, y);}bool eq(char *x, char *y) {return !strcmp(x, y);}#pragma clang attribute pop
/*** @file include/def.h*/#pragma once#define _TOSTR(x) #x#define TOSTR(x) _TOSTR(x)#define EMP(...)#define EXPAND(...) __VA_ARGS__// max depth: 4 ^ 5 = 1024#define EVAL(...) EVAL1(EVAL1(EVAL1(EVAL1(__VA_ARGS__))))#define EVAL1(...) EVAL2(EVAL2(EVAL2(EVAL2(__VA_ARGS__))))#define EVAL2(...) EVAL3(EVAL3(EVAL3(EVAL3(__VA_ARGS__))))#define EVAL3(...) EVAL4(EVAL4(EVAL4(EVAL4(__VA_ARGS__))))#define EVAL4(...) EXPAND(EXPAND(EXPAND(EXPAND(__VA_ARGS__))))#define PRIM_CAT(a, b) a##b#define CAT(a, b) PRIM_CAT(a, b)#define PRIM_CAR(_1, ...) _1#define PRIM_CDR(_1, ...) __VA_ARGS__#define CAR(...) PRIM_CAR(__VA_ARGS__)#define CDR(...) PRIM_CDR(__VA_ARGS__)#define CHECK(x) CAR(CDR(x, 0))#define NOT(x) CHECK(PRIM_CAT(NOT_, x))#define NOT_0 _, 1#define BOOL(x) NOT(NOT(x))#define RECURSE(a, b) CAT EMP()(a, b)#define PRIM_MAP(M, _1, ...) \M(_1) __VA_OPT__(RECURSE(PRIM, _MAP)(M, __VA_ARGS__))#define MAP(...) EVAL(PRIM_MAP(__VA_ARGS__))#define PRIM_MAP_PAIR(M, _1, ...) \M _1 __VA_OPT__(RECURSE(PRIM, _MAP_PAIR)(M, __VA_ARGS__))#define MAP_PAIR(...) EVAL(PRIM_MAP_PAIR(__VA_ARGS__))
/*** @file src/def.c*/#include "def.h"#include "testing.h"test_table(bool_macro, , (int, int),{{0, BOOL(0)},{1, BOOL(1)},{1, BOOL(8)},{0, NOT(10)},{1, NOT(0)},})
/*** @file include/chore.h* @brief Define util macros*/#pragma once#include "def.h"#include <dirent.h>#include <stdio.h>#include <string.h>constexpr size_t alpha_n = 'z' - 'a' + 1;#define HERE __FILE__ ":" TOSTR(__LINE__)#define less(lhs, rhs) ((lhs) < (rhs) ? (lhs) : (rhs))#define more(lhs, rhs) ((lhs) > (rhs) ? (lhs) : (rhs))#define overloadable [[clang::overloadable]]#define ondrop(cl) [[gnu::cleanup(cl)]]#define drop ondrop(freecl)#define dropfile ondrop(fclosecl)#define dropdir ondrop(closedircl)#define __ CAT(_DISCARD_, __COUNTER__) [[gnu::unused]]#define _ auto __#define xalloc(T, size) ((T *)palloc(size * sizeof(T)))#define nfree(p) \do { \if (p == nullptr) break; \free(p); \p = nullptr; \} while (0)#define bit_cast(T, ...) \({ \auto src = __VA_ARGS__; \static_assert(sizeof(T) == sizeof(src)); \T dst; \memcpy(&dst, &src, sizeof(T)); \dst; \})[[gnu::const]] bool isInt(double);[[gnu::returns_nonnull, nodiscard("allocation")]] void *palloc(size_t);[[gnu::nonnull]] void freecl(void *);[[gnu::nonnull]] void fclosecl(FILE **);[[gnu::nonnull]] void closedircl(DIR **);
/*** @file src/chore.c* @brief Define util functions*/#include "chore.h"#include "exproriented.h"#include "mathdef.h"#include "testing.h"/*** @brief Check if the decimal part is 0* @param[in] arg Checked double number* @return Is decimal part 0*/inline bool isInt(double arg) {if (isinf(arg) || isnan(arg)) return false;if (arg < -__LONG_MAX__ - 1L || (double)__LONG_MAX__ < arg) return false;return arg == (double)(long)arg;}test_table(isint, isInt, (bool, double),{{ true, 5.0},{ true, 3.000},{ true, 100},{ true, -10},{false, 5.6},{false, 10.9},{false, 99.99999},{false, -10.4}})/*** @brief panic alloc* @param[in] sz Memory size* @warning Unrecoverable*/void *palloc(size_t sz) {return malloc(sz) ?: p$panic(ERR_ALLOCATION_FAILURE);}/*** @brief free for drop*/void freecl(void *p) {free(*bit_cast(void **, p));}void fclosecl(FILE **fp) {fclose(*fp);}void closedircl(DIR **fp) {closedir(*fp);}
/*** @file include/ansiesc.h* @brief Define escape sequence macros*/#pragma once#define ESCSI "\033["#define ESCLR ESCSI "0m"#define ESBLD ESCSI "1m"#define ESTHN ESCSI "2m"#define ESITA ESCSI "3m"#define ESULN ESCSI "4m"#define ESBLN ESCSI "5m"#define ESFBLN ESCSI "6m"#define ESREV ESCSI "7m"#define ESHID ESCSI "8m"#define ESUDO ESCSI "9m"#define ESCBLK ESCSI "30m"#define ESCRED ESCSI "31m"#define ESCGRN ESCSI "32m"#define ESCYEL ESCSI "33m"#define ESCBLU ESCSI "34m"#define ESCMGN ESCSI "35m"#define ESCCYN ESCSI "36m"#define ESCWHT ESCSI "37m"#define ESCBBLK ESCSI "40m"#define ESCBRED ESCSI "41m"#define ESCBGRN ESCSI "42m"#define ESCBYEL ESCSI "43m"#define ESCBBLU ESCSI "44m"#define ESCBMGN ESCSI "45m"#define ESCBCYN ESCSI "46m"#define ESCBWHT ESCSI "47m"#define ESCCODE(code) ESCSI "38;5;" #code "m"#define ESCCODE_RGB(r, g, b) ESCSI "38;2;" #r ";" #g ";" #b "m"#define ESCUU(n) ESCSI #n "A"#define ESCUD(n) ESCSI #n "B"#define ESCUF(n) ESCSI #n "C"#define ESCUB(n) ESCSI #n "D"#define ESCNL(n) ESCSI #n "E"#define ESCPL(n) ESCSI #n "F"#define ESCHA(n) ESCSI #n "G"#define ESCUP(n, m) ESCSI #n ";" #m "H"#define ESED(n) ESCSI #n "J"#define ESEL(n) ESCSI #n "K"#define ESSU(n) ESCSI #n "S"#define ESSD(n) ESCSI #n "T"#define ESHVP(n, m) ESCSI #n ";" #m "f"#define ESSCP ESCSI "s"#define ESRCP ESCSI "u"
/*** @file src/ansiesc.c* @brief Test escape sequence macros*/#include "ansiesc.h"#include "testing.h"test (ansi_escape_sequence) {expect(true);test_filter("all") {puts(ESCLR);#define PRINT_HELLO(x) puts(x "hello" ESCLR);MAP(PRINT_HELLO,ESBLD,ESTHN,ESITA,ESULN,ESBLN,ESFBLN,ESREV,ESHID,ESUDO,ESCRED,ESCGRN,ESCYEL,ESCBLU,ESCMGN,ESCCYN,ESCBLK,ESCBRED,ESCBGRN,ESCBYEL,ESCBBLU,ESCBMGN,ESCBCYN,ESCBBLK,ESCCODE(100),ESCCODE_RGB(100, 100, 100))}}
#pragma once#include <stdlib.h>typedef struct {char const **buf;int len;} table_t;#define droptbl ondrop(free_tbl)static void free_tbl(table_t *tbl) {free(tbl->buf);}
#include "main.h"#include "../testing/testing.h"#include <luajit-2.1/lauxlib.h>#include <luajit-2.1/lua.h>#include <luajit-2.1/lualib.h>#include <stdlib.h>#include <string.h>lua_State *L;#define lua_unreachable(...) \({ \luaL_error(L, __VA_ARGS__); \nullptr; \})static table_t new_table(size_t len) {return (table_t){malloc(len * sizeof(char *)) ?: lua_unreachable("allocation failure"),len,};}char const *basename(char const *path) {char const *last = strrchr(path, '/');return last ? last + 1 : path;}test_table(basename_test, basename, (char const *, char const *),{{ "main.c", "src/main.c"},{"init.lua", "$(HOME)/.config/nvim/init.lua"},})static bool ismatch(char const *target, char const *pattern) {for (; *target && *pattern; target++) pattern += *target == *pattern;return *pattern == '\0';}test_table(match_test, ismatch, (bool, char const *, char const *),{{ true, "aabbccdd", "abcd"},{ true, "src/main.zig", "s/mz"},{false, "hello", "world"},{false, "init.lua", "iin"},})static table_t fuzfilter(table_t tbl, char const *pat) {table_t ret = new_table(tbl.len);int id = 0;bool isfullpath = strchr(pat, '/');for (int i = 0; i < tbl.len; i++) {char const *target = isfullpath ? tbl.buf[i] : basename(tbl.buf[i]);if (ismatch(target, pat)) ret.buf[id++] = tbl.buf[i];}ret.len = id;return ret;}static int fuzpath(lua_State *arg) {L = arg;luaL_checktype(L, 1, LUA_TTABLE);luaL_checktype(L, 2, LUA_TSTRING);size_t tbl_len = lua_objlen(L, 1);table_t table droptbl = new_table(tbl_len);for (size_t i = 1; i <= tbl_len; i++) {lua_rawgeti(L, 1, i);table.buf[i - 1] = luaL_checkstring(L, -1);lua_pop(L, 1);}char const *pattern = luaL_checkstring(L, 2);table_t result droptbl = fuzfilter(table, pattern);lua_newtable(L);for (int i = 0; i < result.len; i++) {lua_pushstring(L, result.buf[i]);lua_rawseti(L, -2, i + 1);}return 1;}int luaopen_fuzpath(lua_State *L) {static luaL_Reg const funcs[] = {{"fuzpath", fuzpath},{ nullptr, nullptr}};luaL_newlib(L, funcs);return 1;}
.PHONY: lib-build lib-clean plug-install plug-sync plug-gc plug-clean setupPREFIX = $(HOME)/.local/state/nvimCC = ccache clangSRCDIRS = $(filter-out src/testing, $(wildcard src/*))TARGETS = $(patsubst src/%, lib/%.so, $(SRCDIRS))CFLAGS := -std=c2y -Wtautological-compare -Wsign-compare -Wall -Wextra -O3 \-fforce-emit-vtables -ffunction-sections -fdata-sections -fPIC \-faddrsig -march=native -mtune=native -funroll-loops -fomit-frame-pointerLDFLAGS = -flto=full -fwhole-program-vtables -funroll-loops -fomit-frame-pointer \-O3 -shared -lmTESTFLAGS := -std=c2y -DTEST_MODE -gfull $(shell pkg-config --cflags luajit)TESTLDFLAGS := -lm $(shell pkg-config --libs luajit)TESTTARGETS := $(addsuffix /test, $(PREFIX))lib-build: $(TARGETS)$(TARGETS): lib/%.so: src/%$(CC) $</*.c $(CFLAGS) $(LDFLAGS) -o $@lib-test: $(TESTTARGETS)$(TESTTARGETS): %/test: %$(CC) $</*.c $(wildcard src/testing/*.c) $(TESTFLAGS) $(TESTLDFLAGS) -o $@./$@lib-clean:rm $(TARGETS)GITHUB_URL := https://github.comPLUGINDIR := $(PREFIX)/pluginsPLUGINS := \MunifTanjim/nui.nvim \SmiteshP/nvim-navbuddy \SmiteshP/nvim-navic \altermo/ultimate-autopair.nvim \andersevenrud/nvim_context_vt \folke/flash.nvim \gbprod/substitute.nvim \hadronized/hop.nvim \kylechui/nvim-surround \niuiic/core.nvim \niuiic/track.nvim \nvim-lua/plenary.nvim \nvim-telescope/telescope.nvim \nvim-tree/nvim-web-devicons \nvim-treesitter/nvim-treesitter \stevearc/oil.nvim \utilyre/sentiment.nvim \vim-jp/nvimdoc-ja \vim-jp/vimdoc-ja \zbirenbaum/copilot.lua \sphamba/smear-cursor.nvim \# destination directory namePLUGIN_PATHS := $(addprefix $(PLUGINDIR)/, $(PLUGINS))# list of installed repositoriesACCOUNTS_EXIST := $(wildcard $(PLUGINDIR)/*/) # plugin/account1/ plugin/account2/ plugin/account3/ ...REPOS_INSTALLED_PATHS := $(wildcard $(PLUGINDIR)/*/*) # plugin/account1/plug1 plugin/account2/plug1 ...GARBAGE_ACCOUNTS_PATHS := $(filter-out $(dir $(PLUGINS)), $(notdir $(ACCOUNTS_EXIST))) # accountN/ accountM/ ...GARBAGE_REPOS_PATHS := $(filter-out $(PLUGIN_PATHS), $(REPOS_INSTALLED_PATHS)) # plugin/accountN/plugN ...GARBAGES := $(GARBAGE_REPOS_PATHS) $(GARBAGE_ACCOUNTS_PATHS)NEOVIM_PREFIX := ~/.local$(PLUGINDIR)/%: | $(PLUGINDIR)/ ; git clone --depth 1 $(GITHUB_URL)/$* $@%/plug-sync: $(PLUGINDIR)/% ; cd $< && git pull%/plug-rm:ifneq ($(wildcard $(PLUGINDIR)/$*),) # check if file existsrm -rf $(PLUGINDIR)/$*endifplug-install: $(PLUGIN_PATHS)plug-sync: $(addsuffix /plug-sync, $(PLUGINS))plug-gc: ; rm -rf $(GARBAGES)plug-clean: $(addsuffix /plug-rm, $(PLUGINS))plug-update: plug-sync$(MAKE) -f make/setup-treesitter.mk PREFIX=$(NEOVIM_PREFIX)setup: plug-update lib-buildLLMFILE ?= llmfile.txtFILES ?= makefile init.luaDIRS ?= lua lua/ftplugin src/fuzpath src/testing makeFILES_IN_DIRS := $(wildcard $(addsuffix /*.*, $(DIRS)))LIST_FILES ?= $(FILES) $(FILES_IN_DIRS)$(LLMFILE): $(LIST_FILES) # for the LLM to readecho $^ | sed 's/ /\n/g' > $@echo >> $@ # newline# `head` automatically inserts the file name at the start of the filehead -n 9999 $^ >> $@llmfile: $(LLMFILE)%/: ; mkdir -p $@
.PHONY: build installPREFIX ?= ~/.localall: build installbuild:nvim --headless -c "lua Load_plugin 'nvim-treesitter/nvim-treesitter'" -c "TSUpdateSync all" -c "q"install:cp -r $(HOME)/.local/state/nvim/plugins/nvim-treesitter/nvim-treesitter/parser $(PREFIX)/lib/nvimcp -r $(HOME)/.local/state/nvim/plugins/nvim-treesitter/nvim-treesitter/queries $(PREFIX)/share/nvim/runtime
M = {}function M.open_wrapwin()local curwin = vim.api.nvim_tabpage_get_win(0)local newwin = vim.api.nvim_open_win(0, false, { split = 'left' })local winheight = vim.api.nvim_win_get_height(0)local winbot = vim.fn.line('w$')local targetline = winbot + math.floor(winheight / 2) - 1-- scroll new window page forwardvim.api.nvim_win_set_cursor(0, { targetline, 1 })vim.cmd.normal 'zz'-- enable scrollbind for bothvim.o.scrollbind = truevim.api.nvim_tabpage_set_win(0, newwin)vim.o.scrollbind = true-- delete only new windowvim.keymap.set('n', '<C-c>', function()vim.api.nvim_win_close(newwin, false)vim.keymap.set('n', 'Q', 'ZZ')end, { buffer = true })-- delete both of windowsvim.keymap.set('n', 'Q', function()vim.api.nvim_win_close(newwin, false)vim.api.nvim_tabpage_set_win(0, curwin)vim.cmd.quit()end, { buffer = true })vim.keymap.set('n', '<C-f>', '2<C-f>', { buffer = true })vim.keymap.set('n', '<C-b>', '2<C-b>', { buffer = true })vim.keymap.set('n', '<C-d>', '<C-f>', { buffer = true })vim.keymap.set('n', '<C-u>', '<C-b>', { buffer = true })endreturn M
M = {}function M.get_visual_selection()local vpos = vim.fn.getpos("v")local begin_pos = { vpos[2], vpos[3] - 1 }local end_pos = vim.api.nvim_win_get_cursor(0)if begin_pos[1] < end_pos[1] or begin_pos[1] == end_pos[1] and begin_pos[2] <= end_pos[2] thenreturn { start = begin_pos, last = end_pos }elsereturn { start = end_pos, last = begin_pos }endendreturn M
local extui = require 'vim._extui'extui.enable({enable = true})
M = {}---@param str string---@return stringlocal function make_uniq(str)return '<Plug>(' .. str .. ')'endlocal function isfun(any)return type(any) == 'function'endlocal function map(mode, lhs, rhs, remap)vim.keymap.set(mode, lhs, rhs, { expr = isfun(rhs), remap = remap })end---@class Autos---@field entering (fun(): string?|string)?---@field repeating (fun(): string?|string)?---@field leaving (fun(): string?|string)? (reserved)---@class Follower---@field key string---@field run_when Autos?---@param mode string|string[]---@param leader string---@param followers Follower[]function M.set_submode_keymap(mode, leader, followers)local uniqid = make_uniq(leader)local uniqprefix = uniqid .. leaderfor _, follower in ipairs(followers) dolocal key = leader .. follower.keylocal run_when = follower.run_when or {}local get_rhs = function(any)if not any thenreturn key .. uniqprefixelseif type(any) == 'string' thenreturn any .. uniqprefixelseif isfun(any) thenreturn function()return (any() or '') .. uniqprefixendendendmap(mode, key, get_rhs(run_when.entering), true)map(mode, uniqprefix .. follower.key, get_rhs(run_when.repeating), true)endmap(mode, uniqprefix, '', true)end---@class AccOpts---@field base number?---@field thre number?---@param mode string|string[]---@param key string---@param callback (fun(): string?)?---@param opts AccOpts?function M.acceleration_key(mode, key, callback, opts)local uniqid = make_uniq(key)local count ---@type numberlocal base = opts and opts.base or 2local thre = opts and opts.thre or 3vim.keymap.set(mode, key, function()if vim.v.count > 0 thenreturn keyendcount = 1if callback thenreturn (callback() or '') .. uniqidendreturn key .. uniqidend, { expr = true })vim.keymap.set(mode, uniqid .. key, function()local speed = math.pow(base, math.floor(count / thre))count = count + 1if callback thenreturn speed .. (callback() or key) .. uniqidendreturn speed .. key .. uniqidend, { expr = true })vim.keymap.set(mode, uniqid, '<Nop>')endreturn M
local mysnip = {}local map = vim.keymap.setM = {}function M.set_snip(sn)mysnip[sn.abbr] = sn.snipendfunction M.setup_keymap()map('i', '<Tab>', function()local curpos = vim.api.nvim_win_get_cursor(0);if curpos[2] == 0 then return '<Tab>' endlocal newpos = { curpos[1], curpos[2] - 1 }vim.api.nvim_win_set_cursor(0, newpos)local cword = vim.fn.expand('<cword>')local snip = mysnip[cword]if snip thenreturn '<Esc>ciw<cmd>lua vim.snippet.expand"' .. snip:gsub('\n', '\\n') .. '"<CR>'endvim.api.nvim_win_set_cursor(0, curpos)if vim.snippet.active({ direction = 1 }) thenreturn '<cmd>lua vim.snippet.jump(1)'elsereturn '<Tab>'endend, { expr = true })map({ 'i', 's' }, '<S-Tab>', function()if vim.snippet.active({ direction = -1 }) thenvim.snippet.jump(-1)elsereturn '<S-Tab>'endend, { expr = true })endreturn M
local map = vim.keymap.setreturn {['folke/flash.nvim'] = {modname = 'flash',opts = {},callback = function()local flash = require 'flash'flash.toggle(true)end},['gbprod/substitute.nvim'] = {modname = 'substitute',callback = function()local sub = require 'substitute'map('n', 's', sub.operator)map('n', 'ss', sub.line)map('n', 'S', sub.eol)map('x', 's', sub.visual)end},['kylechui/nvim-surround'] = {modname = 'nvim-surround',opts = {},},['stevearc/oil.nvim'] = {modname = 'oil',opts = {columns = {'icon','permission','size','mtime'},},callback = function()map('n', '^o', require 'oil'.toggle_float)end,dependencies = { 'nvim-tree/nvim-web-devicons' }},['vim-jp/vimdoc-ja'] = {},['vim-jp/nvimdoc-ja'] = {},['altermo/ultimate-autopair.nvim'] = {modname = 'ultimate-autopair',opts = {fastwarp = {rmap = '<A-y>',rcmap = '<A-y>',},tabout = {multi = true,enable = true,hopout = true,},bs = {indent_ignore = true,},space2 = {enable = true,},extensions = {fly = {multiline = true,enable = true},}},},['utilyre/sentiment.nvim'] = {modname = 'sentiment',opts = {},callback = function()vim.g.loaded_matchparen = 1end},['nvim-tree/nvim-web-devicons'] = {},['niuiic/core.nvim'] = {},['niui/track.nvim'] = {modname = 'track',opts = {},callback = function()local track = require 'track'local markfile = vim.fn.stdpath('data') .. '/marks/mark.json'map('n', 'ma', track.add_mark)map('n', 'mA', track.add_flow)map('n', 'md', track.delete_mark)map('n', 'mD', track.delete_flow)map('n', 'mu', track.update_mark)map('n', 'mU', track.update_flow)map('n', 'ms', function() track.store_marks(markfile) end)track.restore_marks(markfile)end,dependencies = {'nvim-lua/plenary.nvim','nvim-telescope/telescope.nvim','niuiic/core.nvim',},},['nvim-lua/plenary.nvim'] = {},['nvim-telescope/telescope.nvim'] = {modname = 'telescope',opts = {},dependencies = {'nvim-lua/plenary.nvim',},},['hadronized/hop.nvim'] = {modname = 'hop',opts = {},callback = function()local hop = require 'hop'map({ 'n', 'v', 'o' }, 'gw', hop.hint_words)map({ 'n', 'v', 'o' }, 'ga', hop.hint_anywhere)end},['zbirenbaum/copilot.lua'] = {modname = 'copilot',opts = {suggestion = {enabled = true,auto_trigger = false,keymap = {accept = '<C-S-y>',next = '<C-S-n>',prev = '<C-S-p>',dismiss = '<C-S-e>',}},filetypes = {gitcommit = true}},callback = function()map('n', '^a', require 'copilot.suggestion'.toggle_auto_trigger)end},['nvim-treesitter/nvim-treesitter'] = {modname = 'nvim-treesitter',opts = { ensure_installed = 'all' },},['SmiteshP/nvim-navic'] = {modname = 'nvim-navic',opts = {lsp = { auto_attach = true },highlight = true}},['SmiteshP/nvim-navbuddy'] = {modname = 'nvim-navbuddy',opts = {lsp = { auto_attach = true },highlight = true},dependencies = {'SmiteshP/nvim-navic','MunifTanjim/nui.nvim'}},['MunifTanjim/nui.nvim'] = {modname = 'nui',},['andersevenrud/nvim_context_vt'] = {modname = 'nvim_context_vt',opts = {enabled = true,},},['sphamba/smear-cursor.nvim'] = {modname = 'smear_cursor',opts = {},},}
local au = vim.api.nvim_create_autocmdlocal map = vim.keymap.setlocal pluginOptions = require 'plugindata'---@param plugname stringfunction Load_plugin(plugname)if pluginOptions[plugname] thenlocal pluginpath = vim.env.HOME .. "/.local/state/nvim/plugins/"local modname = pluginOptions[plugname].modnamelocal opts = pluginOptions[plugname].optslocal callback = pluginOptions[plugname].callbacklocal dependencies = pluginOptions[plugname].dependenciesif dependencies thenfor _, dep in ipairs(dependencies) doLoad_plugin(dep)endendvim.opt.runtimepath:append(pluginpath .. plugname)if opts and modname then require(modname).setup(opts) endif callback then callback() endpluginOptions[plugname] = nilendendau({ 'UIEnter' }, {callback = function()Load_plugin 'folke/flash.nvim'Load_plugin 'gbprod/substitute.nvim'Load_plugin 'kylechui/nvim-surround'Load_plugin 'andersevenrud/nvim_context_vt'end})local function Load_cmdln()require 'command'require 'fzf'Load_plugin 'vim-jp/vimdoc-ja'Load_plugin 'vim-jp/nvimdoc-ja'Load_plugin 'stevearc/oil.nvim'endlocal cmdlnc = { ':', '/', '?' }for _, c in ipairs(cmdlnc) domap({ 'n', 'v', }, c, function()Load_cmdln()for _, cc in ipairs(cmdlnc) dovim.keymap.del({ 'n', 'v' }, cc)endvim.fn.feedkeys(c)end)endmap('n', '^a', function()Load_plugin 'zbirenbaum/copilot.lua'local sug = require 'copilot.suggestion'map('n', '^a', sug.toggle_auto_trigger)sug.toggle_auto_trigger()end)map('n', 'g/', function()Load_plugin 'nvim-telescope/telescope.nvim'local tb = require 'telescope.builtin'map('n', 'g/', tb.live_grep)tb.live_grep()end)map('n', 'm', function()Load_plugin 'niuiic/track.nvim'vim.keymap.del('n', 'm')vim.fn.feedkeys 'm'end)map('n', '<A-n>', function()Load_plugin 'SmiteshP/nvim-navbuddy'map('n', '<A-n>', vim.cmd.Navbuddy)vim.cmd.Navbuddy()end)au({ "InsertEnter", "CmdlineEnter" }, {once = true,callback = function()if vim.bo.filetype ~= 'markdown' then Load_plugin 'altermo/ultimate-autopair.nvim' endend})au({ "CursorMoved" }, {once = true,callback = function()Load_plugin 'mini.indentscope'Load_plugin 'utilyre/sentiment.nvim'Load_plugin 'hadronized/hop.nvim'-- if not vim.g.neovide and vim.env.TERM ~= 'xterm-kitty' then-- Load_Plugin 'sphamba/smear-cursor.nvim'-- endend})
local o = vim.opto.autoread = trueo.autowrite = trueo.complete = "w,i,d,kspell"o.completeopt = "menuone,preinsert,noselect,popup,fuzzy"o.cursorline = trueo.expandtab = trueo.foldmethod = "manual"o.fillchars = { stl = ' ', stlnc = ' ' }o.gdefault = trueo.guicursor = "n-v-c-sm:block,i-ci-ve:ver25-blinkwait1000-blinkoff300-blinkon1000,t:block-TermCursor"o.guifont = "PlemolJP35 Console NF:h8"o.helplang = "ja,en"o.hidden = trueo.ignorecase = trueo.hlsearch = falseo.incsearch = falseo.laststatus = 0o.mouse = ""o.number = falseo.paragraphs = ''o.path = ".,,,**"o.ruler = falseo.scrolloff = 10o.shada = ''o.shell = '/run/current-system/sw/bin/zsh'o.shiftwidth = 4o.showcmd = falseo.showmode = falseo.showtabline = 0o.signcolumn = "yes"o.smartcase = trueo.smartindent = trueo.statusline = ' 'o.tabstop = 4o.termguicolors = trueo.textwidth = 0o.timeout = falseo.undodir = vim.fn.stdpath("data") .. "/undo"o.undofile = trueo.wildmenu = trueo.wrap = falsevim.g.copilot_filetypes = { gitcommit = true, yaml = true, markdown = true }if vim.g.neovide thenvim.g.neovide_hide_mouse_when_typing = truevim.g.neovide_opacity = 1.0vim.g.transparency = 1.0vim.g.neovide_text_gamma = 0vim.g.neovide_text_contrast = 0.0vim.g.terminal_color_0 = '#171717' -- blackvim.g.terminal_color_1 = '#d81765' -- normal redvim.g.terminal_color_2 = '#97d01a' -- normal greenvim.g.terminal_color_3 = '#ffa800' -- normal yellowvim.g.terminal_color_4 = '#16b1fb' -- normal bluevim.g.terminal_color_5 = '#ff2491' -- normal magentavim.g.terminal_color_6 = '#0fdcb6' -- normal cyanvim.g.terminal_color_7 = '#ebebeb' -- light grayvim.g.terminal_color_8 = '#88757c' -- dark grayvim.g.terminal_color_9 = '#ff0000' -- bright redvim.g.terminal_color_10 = '#76b639' -- bright greenvim.g.terminal_color_11 = '#f7b125' -- bright yellowvim.g.terminal_color_12 = '#289cd5' -- bright bluevim.g.terminal_color_13 = '#ff2491' -- bright magentavim.g.terminal_color_14 = '#0a9b81' -- bright cyanvim.g.terminal_color_15 = '#f8f8f8' -- whiteend
local map = vim.keymap.setlocal submode = require 'submode'vim.g.mapleader = ' 'local function smart_gf()local fpath = vim.fn.expand('<cfile>')if fpath:sub(1, 8) == 'https://' thenvim.cmd.term('w3m ' .. fpath)vim.cmd.startinsert()elsevim.cmd.normal 'gF'endend-- consider indentationlocal function smart_i()if vim.fn.getline('.'):match("^ *$") thenvim.api.nvim_input '"_cc'else-- vim.api.nvim_input 'i' -- freezevim.cmd.startinsert()endendmap("n", "<BS>", "<C-b>")map("n", "<Delete>", "<C-f>")map('n', '<C-S-e>', '5<C-e>')map('n', '<C-S-y>', '5<C-y>')map('n', 'i', smart_i)map('n', 'S', 'c^')map("n", "Q", "ZZ", { noremap = true })map('n', 'G', '')map('n', 'GG', 'G')map("n", "gk", "25k")map("n", "gj", "25j")map('n', 'gf', smart_gf)map("n", "gb", vim.cmd.bnext)map('n', 'gB', vim.cmd.bprev)map('n', '^n', function() vim.o.number = not vim.o.number end)map('n', '^r', function() vim.o.relativenumber = not vim.o.relativenumber end)map('n', '^s', function() vim.o.spell = not vim.o.spell end)map('n', '<C-z>', ':w<CR><C-z>')map('n', 'zS', vim.show_pos)map({ 'n', 'v' }, 'q;', 'q:')map({ 'n', 'o', 'v' }, 'K', '5k')map({ 'n', 'o', 'v' }, 'J', '5j')map({ 'n', 'v' }, "x", '"_d')map({ 'n', 'v' }, 'X', '"_D')map({ "n", "v" }, "]]", "<C-]>")map({ "n", "v" }, "<Leader>y", [["+y]])map({ "n", "v" }, "<Leader>Y", [["+Y]])map({ "n", "v" }, "<Leader>d", [["_d]])map({ "n", "v", "o" }, "gl", "$l")map({ "n", "v", "o" }, "gh", "^")map({ "n", "v", "o" }, "]b", "])")map({ "n", "v", "o" }, "[b", "[(")map({ "n", "v", "o" }, "]B", "]}")map({ "n", "v", "o" }, "[B", "[{")map('i', '<Esc>', '<Right><Esc>')map('v', '<C-k>', ":m '<-2<CR>gv=gv")map('v', '<C-j>', ":m '>+1<CR>gv=gv")map('v', 'v', "<C-v>")map('v', 'aa', 'VggoG')map('o', '.', 'i>')map('o', 'iq', "i'")map('o', 'iQ', 'i"')map('o', 'aq', "a'")map('o', 'aQ', 'a"')map('o', 'i<Space>', 'iW')map('o', 'a<Space>', 'aW')map('t', '<C-\\>', '<C-\\><C-n>')submode.set_submode_keymap('n', 'g', {{ key = 't' },{ key = 'T' },{ key = 'e' },{ key = 'E' },{ key = 'J' },})submode.set_submode_keymap('n', 'd', {{ key = 'h' },{ key = 'l' },})submode.set_submode_keymap('n', '<C-w>', {{ key = '>' },{ key = '<' },{ key = '+' },{ key = '-' },{ key = 'h' },{ key = 'j' },{ key = 'k' },{ key = 'l' },})submode.set_submode_keymap('n', 'z', {{ key = '<Space>', run_when = { entering = '<C-f>', repeating = '<C-f>' } },{ key = 'b', run_when = { entering = '<C-b>', repeating = '<C-b>' } },})-- When pressed once, it does not move, but registers the word at the cursor position in the / register.submode.set_submode_keymap('n', '*', {{ key = '*', run_when = { entering = '#*', repeating = '*' } },})submode.set_submode_keymap('n', '#', {{ key = '#', run_when = { entering = '*#', repeating = '#' } },})submode.acceleration_key('n', 'j')submode.acceleration_key('n', 'k')submode.acceleration_key('n', 'h')submode.acceleration_key('n', 'l')local function safe_cabbrev(lhs, rhs)vim.cmd('cabbrev <expr> ' ..lhs .. ' (getcmdtype() ==# ":" && getcmdline() ==# "' .. lhs .. '") ? "' .. rhs .. '" : "' .. lhs .. '"')endsafe_cabbrev('r', 'lua require')safe_cabbrev('l', 'lua')vim.cmd 'cabbrev api vim.api'
M = {}vim.keymap.set('n', '=', vim.lsp.buf.format)vim.keymap.set('n', '^h', function()vim.lsp.inlay_hint.enable(not vim.lsp.inlay_hint.is_enabled())end)vim.keymap.set('n', 'gd', vim.lsp.buf.definition)vim.keymap.set('n', 'grh', vim.lsp.buf.hover)vim.diagnostic.config({ virtual_text = true })vim.lsp.document_color.enable(true, 0, { style = 'virtual' })function M.on_attach(client, bufnr)local chars = {}for i = 32, 126 do table.insert(chars, string.char(i)) endclient.server_capabilities.completionProvider.triggerCharacters = charsvim.lsp.completion.enable(true, client.id, bufnr, {autotrigger = true,convert = function(item)return { abbr = item.label:gsub('%b()', '') }end})endreturn M
local M = {}local function b2i(bool)return bool and 1 or 0endfunction M.goto_head()vim.fn.setpos('.', vim.fn.getpos("'["))local p = vim.api.nvim_win_get_cursor(0)local line = vim.api.nvim_get_current_line()local isfst = p[2] <= 1local isend = line:len() <= p[2]if isfst or isend thenlocal fst_nonspc = line:match("^%s*"):len()vim.api.nvim_win_set_cursor(0, { p[1] + b2i(isend), fst_nonspc })endendfunction M.goto_tail()vim.fn.setpos('.', vim.fn.getpos("']"))endvim.keymap.set({'n', 'v', 'o'}, '<Plug>(goto_txtobj-head)', '<cmd>se opfunc=v:lua.require("goto_txtobj").goto_head<CR>g@')vim.keymap.set({'n', 'v', 'o'}, '<Plug>(goto_txtobj-tail)', '<cmd>se opfunc=v:lua.require("goto_txtobj").goto_tail<CR>g@')vim.keymap.set({'n', 'v', 'o'}, 'gi', '<Plug>(goto_txtobj-head)i')vim.keymap.set({'n', 'v', 'o'}, 'ga', '<Plug>(goto_txtobj-head)a')vim.keymap.set({'n', 'v', 'o'}, 'Gi', '<Plug>(goto_txtobj-tail)i')vim.keymap.set({'n', 'v', 'o'}, 'Ga', '<Plug>(goto_txtobj-tail)a')return M
local map = vim.keymap.setlocal api = vim.apilocal function printBlameText()local currFile = vim.fn.expand('%')local line = api.nvim_win_get_cursor(0)local blame = vim.fn.system(string.format('git blame -c -L %d,%d %s', line[1], line[1], currFile))local hash = string.match(blame, '%S+')if hash == '00000000' thenText = 'Not Committed Yet'elselocal cmd = "git show " .. hash .. " --format='%an | %ar | %s' | head -n 1"Text = vim.fn.system(cmd):sub(1, -2)if Text:find("fatal") thenText = 'Not Committed Yet'endendprint(Text)endmap('n', '\\b', printBlameText)
---@param directory string---@param files table---@return tablelocal function get_files_recursive(directory, files)local curdir = vim.env.PWDlocal directory_files = vim.fn.readdir(directory)local ignored_dirs = { '.', '..', '.git', 'build', 'bin', 'plugins' }for _, file in ipairs(directory_files) dolocal full_path = directory .. '/' .. fileif vim.fn.isdirectory(full_path) ~= 0 and not vim.tbl_contains(ignored_dirs, file) thenget_files_recursive(full_path, files)elsetable.insert(files, full_path:sub(#curdir + 2))endendreturn filesendlocal file_cache = nilvim.api.nvim_create_user_command("F",function(opts)vim.cmd.tabnew(opts.fargs[1])end,{nargs = 1,bar = true,complete = function(trigger)if not file_cache thenfile_cache = get_files_recursive(vim.env.PWD, {})endif #trigger > 0 thenreturn vim.fn.matchfuzzy(file_cache, trigger)elsereturn file_cacheendend})
local au = vim.api.nvim_create_autocmdlocal snip = require 'snippet'--- evaluate code selected in visual mode---@param cmd string[]local function quickeval(cmd)local range = require 'utils'.get_visual_selection()local begin = range.startlocal last = range.lastbegin[1] = begin[1] - 1last[1] = last[1] - 1last[2] = last[2] + 1local content = vim.api.nvim_buf_get_text(0, begin[1], begin[2], last[1], last[2], {})local tmpfilename = '/tmp/nvim-ftplugin.' .. vim.fn.expand('%:e')local file = assert(io.open(tmpfilename, 'w'))for _, line in ipairs(content) dofile:write(line .. '\n')endfile:close()vim.cmd('vert term ' .. cmd .. tmpfilename)vim.cmd.startinsert()endau("FileType", {callback = function(ev)local ft = ev.matchlocal ok, ftp = pcall(require, 'ftplugin.' .. ft)if not ok then return endif ftp.lsp thenftp.lsp.on_attach = require 'lsp'.on_attachvim.loop.new_async(vim.schedule_wrap(function()vim.lsp.start(ftp.lsp)end)):send()endif ftp.quickeval_cmd thenvim.keymap.set('v', 'x', function()quickeval(ftp.quickeval_cmd)end)endif ftp.callback thenftp.callback()endif ftp.snippet thensnip.setup_keymap()for _, sn in ipairs(ftp.snippet) dosnip.set_snip(sn)endendend})
return {lsp = {name = 'zls-prime',cmd = { 'zls-prime' }},snippet = {{ abbr = 'i', snip = 'if ($1) {\n $2\n}\n$0' },{ abbr = 'f', snip = 'for ($1) |$2| {\n $3\n}\n$0' },{ abbr = 'w', snip = 'while ($1) {\n $2\n}\n$0' },{ abbr = 'fn', snip = 'fn $1($2) $3 {\n $4\n}\n$0' },{ abbr = 's', snip = 'switch ($1) {\n $2\n}\n$0' },{ abbr = 'p', snip = '$1 => $2,\n$0' },{ abbr = 't', snip = 'test "$1" {\n $2\n}' },},callback = function()vim.bo.expandtab = truevim.bo.shiftwidth = 4vim.bo.tabstop = 4end}
return {lsp = {name = 'yaml-ls',cmd = { 'yaml-language-server' }}}
return {lsp = {name = 'tinymist',cmd = { 'tinymist' }}}
return {lsp = {name = 'texlab',cmd = { 'texlab' }},snippet = {{abbr = '!',snip = [[\\documentclass[uplatex, dvipdfmx, a4paper]{ltjsarticle}\\usepackage{}\\title{$1}\\author{$2}\\date{}\\begin{document}\\maketitle\\newpage$0\\end{document}]]},{ abbr = 'b', snip = '\\\\begin{${1:env}}\n$2\n\\\\end{${1:env}}\n$0' },{ abbr = 's', snip = '\\\\section{$1}\n$0' },{ abbr = 'sb', snip = '\\\\subsection{$1}\n$0' },}}
return {quickeval_cmd = 'scheme',snippet = {{ abbr = 'i', snip = '(if ${1:cond}\n ${2:true}\n ${3:false})' },{ abbr = 'fn', snip = '(define $1 (lambda ($2)\n $3))' },},callback = function()vim.bo.expandtab = truevim.bo.shiftwidth = 2vim.bo.tabstop = 2end}
return {lsp = {name = 'rust-analyzer',cmd = { 'rust-analyzer' }},snippet = {{ abbr = 'i', snip = 'if $1 {\n\t$2\n}\n$0' },{ abbr = 'f', snip = 'for $1 in $2 {\n\t$3\n}\n$0' },{ abbr = 'w', snip = 'while $1 {\n\t$2\n}\n$0' },{ abbr = 'm', snip = 'match $1 {\n\t$2\n}\n$0' },{ abbr = 'p', snip = '$1 => $2,\n$0' },{ abbr = 'fn', snip = 'fn $1($2) {\n\t$3\n}\n$0' },{ abbr = 'fnr', snip = 'fn $1($2) -> $3 {\n\t$4\n}\n$0' },}}
return {lsp = {name = 'nu',cmd = { 'nu', '--lsp' }}}
return {lsp = {name = 'nixd',cmd = { 'nixd' }}}
return {quickeval_cmd = 'make -n -f ',snippet = {{ abbr = 'target', snip = '$1: $2\n\t$0' },{ abbr = 'p', snip = '.PHONY: $1' },}}
return {lsp = {name = 'lua-ls',cmd = { 'lua-language-server' },root_dir = vim.fn.stdpath('config')},snippet = {{ abbr = 'i', snip = 'if $1 then\n\t$2\nend\n$0' },{ abbr = 'f', snip = 'for $1 in $2 do\n\t$3\nend\n$0' },{ abbr = 'fn', snip = 'function $1($2)\n\t$3\nend\n$0' },{ abbr = 'l', snip = 'function($1)\n\t$2\nend\n$0' },}}
return {lsp = {name = 'java-language-server',cmd = { 'java-language-server' }}}
return {lsp = {name = 'gopls',cmd = { 'gopls' }}}
return {lsp = {name = 'fish-lsp',cmd = { 'fish-lsp', 'start' }}}
return require 'ftplugin.c'
return {lsp = {name = 'cmake-ls',cmd = { 'cmake-language-server' }}}
return {lsp = {name = 'clangd',cmd = { 'clangd' }},quickeval_cmd = 'clang-repl --summary-file=',snippet = {{ abbr = 'in', snip = '#include <$1.h>\n$0' },{ abbr = 'i', snip = 'if ($1) {\n $2\n}\n$0' },{ abbr = 'f', snip = 'for ($1; $2; $3) {\n $4\n}\n$0' },{ abbr = 's', snip = 'switch ($1) {\n $2\n}\n$0' },{ abbr = 'c', snip = 'case $1:\n $0' },{ abbr = 'w', snip = 'while ($1) {\n $2\n}\n$0' },{ abbr = 'd', snip = '#define $0' },{ abbr = 'p', snip = 'printf("$1", $2);\n$0' },{ abbr = 'call', snip = '$1($2);\n$0' },},callback = function()vim.bo.expandtab = truevim.bo.shiftwidth = 2vim.bo.tabstop = 2vim.cmd 'iabbrev and &&'vim.cmd 'iabbrev or \\|\\|'vim.cmd 'iabbrev not !'end}
return {lsp = {name = 'asm-lsp',cmd = { 'asm-lsp' }}}
local IM_cmd = "fcitx5-remote"local toggle_IM = { IM_cmd, "-t" }local was_IM_enabled = false -- was im enabled in previous insert mode---@return booleanlocal function get_IM_status()return vim.system({ IM_cmd }):wait().stdout:sub(1, 1) == '2'endlocal function toggle_IM_status()if was_IM_enabled then vim.system(toggle_IM) endendvim.api.nvim_create_autocmd("InsertEnter", { callback = toggle_IM_status })vim.api.nvim_create_autocmd("InsertLeave", {callback = function()was_IM_enabled = get_IM_status()toggle_IM_status()end})
local dmacro_key = '<C-T>'local clear_key = '<C-S-T>'local key_log = ''local prev_macro = nil---@param kl string---@return stringlocal function guess_macro(kl)for i = #kl / 2, #kl dolocal curspan = kl:sub(i)local srchspan = kl:sub(1, i - 1)local start, fin = srchspan:find(curspan, 1, true)if start and fin thenprev_macro = srchspan:sub(start)return srchspan:sub(fin + 1)endendreturn ''end---@param typed stringlocal function key_logger(_, typed)local readable_keycode = vim.fn.keytrans(typed)if readable_keycode == dmacro_key then return endkey_log = key_log .. readable_keycodeif #key_log > 100 thenkey_log = key_log:sub(#key_log - 100)endprev_macro = nilendvim.on_key(key_logger)vim.keymap.set({ 'i', 'n', 'v', 'o', 'c', 't' }, dmacro_key, function()vim.api.nvim_input(prev_macro or guess_macro(key_log))end)vim.keymap.set({ 'i', 'n', 'v', 'o', 'c', 't' }, clear_key, function()key_log = ''end)
local command = vim.api.nvim_create_user_commandcommand('M', function(opts)local args = table.concat(opts.fargs, ' ')vim.cmd.term('man ' .. args .. '| bat -p -l man')vim.cmd.startinsert()end, {nargs = '*',bar = true,})command('W', function(opts)vim.cmd.term('w3m ' .. opts.fargs[1])vim.cmd.startinsert()end, {nargs = 1,bar = true})command('H', function(opts)vim.cmd('tab h ' .. opts.fargs[1])require 'wrapwin'.open_wrapwin()end, {nargs = 1,complete = "help"})command('VS', function(_)require 'wrapwin'.open_wrapwin()end, {nargs = 0,})
local NITSC = {green = "#07d101",blue = "#00bfff",cream = "#edf0e0",bush = "#f584c6",red = "#f85624",brick = "#d8916e",navy = "#0047ab",gray = "#c0c0c0",greenyellow = "#adff2f",electriclime = "#ccff00",forest = "#228b22",cherry = "#ffb7c5",gold = "#ffd700",}---@param group string---@param opts tablelocal function hi(group, opts)vim.api.nvim_set_hl(0, group, opts)endhi("Normal", { bg = "None" })hi("NormalNC", { bg = "None" })hi("SignColumn", { bg = "None" })hi("CursorLine", { bg = "none" })hi("CursorLineNR", { fg = NITSC.red, bg = "none", bold = true })hi("CursorLineNC", { bg = "none" })hi("LineNr", { fg = NITSC.navy, bg = "none" })hi("StatusLine", { bg = "none" })hi("StatusLineNC", { bg = "none" })hi('LspInlayHint', { fg = 'DarkCyan' })hi("Visual", { bg = NITSC.blue })hi("PmenuSel", { fg = NITSC.gold, bg = NITSC.blue })hi("Search", { fg = NITSC.cream })hi("CurSearch", { fg = NITSC.forest, bg = NITSC.cream })hi("Substitute", { fg = NITSC.cream })hi("WinSeparator", { fg = NITSC.blue })hi("Boolean", { fg = NITSC.blue })hi("Comment", { fg = NITSC.gray })hi("Constant", { fg = NITSC.bush })hi("Statement", { fg = NITSC.green, bold = true })hi("KeyWord", { fg = NITSC.cream, bold = true })hi("PreProc", { fg = NITSC.brick })hi("Identifier", { fg = NITSC.greenyellow, bold = true })hi("Special", { fg = NITSC.blue })hi("String", { fg = NITSC.cherry })hi("Type", { fg = NITSC.blue, bold = true })hi("Number", { fg = NITSC.gold })hi("Todo", { fg = NITSC.navy, bg = NITSC.cream, bold = true })hi("Operator", { fg = NITSC.cream })hi("Function", { fg = NITSC.gold })hi("SpecialChar", { fg = NITSC.bush })hi("Delimiter", { fg = NITSC.cream })hi("@variable", { fg = NITSC.electriclime })hi("@variable.parameter", { italic = true })
local fuzpath = require 'fuzpath'local id = { name = 1, count = 2 }---@param tbl table<string, number>[]---@param val stringlocal function insert(tbl, val)table.insert(tbl, { val, 1 })end---@param rec1 table<string, number>---@param rec2 table<string, number>---@return booleanlocal function compare(rec1, rec2)return rec1[id.count] > rec2[id.count]end---@param name string---@return table<string, number>local function readfile(name)local ret = {}local fp = io.open(name, 'r')if not fp then return {} endfor line in fp:lines() dotable.insert(ret, vim.split(line, ','))endfp:close()table.sort(ret, compare)return retendlocal logfile = vim.fn.stdpath("data") .. '/cdtrack/dir.log'local dirs_table = readfile(logfile)---@param self table---@param n number---@return tablelocal function getcol(self, n)return vim.tbl_map(function(row)return row[n]end, self)endlocal cwd = vim.uv.cwd()if not vim.tbl_contains(getcol(dirs_table, id.name), cwd) theninsert(dirs_table, cwd)end---@param dirs table<string, number>[]---@param dir string---@return number?local function finddirrecord(dirs, dir)for _, rec in ipairs(dirs) doif rec[id.name] == dir thenreturn _endendend---@param dirs table<string, number>[]---@param dir stringlocal function update_record(dirs, dir)local index = finddirrecord(dirs, dir)if index thendirs[index][id.count] = dirs[index][id.count] + 1elseinsert(dirs, dir)endendlocal function normalize_path(dir)local isrel = dir:sub(1, 1) ~= '/'local base = isrel and vim.uv.cwd() .. '/' or ''return vim.fs.normalize(base .. dir)endlocal function rm_nonexistpath(pathtbl)local i = 1while i <= #pathtbl doif vim.uv.fs_stat(pathtbl[i]) theni = i + 1elsetable.remove(pathtbl, i)endendreturn pathtblend---@param trigger string---@return string[]local function findmatch(trigger)local matched = fuzpath.fuzpath(getcol(dirs_table, id.name), trigger)return rm_nonexistpath(matched)end---@param input stringlocal function cdtrack(input)local dir = normalize_path(input)if not vim.uv.fs_stat(dir) thenlocal candidates = findmatch(input)if #candidates == 0 thenprint('No such directory ' .. dir)returnendif #candidates == 1 thendir = candidates[1]elsevim.ui.select(candidates, { prompt = 'Select Directory:' }, function(choise)dir = choiseend)endendvim.cmd.cd(dir)endvim.api.nvim_create_user_command('Z', function(opts)cdtrack(opts.fargs[1])end, { nargs = 1, bar = true, complete = findmatch })vim.keymap.set('n', 'Zf', function()vim.ui.input({ prompt = 'cdtrack: ', complete = findmatch }, cdtrack)end)vim.api.nvim_create_autocmd('DirChanged', {callback = function()update_record(dirs_table, vim.uv.cwd())end})vim.api.nvim_create_autocmd('VimLeave', {callback = function()-- ensure directory existsif vim.fn.mkdir(vim.fn.fnamemodify(logfile, ':p:h'), 'p') ~= 1 then return endlocal buf = table.concat(vim.tbl_map(function(row)return table.concat(row, ',')end, dirs_table), '\n')local fp = io.open(logfile, 'w')if not fp then return end -- no one wants to see errors when leavingfp:write(buf)fp:close()end})
local au = vim.api.nvim_create_autocmdlocal map = vim.keymap.setfunction Treesitter_config()local prefix = vim.env.HOME .. '/.local/share/nvim/runtime/queries/'if #vim.o.filetype > 0 and vim.uv.fs_stat(prefix .. vim.o.filetype) thenvim.treesitter.start()endendau({ "UIEnter" }, {callback = function()require 'map'vim.cmd.rshada()if (vim.fn.argc() == 0) thenvim.cmd.term("nu")elsevim.cmd.normal 'g`"'endend})au({ "FileType" }, {callback = Treesitter_config})au({ 'CmdLineEnter' }, {callback = function()require 'cdtrack'end,once = true})au({ "TextYankPost" }, {callback = function()if vim.v.event.regname == '' thenvim.fn.setreg(vim.v.event.operator, vim.fn.getreg())endend})au({ "CmdWinEnter" }, {callback = function()map('n', '<ESC>', '<cmd>q!<CR>', { buffer = true })vim.bo.filetype = 'vim'end})au({ "BufWinEnter" }, {pattern = "COMMIT_EDITMSG",callback = function()for i, s in ipairs(vim.fn.systemlist('git diff --cached')) dovim.fn.append(i - 1, "# " .. s)endend})au({ 'BufWritePre' }, {callback = function()local dir = vim.fn.expand('<afile>:p:h')local f = io.open(dir, 'r')if f thenf:close()returnendvim.fn.mkdir(dir, 'p')end})au({ 'VimLeave' }, { command = 'wshada' })
-- overwrite superfluous pathsvim.opt.runtimepath = "~/.config/nvim,~/.local/share/nvim/runtime,~/.local/lib/nvim"local clibpath = vim.fn.stdpath('config') .. '/lib/?.so'package.cpath = package.cpath .. ';' .. clibpathrequire 'autocmd'require 'dmacro'require 'fcitx5'require 'ftplugin'require 'gitlens'require 'goto_txtobj'require 'opt'require 'plugin'require 'colorscheme'require 'ui'
{xdg.configFile."nvim".source = ./.;}
const std = @import("std");const String = []const u8;const List = []const []const u8;const plugin_path = "plugins";const plugins = [_]String{"MunifTanjim/nui.nvim","SmiteshP/nvim-navbuddy","SmiteshP/nvim-navic","altermo/ultimate-autopair.nvim","andersevenrud/nvim_context_vt","folke/flash.nvim","gbprod/substitute.nvim","hadronized/hop.nvim","kylechui/nvim-surround","niuiic/core.nvim","niuiic/track.nvim","nvim-lua/plenary.nvim","nvim-telescope/telescope.nvim","nvim-tree/nvim-web-devicons","nvim-treesitter/nvim-treesitter","stevearc/oil.nvim","utilyre/sentiment.nvim","vim-jp/nvimdoc-ja","vim-jp/vimdoc-ja","zbirenbaum/copilot.lua","sphamba/smear-cursor.nvim","neovim/neovim",};pub fn build(b: *std.Build) void {const cwd = b.build_root.path.?;const plugin_dir = b.fmt("{s}/plugins", .{ cwd });const plug_sync_step = b.step("plug-sync", "sync plugins");_ = .{ b, plugin_dir, plug_sync_step };}
{"$schema": "https://raw.githubusercontent.com/LuaLS/vscode-lua/master/setting/schema.json","runtime": {"version": "LuaJIT"},"workspace": {"library": ["runtime/lua","${3rd}/busted/library","${3rd}/luv/library"],"ignoreDir": ["test"],"checkThirdParty": "Disable"},"diagnostics": {"globals": ["vim"],"hint.enable": false,"disable": ["luadoc-miss-see-name"]}}
.gitignore.gptignoreplugins/*.git/**.jsonREADME.md**/*.so**/.cache/*archive/*
**/.gitlazy-lock.jsonspellpluginspackmarks**/.cache**/compile_commands.json**/*.soarchivellmfile.txtsrc/*/test.zig-cache
AlignAfterOpenBracket: BlockIndentAlignArrayOfStructures: RightAlignConsecutiveAssignments: falseAlignConsecutiveMacros: trueAlignConsecutiveShortCaseStatements:Enabled: trueAlignConsecutiveTableGenCondOperatorColons: trueAlignEscapedNewlines: DontAlignAlignOperands: AlignAfterOperatorAlignTrailingComments:Kind: AlwaysOverEmptyLines: 1AllowShortBlocksOnASingleLine: AlwaysAllowShortCaseExpressionOnASingleLine: trueAllowShortCaseLabelsOnASingleLine: falseAllowShortCompoundRequirementOnASingleLine: trueAllowShortEnumsOnASingleLine: trueAllowShortFunctionsOnASingleLine: NoneAllowShortIfStatementsOnASingleLine: AllIfsAndElseAllowShortLoopsOnASingleLine: trueAlwaysBreakBeforeMultilineStrings: falseBinPackArguments: false# BinPackLongBracedList: trueBraceWrapping:AfterCaseLabel: falseAfterClass: trueAfterEnum: falseAfterFunction: falseAfterNamespace: trueAfterStruct: falseAfterUnion: falseAfterExternBlock: trueBeforeElse: falseBeforeWhile: false# BraceWrappingAfterControlStatementStyle: NeverIndentBraces: falseBreakAdjacentStringLiterals: falseBreakAfterAttributes: LeaveBreakAfterJavaFieldAnnotations: trueBreakAfterReturnType: AutomaticBreakBeforeBinaryOperators: AllBreakBeforeBraces: AttachBreakBeforeInlineASMColon: OnlyMultilineBreakBeforeTernaryOperators: trueBreakFunctionDefinitionParameters: falseBreakStringLiterals: true# ColumnLimit: 80ContinuationIndentWidth: 2ForEachMacros: [test, bench]IncludeBlocks: MergeIndentCaseBlocks: falseIndentCaseLabels: falseIndentGotoLabels: falseIndentPPDirectives: BeforeHashIndentWidth: 2IndentWrappedFunctionNames: falseInsertNewlineAtEOF: trueIntegerLiteralSeparator:Binary: 0Decimal: 3DecimalMinDigits: 5Hex: 2HexMinDigits: 5KeepEmptyLines:AtEndOfFile: falseAtStartOfBlock: falseAtStartOfFile: falseLineEnding: LFMaxEmptyLinesToKeep: 1PPIndentWidth: 1PointerAlignment: RightQualifierAlignment: Right# ReflowComments: NeverRemoveBracesLLVM: false# RemoveEmptyLinesInUnwrappedLines: trueRemoveParentheses: LeaveRemoveSemicolon: falseSortIncludes: CaseSensitiveSpaceAfterCStyleCast: falseSpaceAfterLogicalNot: falseSpaceAroundPointerQualifiers: AfterSpaceBeforeAssignmentOperators: trueSpaceBeforeCaseColon: falseSpaceBeforeCpp11BracedList: falseSpaceBeforeParens: ControlStatementsSpaceBeforeSquareBrackets: falseSpaceInEmptyBlock: trueSpacesBeforeTrailingComments: 1SpacesInContainerLiterals: trueSpacesInLineCommentPrefix:Minimum: 1Maximum: -1# SpaceInParens: NeverSpacesInSquareBrackets: falseStatementMacros: [test_table]TabWidth: 2# UseTab: Never
util: {home.file.".config/niri/config.kdl".text = util.generators.toNiriConf {environment = {PATH = "/etc/profiles/per-user/sundo/bin:/run/current-system/sw/bin";};binds = {"Win+Shift+Slash".show-hotkey-overlay = {};"Win+W".spawn = [ "nu" "-c" "zsh -c (open $nu.history-path | lines | reverse | str join \"\\n\" | wofi)" ];"Win+Q".spawn = [ "nu" "-c" "zsh -c (^echo -e 'foot\\nneovide\\nvivaldi' | wofi)" ];"Win+Shift+E".quit = {};"Win+F".maximize-column = {};"Win+Ctrl+F".fullscreen-window = {};"Win+Shift+P".power-off-monitors = {};XF86AudioRaiseVolume.spawn = [ "wpctl" "set-volume" "@DEFAULT_AUDIO_SINK@" "0.05+" ];XF86AudioLowerVolume.spawn = [ "wpctl" "set-volume" "@DEFAULT_AUDIO_SINK@" "0.05-" ];"Win+H".focus-column-left = {};"Win+J".focus-workspace-down = {};"Win+K".focus-workspace-up = {};"Win+L".focus-column-right = {};"Win+Shift+L".focus-monitor-right = {};"Win+Shift+H".focus-monitor-left = {};"Win+Shift+J".move-workspace-to-monitor-left = {};"Win+Shift+K".move-workspace-to-monitor-right = {};"Win+1".focus-workspace = 1;"Win+2".focus-workspace = 2;"Win+3".focus-workspace = 3;"Win+4".focus-workspace = 4;"Win+5".focus-workspace = 5;"Win+6".focus-workspace = 6;"Win+7".focus-workspace = 7;"Win+8".focus-workspace = 8;"Win+9".focus-workspace = 9;"Win+Ctrl+1".move-column-to-workspace = 1;"Win+Ctrl+2".move-column-to-workspace = 2;"Win+Ctrl+3".move-column-to-workspace = 3;"Win+Ctrl+4".move-column-to-workspace = 4;"Win+Ctrl+5".move-column-to-workspace = 5;"Win+Ctrl+6".move-column-to-workspace = 6;"Win+Ctrl+7".move-column-to-workspace = 7;"Win+Ctrl+8".move-column-to-workspace = 8;"Win+Ctrl+9".move-column-to-workspace = 9;};cursor.hide-when-typing = {};input.touchpad.tap = {};output."eDP-1" = {mode = "2880x1800@60.001";background-color = "#000000";backdrop-color = "#000000";};output."HDMI-A-1" = {position = {x = 2880;y = 0;};};layout = {background-color = "black";always-center-single-column = {};center-focused-column = "on-overflow";gaps = 0;};window-rule = [{ focus-ring.off = {}; }{match._props.is-active = false;exclude._props.app-id = "vivaldi";opacity = 0.8;}];};}
pkgs: {i18n.inputMethod = {enable = true;type = "fcitx5";fcitx5 = {addons = with pkgs; [ fcitx5-skk catppuccin-fcitx5 ];waylandFrontend = true;settings.addons = {classicui.globalSection = letfont = "PlemolJP35 Console NF";font-size = "10";f = a: "${font} ${a} ${font-size}";in {Font = f "Text";MenuFont = f "Text";TrayFont = f "SemiBold";Theme = "catppuccin-mocha-blue";};skk.globalSection = {Rule = "azik-sticky-shift";PunctuationStyle = "Japanese";InitialInputMode = "Latin";CandidateChooseKey = "Qwerty Center Row (a,s,d,...)";};xim.globalSection = {UseOnTheSpot = "True";};};settings.inputMethod = {GroupOrder."0" = "skk";"Groups/0" = {Name = "Default";"Default Layout" = "us";DefaultIM = "skk";};"Groups/0/Items/0" = {Name = "skk";Layout = "";};};};};xdg.configFile."libskk/rules/azik-sticky-shift".source = ./azik-sticky-shift;}
{"include": [ "azik/default" ],"define": {"rom-kana": {";": null,"'": ["", "っ"],",": ["", ","],".": ["", "."],"-": ["", "-"],":": ["", ":"],"?": ["", "?"],"[": null,"]": null,"z,": ["", "、"],"z.": ["", "。"],"z-": ["", "ー"],"z:": ["", ":"],"z?": ["", "?"],"z[": ["", "「"],"z]": ["", "」"]}}}
{ "name": "azik-sticky-shift", "description": "azik sticky shift" }
{"include": [ "azik/latin" ],"define": {"keymap": {"C- ": "set-input-mode-hiragana"}}}
{"include": [ "azik/hiragana" ],"define": {"keymap": {";": "start-preedit-no-delete","C- ": "set-input-mode-latin"}}}
{ system, username }: { config, pkgs, lib, ... }:lethomeDirectory = "/home/${username}";util = import ./util pkgs;in{imports = [./git./shell./term./nvim(import ./niri util)(import ./wofi util)(import ./im pkgs)./pkgs.nix];home.username = username;home.homeDirectory = homeDirectory;home.stateVersion = "26.05";home.sessionPath = [ "$HOME/.local/bin" "$HOME/.zvm/bin" ];home.sessionVariables = {DISPLAY = ":0";NIXOS_OZONE_WL = "1";GTK_IM_MODULE = "fcitx";QT_IM_MODULE = "fcitx";};programs.bat.enable = true;programs.difftastic.enable = true;programs.neovim = {enable = true;defaultEditor = true;};programs.home-manager.enable = true;services.mako.enable = true;nixpkgs.config.allowUnfree = true;}
{programs.git = {enable = true;settings = {init.defaultBranch = "main";core.editor = "nvim";credential.helper = "store";safe.directory = "/etc/nixos";pull.rebase = false;user.name = "tolpi";user.email = "tolpifygau@gmail.com";alias = {b = "branch";cl = "clone";m = "send-email";p = "push";pl = "pull";s = "switch";};sendmail = {smtpEncryption = "tls";ssmptServer = "smtp.gmail.com";smtpUser = "tolpifygau@gmail.com";smtpServerPort = 587;};};};programs.lazygit.enable = true;programs.radicle = {enable = true;settings = {publicExplorer = "https://app.radicle.xyz/nodes/$host/$rid$path";node = {enable = true;alias = "tolpi";seedingPolicy.default = "block";};};};}
{ config, lib, pkgs, modulesPath, ... }:{imports =[ (modulesPath + "/installer/scan/not-detected.nix")];boot.initrd.availableKernelModules = [ "nvme" "xhci_pci" "ahci" "usb_storage" "sd_mod" ];boot.initrd.kernelModules = [ ];boot.kernelModules = [ "kvm-amd" ];boot.extraModulePackages = [ ];fileSystems."/" ={ device = "/dev/disk/by-uuid/834bdff1-0284-45ff-b27f-de2c2292f36a";fsType = "btrfs";};fileSystems."/boot" ={ device = "/dev/disk/by-uuid/243B-FF15";fsType = "vfat";options = [ "fmask=0022" "dmask=0022" ];};swapDevices = [{device = "/swap";size = 16 * 1024; # 16GB}];networking.useDHCP = lib.mkDefault true;nixpkgs.hostPlatform = lib.mkDefault "x86_64-linux";hardware.cpu.amd.updateMicrocode = lib.mkDefault config.hardware.enableRedistributableFirmware;hardware.graphics.enable = true;}
{description = "flake";inputs = {nixpkgs.url = "github:NixOS/nixpkgs/nixos-unstable";home-manager = {url = "github:nix-community/home-manager";inputs.nixpkgs.follows = "nixpkgs";};neovim-nightly.url = "github:nix-community/neovim-nightly-overlay";};outputs = { self, nixpkgs, home-manager, neovim-nightly, ... }:letsystem = "x86_64-linux";username = "sundo";overlays = [ neovim-nightly.overlays.default ];in {nixosConfigurations.nixos = nixpkgs.lib.nixosSystem {inherit system;modules = [(import ./configuration.nix { inherit system username; })home-manager.nixosModules.home-manager{home-manager.useGlobalPkgs = true;home-manager.useUserPackages = true;home-manager.users.${username}.imports = [(import ./home-manager/home.nix { inherit system username; })];}{nixpkgs.overlays = overlays;}];};};}
{"nodes": {"flake-parts": {"inputs": {"nixpkgs-lib": ["neovim-nightly","nixpkgs"]},"locked": {"lastModified": 1768135262,"narHash": "sha256-PVvu7OqHBGWN16zSi6tEmPwwHQ4rLPU9Plvs8/1TUBY=","owner": "hercules-ci","repo": "flake-parts","rev": "80daad04eddbbf5a4d883996a73f3f542fa437ac","type": "github"},"original": {"owner": "hercules-ci","repo": "flake-parts","type": "github"}},"home-manager": {"inputs": {"nixpkgs": ["nixpkgs"]},"locked": {"lastModified": 1768068402,"narHash": "sha256-bAXnnJZKJiF7Xr6eNW6+PhBf1lg2P1aFUO9+xgWkXfA=","owner": "nix-community","repo": "home-manager","rev": "8bc5473b6bc2b6e1529a9c4040411e1199c43b4c","type": "github"},"original": {"owner": "nix-community","repo": "home-manager","type": "github"}},"neovim-nightly": {"inputs": {"flake-parts": "flake-parts","neovim-src": "neovim-src","nixpkgs": "nixpkgs"},"locked": {"lastModified": 1768176302,"narHash": "sha256-x6hYwNeceQWaa80fJx7/RGdHyZiR76Gd/gTQxuLJkPs=","owner": "nix-community","repo": "neovim-nightly-overlay","rev": "e6786c2101ec7fc4b034084ca776eb4b7c0323cc","type": "github"},"original": {"owner": "nix-community","repo": "neovim-nightly-overlay","type": "github"}},"neovim-src": {"flake": false,"locked": {"lastModified": 1768172676,"narHash": "sha256-m/099KnfavqjmuOD4ASi0ChWXtNdvPRj8PD4RLiTqaE=","owner": "neovim","repo": "neovim","rev": "aed1f8c37730103a38f7248f22826892cd6f556e","type": "github"},"original": {"owner": "neovim","repo": "neovim","type": "github"}},"nixpkgs": {"locked": {"lastModified": 1768032153,"narHash": "sha256-6kD1MdY9fsE6FgSwdnx29hdH2UcBKs3/+JJleMShuJg=","owner": "NixOS","repo": "nixpkgs","rev": "3146c6aa9995e7351a398e17470e15305e6e18ff","type": "github"},"original": {"owner": "NixOS","ref": "nixpkgs-unstable","repo": "nixpkgs","type": "github"}},"nixpkgs_2": {"locked": {"lastModified": 1768127708,"narHash": "sha256-1Sm77VfZh3mU0F5OqKABNLWxOuDeHIlcFjsXeeiPazs=","owner": "NixOS","repo": "nixpkgs","rev": "ffbc9f8cbaacfb331b6017d5a5abb21a492c9a38","type": "github"},"original": {"owner": "NixOS","ref": "nixos-unstable","repo": "nixpkgs","type": "github"}},"root": {"inputs": {"home-manager": "home-manager","neovim-nightly": "neovim-nightly","nixpkgs": "nixpkgs_2"}}},"root": "root","version": 7}
{ system, username }: { config, lib, pkgs, ... }:{nixpkgs.config.allowUnfree = true;imports =[./hardware-configuration.nix./keyboard(import ./services pkgs)];boot.loader.systemd-boot.enable = true;boot.loader.efi.canTouchEfiVariables = true;boot.loader.timeout = 0;boot.kernelPackages = pkgs.linuxPackages_latest;networking.hostName = "nixos";networking.networkmanager.enable = true;time.timeZone = "Asia/Tokyo";i18n.defaultLocale = "en_US.UTF-8";console = {font = "ter-v32n";packages = with pkgs; [ terminus_font ];keyMap = "us";};fonts.packages = with pkgs; [ plemoljp-nf ];users.users.${username} = {isNormalUser = true;shell = pkgs.zsh;extraGroups = [ "dialout" "video" "wheel" ];hashedPassword = "$y$j9T$srZCpiaeafhJn6f4ZWKvV1$uhpACgzDkWf8I66j6fdfNFL3fdA0XmbWzv5/izWnjA1";};users.mutableUsers = false;environment.systemPackages = with pkgs; [bashvimvulkan-loadervulkan-toolswl-clipboardwgetxwayland-satellite];programs.gnupg.agent = {enable = true;enableSSHSupport = true;};programs.mtr.enable = true;programs.niri.enable = true;programs.nix-ld.enable = true;programs.zsh = {enable = true;enableCompletion = true;autosuggestions.enable = true;syntaxHighlighting.enable = true;shellAliases = {n = "nvim";};};services.kubo.enable = true;services.openssh.enable = true;services.tlp = {enable = true;settings = {AMDGPU_ABM_LEVEL_ON_BAT = 3;CPU_BOOST_ON_BAT = 0;CPU_ENERGY_PERF_POLICY_ON_BAT = "power";CPU_HWP_DYN_BOOST_ON_BAT = 0;NMI_WATCHDOG = 0;PLATFORM_PROFILE_ON_BAT = "low-power";RADEON_DPM_PERF_LEVEL_ON_BAT = "auto";RADEON_DPM_STATE_ON_BAT = "battery";RADEON_POWER_PROFILE_ON_BAT = "low";RESTORE_THRESHOLDS_ON_BAT = 0;TLP_DEFAULT_MODE = "BAT";};};services.udev.extraRules = letp = "${pkgs.coreutils}/bin";in ''ACTION=="add", SUBSYSTEM=="backlight", RUN+="${p}/chgrp video $sys$devpath/brightness", RUN+="${p}/chmod g+w $sys$devpath/brightness"'';# This option defines the first version of NixOS you have installed on this particular machine,# and is used to maintain compatibility with application data (e.g. databases) created on older NixOS versions.## Most users should NEVER change this value after the initial install, for any reason,# even if you've upgraded your system to a new NixOS release.## This value does NOT affect the Nixpkgs version your packages and OS are pulled from,# so changing it will NOT upgrade your system - see https://nixos.org/manual/nixos/stable/#sec-upgrading for how# to actually do that.## This value being lower than the current NixOS release does NOT mean your system is# out of date, out of support, or vulnerable.## Do NOT change this value unless you have manually inspected all the changes it would make to your configuration,# and migrated your data accordingly.## For more information, see `man configuration.nix` or https://nixos.org/manual/nixos/stable/options#opt-system.stateVersion .system.stateVersion = "25.05"; # Did you read the comment?# nix bug: pathsystemd.user.services.niri.wantedBy = [ "default.target" ];virtualisation.virtualbox.host.enable = true;boot.blacklistedKernelModules = [ "kvm" "kvm_amd" "kvm_intel" ];nix.settings.experimental-features = [ "nix-command" "flakes" ];}
.git.DS_Store