repositories / dotfiles

dotfiles

bugabingas dorkfiles

owned by bugabinga

Compare 392a2efaca068dd6044620e76a1973dcd295f530 → HEAD

Semantics: changes introduced since merge base. Base 489a2eedc669, head 9092ba81aa96.

Changed files (1172)

+133223 / −36976 text lines · all files grouped into 32 bars · 2 metadata-only · 30 binary (striped old/new sizes in 64-byte units, not churn) · lines and sizes scale separately · double caps mark values above 4096 lines

Diff layout

Remaining file details omitted: diff output limit reached.

.gitattributes

Added
new file mode 100644

+19 / −0 text lines

1* text=auto eol=lf
2
3# BEGIN bootstripper secrets
4MusicBrainz/Picard.ini -text filter=dotfiles-aes -diff merge=dotfiles-aes
5zed/settings.json -text filter=dotfiles-aes -diff merge=dotfiles-aes
6ssh/github.key -text filter=dotfiles-aes -diff merge=dotfiles-aes
7ssh/box.bugabinga.net.key -text filter=dotfiles-aes -diff merge=dotfiles-aes
8ssh/klops.key -text filter=dotfiles-aes -diff merge=dotfiles-aes
9ssh/tini.key -text filter=dotfiles-aes -diff merge=dotfiles-aes
10ssh/hetzner.key -text filter=dotfiles-aes -diff merge=dotfiles-aes
11ssh/aur.key -text filter=dotfiles-aes -diff merge=dotfiles-aes
12ssh/bugabinga.net.key -text filter=dotfiles-aes -diff merge=dotfiles-aes
13ssh/code.isp-insoft.de -text filter=dotfiles-aes -diff merge=dotfiles-aes
14gh/hosts.yml -text filter=dotfiles-aes -diff merge=dotfiles-aes
15aerc/accounts.conf -text filter=dotfiles-aes -diff merge=dotfiles-aes
16bash/secrets.bash -text filter=dotfiles-aes -diff merge=dotfiles-aes
17nushell/secrets.nu -text filter=dotfiles-aes -diff merge=dotfiles-aes
18pi/google-workspace/tokens/o.krylow%40isp-insoft.de.json -text filter=dotfiles-aes -diff merge=dotfiles-aes
19# END bootstripper secrets

.gitignore

Modified

+41 / −21 text lines

1**/__pycache__
2**/node_modules/
1/.idea
4*.bak
5*.synclock
6opencode/.dictator/cache/
7opencode/.output/
8opencode/.ruff_cache/
9opencode/logs/
10opencode/opencode-notifier-state.json
11.opencode/package-lock.json
3*.db
4*.sqlite
13nushell/zoxide.nu
14nushell/history.txt
15nushell/history.sqlite3*
16nushell/plugin.nu
17nushell/aliases.nu
6sync.log
7sync.log.*
19chawan/history.uri
9# vscode
10.vscode/*
11!.vscode/settings.json
12!.vscode/tasks.json
13!.vscode/launch.json
14!.vscode/extensions.json
15!.vscode/*.code-snippets
21# Yazi package manager installs plugin repos here; package.toml is source of truth.
22yazi/plugins/
17.history/
18*.vsix
24aerc/accounts.conf
20# direnv
21.direnv
26fonts/.uuid
23.private/
24.geheim/
28jj/repos/
26.venv/
27.envrc
29ssh/config.local
3030ssh/known_hosts
3131ssh/known_hosts.old
3636.aider.chat.history.md
3737.*syncthing.*
3838.trash/
40fonts/
42# Quickshell LSP scratch/config generated by qs.
43**/.qmlls.ini
44.superpowers/
46# Generated/local app state
47**/target/
48/pi/agent/install/
49pi/agent/bin
50pi/agent/install
51pi/agent/models-store.json
52pi/agent/crashes.json
53pi/agent/mcp-auth.json
54pi/agent/overkill-runs
55pi/agent/tmp
56pi/agent/bin
57yazi/plugins/
58MusicBrainz/.Picard.ini.synclock

.gitleaks.toml

Added
new file mode 100644

+10 / −0 text lines

1[extend]
2useDefault = true
3
4[[allowlists]]
5description = "Public Git signing-key fingerprint in historical host configuration"
6condition = "AND"
7targetRules = ["generic-api-key"]
8regexTarget = "line"
9paths = ['''^git/\.gitconfig\.EJ-PC-00363$''']
10regexes = ['''(?i)^\s*singingkey\s*=\s*[0-9a-f]{40}\s*$''']

.gitmodules

Deleted
deleted file mode 100644

+0 / −8 text lines

1[submodule "Notes"]
2 path = Notes
3 url = git@vcs.bugabinga.net:Notes.git
4 branch = trunk
5[submodule "pi-ext"]
6 path = pi-ext
7 url = git@vcs.bugabinga.net:pi-ext.git
8 branch = trunk

.miserc.toml

Added
new file mode 100644

+1 / −0 text lines

1auto_env = true

.pi/settings.json

Added
new file mode 100644

+5 / −0 text lines

1{
2 "skills": [
3 "../pi/agent/skills/nugu"
4 ]
5}

.secrets

Modified

+3 / −0 text lines

1010ssh/bugabinga.net.key
1111ssh/code.isp-insoft.de
1212gh/hosts.yml
13aerc/accounts.conf
14bash/secrets.bash
1315nushell/secrets.nu
16pi/google-workspace/tokens/o.krylow%40isp-insoft.de.json

.system/MISSION.md

Added
new file mode 100644

+3 / −0 text lines

1# MISSION
2
3Every machine I touch becomes mine after one clone: encrypted secrets, hostname manifests, one command to check.

.system/RULES.md

Added
new file mode 100644

+57 / −0 text lines

1# RULES
2
3## Standards
4
5Zero warnings, isolated evidence, reviewed output. Rigor over velocity claims.
6
7## Repository
8
9- Run repo commands from the dotfiles root; nested project commands run from their project root.
10- Check `git status --short` before edits; preserve unrelated dirty work.
11- Never run privileged, root, or elevated commands.
12- Do not delete noisy research, cache, or untracked files unless explicitly asked.
13- Prefer repo paths (`pi/agent/...`) over `$HOME` paths.
15## Secrets
17- `.secrets` is plaintext and lists repo-relative paths to encrypt; the `dotfiles-aes` Git filter does the encryption.
18- New secret flow:
19 1. edit `.secrets`
20 2. `java bootstripper.java check`
21 3. `git add .secrets .gitattributes`
22 4. `git check-attr -a -- path/to/secret`
23- Required attrs: `filter: dotfiles-aes`, `text: unset`, `diff: unset`.
24- A `.secrets` path must not match any ignore rule; `check` fails otherwise because `git add -A` would silently skip it.
25- Never `git add -A` new secret-looking files before that flow.
26- Private keys must not be staged as plaintext: `git cat-file -p :path/to/key | LC_ALL=C grep -q 'BEGIN .*PRIVATE KEY' && exit 1`.
27- Never print decrypted secrets; never ask for or expose `DOTFILES_AES_PASSPHRASE` unless I explicitly initiate setup.
28- Secret paths include `ssh/*.key`, `gh/hosts.yml`, `pi/agent/auth.json`, `nushell/secrets.nu`, app private settings.
30## Git
32- `rebase.autostash` and `merge.autostash` stay `false`; `mise run check` asserts it. Dirty worktree: commit first, or stash explicitly and pop it yourself.
33- The `dotfiles-aes` filter and `pre-commit`/`pre-push` hooks can abort Git midway; never pass `--no-verify`.
34- Commits and pushes require `gitleaks` on Git's `PATH`; missing Gitleaks blocks the Git operation, not the worktree.
36## Symlinks
38- Manifest pairs stay ordered and complete; blank line between pairs.
39- Managed symlinks never point outside HOME; no `/usr`, no `/etc`. Outside-HOME symlinks are errors: do not relink or delete them.
41## Repo commands
43Safe checks: `mise run check`, `mise run secrets-scan`.
44Heavy integration: `mise run ci` (needs host Podman).
45Crypto and hooks: `java bootstripper.java check | pre-commit | pre-push | install-hooks | init-crypto | setup-crypto`.
46HOME-mutating, only on explicit request: `mise run link`, `mise run clean`.
47`link` validates manifests, converges crypto idempotently, installs or repairs hooks, and creates symlinks; restoration refuses staged changes, deletions, symlinks, changed ciphertext, or mixed states.
49## Nested Systems
51- `quickshell/nuguland/.system/` governs the shell; its law applies there, not here.
52- Do not duplicate nested law in this System.
54## Docs
56- `.system/` cores and specs are agent authority; read RULES and the relevant spec before governed work.
57- READMEs are human overview; agent-only knowledge belongs in `.system/`.

.system/SYSTEM.md

Added
new file mode 100644

+24 / −0 text lines

1# SYSTEM
2
3## Repo
4
5Dorkfiles. One Git repository, several machines.
6Host bootstrap assumes Git and mise; mise supplies Java; other tools come from the system package manager.
7`bootstripper.java` converges the Git filter, attributes, and hooks that keep secrets encrypted and commits gated.
8
9Symlink manifests are `repo/path` + `~/target/path` pairs; the hostname chooses `<host>.symlinks`.
11Nested Systems, each governing its own subtree:
13- `quickshell/nuguland/` — desktop shell, own System with `NL` IDs.
14- `neovim/` — own subtree; not yet initialized.
16Also in this repo:
18- `pi/agent/` — Pi settings, models, modes, skills; extension sources under `pi-ext/extensions/`.
19- Nugu palettes and themes — load the `nugu` skill before palette work.
21## Docs hierarchy
23This System and RULES are repo authority below nested Systems.
24READMEs are human overview and carry no binding rules.

.system/board.json

Added
new file mode 100644

+4 / −0 text lines

1{
2 "schemaVersion": 0,
3 "items": {}
4}

.system/config.json

Added
new file mode 100644

+5 / −0 text lines

1{
2 "prefix": "DORK",
3 "schemaVersion": 0,
4 "title": "dotfiles"
5}

AGENTS.md

Deleted
deleted file mode 100644

+0 / −36 text lines

1# Dotfiles
2
3Dorkfiles repo.
4Preserve unrelated dirty work.
5Never print decrypted secrets.
6
7## Secrets
8
9`.secrets` is plaintext.
10It lists repo-relative paths to encrypt.
12Encryption comes from local Git filter `dotfiles-aes` via `.git/info/attributes`.
13`bootstripper` generates that file from `.secrets`.
15For a new secret:
17```sh
18$EDITOR .secrets
19java bootstripper.java check
20git check-attr -a -- path/to/secret
21```
23Required attrs:
25```text
26filter: dotfiles-aes
27text: unset
28diff: unset
29```
31Do not `git add -A` new secret-looking files before this.
32For private keys, verify staged content is not plaintext:
34```sh
35git cat-file -p :path/to/key | LC_ALL=C grep -q 'BEGIN .*PRIVATE KEY' && exit 1
36```

ArchLinux-dev.symlinks

Added
new file mode 100644

+89 / −0 text lines

1pi
2~/.pi
3
4dprint/dprint.jsonc
5~/.config/dprint/dprint.jsonc
6
7git/gitconfig
8~/.config/git/config
9
10git/gitattributes
11~/.config/git/gitattributes
13git/allowed_signers
14~/.config/git/allowed_signers
16git/gitconfig.isp
17~/.config/git/.gitconfig.include
19gh
20~/.config/gh
22cargo/config.toml
23~/.cargo/config.toml
25bat/config
26~/.config/bat/config
28bash/bash_profile
29~/.bash_profile
31bash/bashrc
32~/.bashrc
34bash
35~/.config/bash
37tmux
38~/.config/tmux
40nushell
41~/.config/nushell
43topgrade/topgrade.toml
44~/.config/topgrade.toml
46topgrade/wsl.toml
47~/.config/topgrade.d/wsl.toml
49paru/paru.conf
50~/.config/paru/paru.conf
52ssh
53~/.ssh
55neovim
56~/.config/nvim
58zed
59~/.config/zed
61ghostty
62~/.config/ghostty
64jj
65~/.config/jj
67glow
68~/.config/glow
70mise
71~/.config/mise
73claude/settings.json
74~/.claude/settings.json
76claude/statusline.js
77~/.claude/statusline.js
79claude/cc-statusline-hook.js
80~/.claude/cc-statusline-hook.js
82claude/CLAUDE.md
83~/.claude/CLAUDE.md
85claude/RTK.md
86~/.claude/RTK.md
88codex/config.toml
89~/.codex/config.toml

MangoHud/MangoHud.conf

Modified

+6 / −24 text lines

77font_size=24
88text_color=FFFFFF
99position=top-left
10toggle_hud=Shift_R+F12
11pci_dev=0:2d:00.0
10preset=1,2,3
11toggle_preset=Shift_L+F10
12toggle_hud=Shift_L+F12
13pci_dev=0000:2d:00.0
1214table_columns=3
1315gpu_text=GPU
14gpu_stats
1516gpu_load_change
1617gpu_load_value=50,90
1718gpu_load_color=FFFFFF,FFAA7F,CC0000
18vram
1919vram_color=AD64C1
20gpu_core_clock
21gpu_mem_clock
22gpu_temp
23gpu_power
2420gpu_color=2E9762
2521cpu_text=CPU
26cpu_stats
2722cpu_load_change
2823cpu_load_value=50,90
2924cpu_load_color=FFFFFF,FFAA7F,CC0000
30cpu_mhz
31cpu_temp
32cpu_power
3325cpu_color=2E97CB
34ram
3526ram_color=C26693
36battery
37battery_color=00FF00
38fps
39frame_timing
4027frametime_color=00FF00
41engine_version
4228engine_color=EB5B5B
43fps_limit_method=late
44toggle_fps_limit=Shift_L+F1
4529fps_limit=0
46#offset=0
47vsync=4
4830fps_color_change
4931fps_color=B22222,FDFD09,39F900
5032fps_value=30,60
51output_folder=/home/oli
52log_duration=30
33output_folder=/home/me/.local/state/MangoHud
34log_duration=60
5335log_interval=100
5436toggle_logging=Shift_L+F2
5537blacklist=zenity,protonplus,lsfg-vk-ui,bazzar,gnome-calculator,pamac-manager,lact,ghb,bitwig-studio,ptyxis,yumex

MangoHud/presets.conf

Added
new file mode 100644

+43 / −0 text lines

1# Left Shift + F10 cycles Minimal -> Performance -> Diagnostic.
2
3# Minimal: FPS and numeric frame time.
4[preset 1]
5legacy_layout=0
6cpu_stats=0
7gpu_stats=0
8fps
9frametime
11# Performance: load, temperatures, memory and frame pacing.
12[preset 2]
13legacy_layout=0
14gpu_stats
15gpu_temp
16vram
17cpu_stats
18cpu_temp
19ram
20procmem
21fps
22frametime
23frame_timing
25# Diagnostic: Performance plus clocks, power and per-core load.
26[preset 3]
27legacy_layout=0
28gpu_stats
29gpu_temp
30gpu_core_clock
31gpu_mem_clock
32gpu_power
33vram
34cpu_stats
35cpu_temp
36cpu_mhz
37core_load
38ram
39procmem
40fps
41frametime
42frame_timing
43engine_version

NB-00718.symlinks

Modified

+107 / −71 text lines

1forgejo-cli
2~/AppData/Roaming/Cyborus/forgejo-cli/config
3
4Notes
5~/Notes
6
7pi
8~/.pi
9
10wezterm
11~/.config/wezterm
12
13neovim
14~/AppData/Local/nvim
15
16nushell
17~/AppData/Roaming/nushell
18
19bat/config
20~/AppData/Roaming/bat/config
21
22bottom
23~/AppData/Roaming/bottom
24
25git/gitconfig
26~/.config/git/config
27
28git/gitattributes
29~/.config/git/gitattributes
30
31git/gitconfig.isp
32~/.config/git/.gitconfig.include
33
34gh
35~/AppData/Roaming/GitHub CLI
36
37cargo/config.toml
38~/.cargo/config.toml
39
40neovide
41~/AppData/Roaming/neovide
42
43zed
44~/AppData/Roaming/zed
45
46helix
47~/AppData/Roaming/helix
48
49jj/config.toml
50~/AppData/Roaming/jj/config.toml
51
52glow/glow.yml
53~/AppData/Local/glow/Config/glow.yml
54
55mise
56~/.config/mise
57
58ssh
59~/.ssh
60
61topgrade/topgrade.toml
62~/AppData/Roaming/topgrade.toml
63
64topgrade/win32.toml
65~/AppData/Roaming/topgrade.d/win32.toml
66
67mpv
68~/AppData/Roaming/mpv
69
70rbw
71~/AppData/Roaming/rbw
1forgejo-cli
2~/AppData/Roaming/Cyborus/forgejo-cli/config
3
4claude/settings.json
5~/.claude/settings.json
6
7claude/cc-statusline-hook.js
8~/.claude/cc-statusline-hook.js
9
10claude/statusline.js
11~/.claude/statusline.js
13claude/CLAUDE.md
14~/.claude/CLAUDE.md
16claude/RTK.md
17~/.claude/RTK.md
19codex/config.toml
20~/.codex/config.toml
22pi
23~/.pi
25dprint/dprint.jsonc
26~/AppData/Roaming/dprint/dprint.jsonc
28wezterm
29~/.config/wezterm
31neovim
32~/AppData/Local/nvim
34nushell
35~/AppData/Roaming/nushell
37bat/config
38~/AppData/Roaming/bat/config
40bottom
41~/AppData/Roaming/bottom
43git/gitconfig
44~/.config/git/config
46git/gitattributes
47~/.config/git/gitattributes
49git/allowed_signers
50~/.config/git/allowed_signers
52git/gitconfig.isp
53~/.config/git/.gitconfig.include
55gh
56~/AppData/Roaming/GitHub CLI
58cargo/config.toml
59~/.cargo/config.toml
61neovide
62~/AppData/Roaming/neovide
64zed
65~/AppData/Roaming/zed
67jj/config.toml
68~/AppData/Roaming/jj/config.toml
70glow/glow.yml
71~/AppData/Local/glow/Config/glow.yml
73yazi/windows/yazi.toml
74~/AppData/Roaming/yazi/config/yazi.toml
76yazi/keymap.toml
77~/AppData/Roaming/yazi/config/keymap.toml
79yazi/init.lua
80~/AppData/Roaming/yazi/config/init.lua
82yazi/theme.toml
83~/AppData/Roaming/yazi/config/theme.toml
85yazi/package.toml
86~/AppData/Roaming/yazi/config/package.toml
88yazi/flavors
89~/AppData/Roaming/yazi/config/flavors
91mise
92~/.config/mise
94ssh
95~/.ssh
97topgrade/topgrade.toml
98~/AppData/Roaming/topgrade.toml
100topgrade/win32.toml
101~/AppData/Roaming/topgrade.d/win32.toml
103mpv
104~/AppData/Roaming/mpv
106rbw
107~/AppData/Roaming/rbw

Notes

Deleted
deleted file mode 160000

Link change (old → new): 58ade5460152050b8dc410fddc9567c6199c390a → absent.

README.md

Modified

+10 / −24 text lines

88init.lua
99: main entry point
10\
1111lua/std
1212: standard lib. can only depend on itself and neovim apis.
13\
1414lua/bugabinga
1515: config modules. in aggregation, defines all of the config. can depend on itself, std and plugins.
16\
1717lua/bugabinga/plugins
1818: third party plugins and their config glue integrating it into the config.
19\
2020colors/nugu
2121: color theme
22\
2323ftplugin
2424: file type specific config
26----------
26---
2828# ai poem
3535~ Shirou Emiya
37---------
37---
3939# todo
41* add fonts to dotfiles (how to keep size under control?)
42* write plugin to parse lsp settings locally and apply them
43* is there a use case for a plugin that parses local plugin configuration overrides?
44* kill custom lsp stuff in favor of lspconfig and try neoconf + nvim-java
45* does status bar fail to display if lsp fails to load?
46* pandoc with lua filters for diagrams for generating documents and previewing --> https://github.com/tex/vimpreviewpandoc
47* use gen.ai to generate docs
48* learn marks and refactor mark.lua
49* use ltex-ls for markdown, code comments and commit messages
50* create a floating window that shows plugins, that have commands, as reminder
51* setup DAP
52* add nu-check to nvim-lint
53* create facade over vim.api.nvim_create_user_command
54* create skeleton-plugin for default file content based on file type
55* add support for Java multi line string in autopairs
56* nvim spell for camel case words
41- learn marks and refactor mark.lua
42- add support for Java multi line string in autopairs
43- nvim spell for camel case words

TODO.md

Added
new file mode 100644

+1 / −0 text lines

1- can we run on mise run link: git submodule update --init; switch to trunk? fast idempotetn?

aerc/accounts.conf

Added
new file mode 100644

Binary size (old → new): 0 → 886 bytes.

aerc/aerc.conf

Modified

+746 / −751 text lines

1#
2# aerc main configuration
3
4[general]
5#
6# Used as a default path for save operations if no other path is specified.
7# ~ is expanded to the current user home dir.
8#
9default-save-path=~/Downloads
10
11# If set to "gpg", aerc will use system gpg binary and keystore for all crypto
12# operations. If set to "internal", the internal openpgp keyring will be used.
13# If set to "auto", the system gpg will be preferred unless the internal
14# keyring already exists, in which case the latter will be used.
15#
16# Default: auto
17#pgp-provider=auto
18
19# By default, the file permissions of accounts.conf must be restrictive and
20# only allow reading by the file owner (0600). Set this option to true to
21# ignore this permission check. Use this with care as it may expose your
22# credentials.
23#
24# Default: false
25#unsafe-accounts-conf=false
26
27# Output log messages to specified file. A path starting with ~/ is expanded to
28# the user home dir. When redirecting aerc's output to a file using > shell
29# redirection, this setting is ignored and log messages are printed to stdout.
30#
31#log-file=
32
33# Only log messages above the specified level to log-file. Supported levels
34# are: trace, debug, info, warn and error. When redirecting aerc's output to
35# a file using > shell redirection, this setting is ignored and the log level
36# is forced to trace.
37#
38# Default: info
39#log-level=info
40
41# Set the $TERM environment variable used for the embedded terminal.
42#
43# Default: xterm-256color
44#term=xterm-256color
45
46# Display OSC8 strings in the embedded terminal
47#
48# Default: false
49enable-osc8=true
50
51# Default shell command to use for :menu. This will be executed with sh -c and
52# will run in an popover dialog.
53#
54# Any occurrence of %f will be replaced by a temporary file path where the
55# command is expected to write output lines to be consumed by :menu. Otherwise,
56# the lines will be read from the command's standard output.
57#
58# Examples:
59# default-menu-cmd=fzf
60# default-menu-cmd=fzf --multi
61# default-menu-cmd=dmenu -l 20
62# default-menu-cmd=ranger --choosefiles=%f
63#
64default-menu-cmd=yazi --chooser-file %f
65
66[ui]
67#
68# Describes the format for each row in a mailbox view. This is a comma
69# separated list of column names with an optional align and width suffix. After
70# the column name, one of the '<' (left), ':' (center) or '>' (right) alignment
71# characters can be added (by default, left) followed by an optional width
72# specifier. The width is either an integer representing a fixed number of
73# characters, or a percentage between 1% and 99% representing a fraction of the
74# terminal width. It can also be one of the '*' (auto) or '=' (fit) special
75# width specifiers. Auto width columns will be equally attributed the remaining
76# terminal width. Fit width columns take the width of their contents. If no
77# width specifier is set, '*' is used by default.
78#
79# Default: date<20,name<17,flags>4,subject<*
80index-columns=date<6,flags>4,name<24,subject<*
81
82#
83# Each name in index-columns must have a corresponding column-$name setting.
84# All column-$name settings accept golang text/template syntax. See
85# aerc-templates(7) for available template attributes and functions.
86#
87# Here are some examples to show the To field instead of the From field for
88# an email (modifying column-name):
89#
90# 1. a generic one
91# column-name={{ .Peer | names | join ", " }}
92# 2. based upon the selected folder
93# column-name={{if match .Folder "^(Gesendet|Sent)$"}}{{index (.To | names) 0}}{{else}}{{index (.From | names) 0}}{{end}}
94#
95# Default settings
96#column-date={{.DateAutoFormat .Date.Local}}
97#column-name={{index (.From | names) 0}}
98#column-flags={{.Flags | join ""}}
99#column-subject={{.ThreadPrefix}}{{if .ThreadFolded}}{{printf "{%d}" .ThreadCount}}{{end}}{{.Subject}}
100
101#
102# String separator inserted between columns. When the column width specifier is
103# an exact number of characters, the separator is added to it (i.e. the exact
104# width will be fully available for the column contents).
105#
106# Default: " "
107#column-separator=" "
108
109#
110# See time.Time#Format at https://godoc.org/time#Time.Format
111#
112# Default: 2006-01-02 03:04 PM (ISO 8601 + 12 hour time)
113#timestamp-format=2006-01-02 03:04 PM
114timestamp-format=02.01.2006 03:04h
115# FIXME it would be nice to have different formats for the viewer
116
117#
118# Index-only time format for messages that were received/sent today.
119# If this is not specified, timestamp-format is used instead.
120#
121this-day-time-format=03:04h
122
123#
124# Index-only time format for messages that were received/sent within the last
125# 7 days. If this is not specified, timestamp-format is used instead.
126#
127this-week-time-format=02.01
128
129#
130# Index-only time format for messages that were received/sent this year.
131# If this is not specified, timestamp-format is used instead.
132#
133this-year-time-format=01.2006
134
135#
136# Width of the sidebar, including the border.
137#
138# Default: 20
139sidebar-width=24
140
141#
142# Message to display when viewing an empty folder.
143#
144# Default: (no messages)
145#empty-message=(no messages)
146
147# Message to display when no folders exists or are all filtered
148#
149# Default: (no folders)
150#empty-dirlist=(no folders)
151#
152# Value to set {{.Subject}} template to when subject is empty.
153#
154# Default: (no subject)
155#empty-subject=(no subject)
156
157# Enable mouse events in the ui, e.g. clicking and scrolling with the mousewheel
158#
159# Default: false
160mouse-enabled=true
161
162#
163# Ring the bell when new messages are received
164#
165# Default: true
166#new-message-bell=true
167
168#
169# Template to use for Account tab titles
170#
171# Default: {{.Account}}
172#tab-title-account={{.Account}}
173
174# Marker to show before a pinned tab's name.
175#
176# Default: `
177#pinned-tab-marker='`'
178
179# Template for the left side of the directory list.
180# See aerc-templates(7) for all available fields and functions.
181#
182# Default: {{.Folder}}
183dirlist-left={{.Folder}}{{if .Recent}} 󰺻{{end}}
184
185# Template for the right side of the directory list.
186# See aerc-templates(7) for all available fields and functions.
187#
188# Default: {{if .Unread}}{{humanReadable .Unread}}/{{end}}{{if .Exists}}{{humanReadable .Exists}}{{end}}
189#dirlist-right={{if .Unread}}{{humanReadable .Unread}}/{{end}}{{if .Exists}}{{humanReadable .Exists}}{{end}}
190
191# Delay after which the messages are actually listed when entering a directory.
192# This avoids loading messages when skipping over folders and makes the UI more
193# responsive. If you do not want that, set it to 0s.
194#
195# Default: 200ms
196dirlist-delay=100ms
197
198# Display the directory list as a foldable tree that allows to collapse and
199# expand the folders.
200#
201# Default: false
202dirlist-tree=true
203
204# If dirlist-tree is enabled, set level at which folders are collapsed by
205# default. Set to 0 to disable.
206#
207# Default: 0
208dirlist-collapse=3
209
210# List of space-separated criteria to sort the messages by, see *sort*
211# command in *aerc*(1) for reference. Prefixing a criterion with "-r "
212# reverses that criterion.
213#
214# Example: "from -r date"
215#
216sort=-r date from
217
218# Moves to next message when the current message is deleted
219#
220# Default: true
221#next-message-on-delete=true
222
223# Automatically set the "seen" flag when a message is opened in the message
224# viewer.
225#
226# Default: true
227#auto-mark-read=true
228
229# The directories where the stylesets are stored. It takes a colon-separated
230# list of directories. If this is unset or if a styleset cannot be found, the
231# following paths will be used as a fallback in that order:
232#
233# ${XDG_CONFIG_HOME:-~/.config}/aerc/stylesets
234# ${XDG_DATA_HOME:-~/.local/share}/aerc/stylesets
235# /usr/local/share/aerc/stylesets
236# /usr/share/aerc/stylesets
237#
238#stylesets-dirs=
239
240# Uncomment to use box-drawing characters for vertical and horizontal borders.
241#
242# Default: " "
243border-char-vertical="│"
244border-char-horizontal="─"
245
246# Sets the styleset to use for the aerc ui elements.
247#
248# Default: default
249styleset-name=nugu-dark
250
251# Activates fuzzy search in commands and their arguments: the typed string is
252# searched in the command or option in any position, and need not be
253# consecutive characters in the command or option.
254#
255# Default: false
256fuzzy-complete=true
257
258# How long to wait after the last input before auto-completion is triggered.
259#
260# Default: 250ms
261#completion-delay=250ms
262
263# The minimum required characters to allow auto-completion to be triggered after
264# completion-delay.
265#
266# Setting this to "manual" disables automatic completion, leaving only the
267# manually triggered completion with the $complete key (see aerc-binds(5) for
268# more details).
269#
270# Default: 1
271#completion-min-chars=1
272
273#
274# Global switch for completion popovers
275#
276# Default: true
277#completion-popovers=true
278
279# Uncomment to use UTF-8 symbols to indicate PGP status of messages
280#
281# Default: ASCII
282icon-unencrypted=󰇷
283icon-encrypted=✔
284icon-signed=✔
285icon-signed-encrypted=✔
286icon-unknown=✘
287icon-invalid=⚠
288
289# Reverses the order of the message list. By default, the message list is
290# ordered with the newest (highest UID) message on top. Reversing the order
291# will put the oldest (lowest UID) message on top. This can be useful in cases
292# where the backend does not support sorting.
293#
294# Default: false
295#reverse-msglist-order = false
296
297# Reverse display of the mesage threads. Default order is the the intial
298# message is on the top with all the replies being displayed below. The
299# reverse option will put the initial message at the bottom with the
300# replies on top.
301#
302# Default: false
303#reverse-thread-order=false
304
305# Sort the thread siblings according to the sort criteria for the messages. If
306# sort-thread-siblings is false, the thread siblings will be sorted based on
307# the message UID in ascending order. This option is only applicable for
308# client-side threading with a backend that enables sorting. Note that there's
309# a performance impact when sorting is activated.
310#
311# Default: false
312#sort-thread-siblings=false
313
314[ui:account=oliver]
315#
316# Enable a threaded view of messages. If this is not supported by the backend
317# (IMAP server or notmuch), threads will be built by the client.
318#
319# Default: false
320threading-enabled=true
321
322# Force client-side thread building
323#
324# Default: false
325#force-client-threads=false
326
327# Show thread context enables messages which do not match the current query (or
328# belong to the current mailbox) to be shown for context. These messages can be
329# styled separately using "msglist_thread_context" in a styleset. This feature
330# is not supported by all backends
331#
332# Default: false
333#show-thread-context=false
334
335# Debounce client-side thread building
336#
337# Default: 50ms
338#client-threads-delay=50ms
339
340#
341# Thread prefix customization:
342
343#
344# Customize the thread prefix appearance by selecting the arrow head.
345#
346# Default: ">"
347#thread-prefix-tip = ">"
348
349#
350# Customize the thread prefix appearance by selecting the arrow indentation.
351#
352# Default: " "
353#thread-prefix-indent = " "
354
355#
356# Customize the thread prefix appearance by selecting the vertical extension of
357# the arrow.
358#
359# Default: "│"
360#thread-prefix-stem = "│"
361
362#
363# Customize the thread prefix appearance by selecting the horizontal extension
364# of the arrow.
365#
366# Default: ""
367#thread-prefix-limb = ""
368
369#
370# Customize the thread prefix appearance by selecting the folded thread
371# indicator.
372#
373# Default: ""
374#thread-prefix-folded = ""
375
376#
377# Customize the thread prefix appearance by selecting the unfolded thread
378# indicator.
379#
380# Default: ""
381#thread-prefix-unfolded = ""
382
383#
384# Customize the thread prefix appearance by selecting the first child connector.
385#
386# Default: ""
387#thread-prefix-first-child = ""
388
389#
390# Customize the thread prefix appearance by selecting the connector used if
391# the message has siblings.
392#
393# Default: "├─"
394#thread-prefix-has-siblings = "├─"
395
396#
397# Customize the thread prefix appearance by selecting the connector used if the
398# message has no parents and no children.
399#
400# Default: ""
401#thread-prefix-lone = ""
402
403#
404# Customize the thread prefix appearance by selecting the connector used if the
405# message has no parents and has children.
406#
407# Default: ""
408#thread-prefix-orphan = ""
409
410#
411# Customize the thread prefix appearance by selecting the connector for the last
412# sibling.
413#
414# Default: "└─"
415#thread-prefix-last-sibling = "└─"
416
417#
418# Customize the reversed thread prefix appearance by selecting the connector for
419# the last sibling.
420#
421# Default: "┌─"
422#thread-prefix-last-sibling-reverse = "┌─"
423
424#
425# Customize the reversed thread prefix appearance by selecting the first child
426# connector.
427#
428# Default: ""
429#thread-prefix-first-child-reverse = ""
430
431#
432# Customize the reversed thread prefix appearance by selecting the connector
433# used if the message has no parents and has children.
434#
435# Default: ""
436#thread-prefix-orphan-reverse = ""
437
438[statusline]
439#
440# Describes the format for the status line. This is a comma separated list of
441# column names with an optional align and width suffix. See [ui].index-columns
442# for more details. To completely mute the status line except for push
443# notifications, explicitly set status-columns to an empty string.
444#
445# Default: left<*,center:=,right>*
446#status-columns=left<*,center:=,right>*
447
448#
449# Each name in status-columns must have a corresponding column-$name setting.
450# All column-$name settings accept golang text/template syntax. See
451# aerc-templates(7) for available template attributes and functions.
452#
453# Default settings
454#column-left=[{{.Account}}] {{.StatusInfo}}
455#column-center={{.PendingKeys}}
456#column-right={{.TrayInfo}}
457
458#
459# String separator inserted between columns.
460# See [ui].column-separator for more details.
461#
462#column-separator=" "
463
464# Specifies the separator between grouped statusline elements.
465#
466# Default: " | "
467#separator=" | "
468
469# Defines the mode for displaying the status elements.
470# Options: text, icon
471#
472# Default: text
473#display-mode=text
474
475[viewer]
476#
477# Specifies the pager to use when displaying emails. Note that some filters
478# may add ANSI codes to add color to rendered emails, so you may want to use a
479# pager which supports ANSI codes.
480#
481# Default: less -Rc
482#pager=less -Rc
483
484#
485# If an email offers several versions (multipart), you can configure which
486# mimetype to prefer. For example, this can be used to prefer plaintext over
487# html emails.
488#
489# Default: text/plain,text/html
490#alternatives=text/plain,text/html
491
492#
493# Default setting to determine whether to show full headers or only parsed
494# ones in message viewer.
495#
496# Default: false
497#show-headers=false
498
499#
500# Layout of headers when viewing a message. To display multiple headers in the
501# same row, separate them with a pipe, e.g. "From|To". Rows will be hidden if
502# none of their specified headers are present in the message.
503#
504# Default: From|To,Cc|Bcc,Date,Subject
505#header-layout=From|To,Cc|Bcc,Date,Subject
506
507# Whether to always show the mimetype of an email, even when it is just a single part
508#
509# Default: false
510#always-show-mime=false
511
512# Define the maximum height of the mimetype switcher before a scrollbar is used.
513# The height of the mimetype switcher is restricted to half of the display
514# height. If the provided value for the height is zero, the number of parts will
515# be used as the height of the type switcher.
516#
517# Default: 0
518#max-mime-height = 0
519
520# Parses and extracts http links when viewing a message. Links can then be
521# accessed with the open-link command.
522#
523# Default: true
524#parse-http-links=true
525
526[compose]
527#
528# Specifies the command to run the editor with. It will be shown in an embedded
529# terminal, though it may also launch a graphical window if the environment
530# supports it. Defaults to $EDITOR, or vi.
531editor=nvim
532
533#
534# When set, aerc will create and read .eml files for composing that have
535# non-standard \n linebreaks. This is only relevant if the used editor does not
536# support CRLF linebreaks.
537#
538#lf-editor=false
539
540#
541# Default header fields to display when composing a message. To display
542# multiple headers in the same row, separate them with a pipe, e.g. "To|From".
543#
544# Default: To|From,Subject
545#header-layout=To|From,Subject
546
547#
548# Edit headers into the text editor instead than separate fields.
549#
550# When this is true, address-book-cmd is not supported and address completion
551# is left to the editor itself. Also, displaying multiple headers on the same
552# line is not possible.
553#
554# Default: false
555#edit-headers=false
556
557#
558# Specifies the command to be used to tab-complete email addresses. Any
559# occurrence of "%s" in the address-book-cmd will be replaced with what the
560# user has typed so far.
561#
562# The command must output the completions to standard output, one completion
563# per line. Each line must be tab-delimited, with an email address occurring as
564# the first field. Only the email address field is required. The second field,
565# if present, will be treated as the contact name. Additional fields are
566# ignored.
567#
568# This parameter can also be set per account in accounts.conf.
569#address-book-cmd=
570
571# Specifies the command to be used to select attachments. Any occurrence of
572# '%s' in the file-picker-cmd will be replaced with the argument <arg>
573# to :attach -m <arg>. Any occurence of '%f' will be replaced by the
574# location of a temporary file, from which aerc will read the selected files.
575#
576# If '%f' is not present, the command must output the selected files to
577# standard output, one file per line. If it is present, then aerc does not
578# capture the standard output and instead reads the files from the temporary
579# file which should have the same format.
580file-picker-cmd=yazi --chooser-file %f
581
582#
583# Allow to address yourself when replying
584#
585# Default: true
586#reply-to-self=true
587
588# Warn before sending an email with an empty subject.
589#
590# Default: false
591empty-subject-warning=true
592
593#
594# Warn before sending an email that matches the specified regexp but does not
595# have any attachments. Leave empty to disable this feature.
596#
597# Uses Go's regexp syntax, documented at https://golang.org/s/re2syntax. The
598# "(?im)" flags are set by default (case-insensitive and multi-line).
599#
600# Example:
601# no-attachment-warning=^[^>]*attach(ed|ment)
602#
603no-attachment-warning=^[^>]*(attach|attached|attachment|anhang)
604
605#
606# When set, aerc will generate "format=flowed" bodies with a content type of
607# "text/plain; format=flowed" as described in RFC3676. This format is easier to
608# handle for some mailing software, and generally just looks like ordinary
609# text. To actually make use of this format's features, you'll need support in
610# your editor.
611#
612format-flowed=true
613
614[multipart-converters]
615#
616# Converters allow to generate multipart/alternative messages by converting the
617# main text/plain part into any other MIME type. Only exact MIME types are
618# accepted. The commands are invoked with sh -c and are expected to output
619# valid UTF-8 text.
620#
621# Example (obviously, this requires that you write your main text/plain body
622# using the markdown syntax):
623#text/html=pandoc -f markdown -t html --standalone
624
625[filters]
626#
627# Filters allow you to pipe an email body through a shell command to render
628# certain emails differently, e.g. highlighting them with ANSI escape codes.
629#
630# The commands are invoked with sh -c. The following folders are prepended to
631# the system $PATH to allow referencing filters from their name only:
632#
633# ${XDG_CONFIG_HOME:-~/.config}/aerc/filters
634# ~/.local/libexec/aerc/filters
635# ${XDG_DATA_HOME:-~/.local/share}/aerc/filters
636# $PREFIX/libexec/aerc/filters
637# $PREFIX/share/aerc/filters
638# /usr/libexec/aerc/filters
639# /usr/share/aerc/filters
640#
641# If you want to run a program in your default $PATH which has the same name
642# as a builtin filter (e.g. /usr/bin/colorize), use its absolute path.
643#
644# The following variables are defined in the filter command environment:
645#
646# AERC_MIME_TYPE the part MIME type/subtype
647# AERC_FORMAT the part content type format= parameter
648# AERC_FILENAME the attachment filename (if any)
649# AERC_SUBJECT the message Subject header value
650# AERC_FROM the message From header value
651#
652# The first filter which matches the email's mimetype will be used, so order
653# them from most to least specific.
654#
655# You can also match on non-mimetypes, by prefixing with the header to match
656# against (non-case-sensitive) and a comma, e.g. subject,text will match a
657# subject which contains "text". Use header,~regex to match against a regex.
658#
659text/plain=colorize
660text/calendar=calendar
661message/delivery-status=colorize
662message/rfc822=colorize
663text/html=pandoc -f html -t plain | colorize
664#text/html=html | colorize
665#text/*=bat -fP --file-name="$AERC_FILENAME"
666#application/x-sh=bat -fP -l sh
667image/*=wezterm imgcat --width $(tput cols)
668#subject,~Git(hub|lab)=lolcat -f
669#from,thatguywhodoesnothardwraphismessages=wrap -w 100 | colorize
670
671# This special filter is only used to post-process email headers when
672# [viewer].show-headers=true
673# By default, headers are piped directly into the pager.
674#
675.headers=colorize
676
677[openers]
678#
679# Openers allow you to specify the command to use for the :open and :open-link
680# actions on a per-MIME-type basis. The :open-link URL scheme is used to
681# determine the MIME type as follows: x-scheme-handler/<scheme>.
682#
683# {} is expanded as the temporary filename or URL to be opened with proper
684# shell quoting. If it is not encountered in the command, the filename/URL will
685# be appended to the end of the command. The command will then be executed with
686# `sh -c`.
687#
688# Like [filters], openers support basic shell globbing. The first opener which
689# matches the part's MIME type (or URL scheme handler MIME type) will be used,
690# so order them from most to least specific.
691#
692# Examples:
693x-scheme-handler/irc=weechat
694# x-scheme-handler/http*=printf '%s' {} | wl-copy
695# text/html=surf -dfgms
696# text/plain=gvim {} +125
697# message/rfc822=thunderbird
698
699[hooks]
700#
701# Hooks are triggered whenever the associated event occurs.
702
703#
704# Executed when a new email arrives in the selected folder
705mail-received=notify-send "📫 [$AERC_ACCOUNT/$AERC_FOLDER] New mail from $AERC_FROM_NAME" "$AERC_SUBJECT"
706
707#
708# Executed when mail is deleted from a folder
709#mail-deleted=mbsync "$AERC_ACCOUNT:$AERC_FOLDER" &
710
711#
712# Executed when aerc adds mail to a folder
713#mail-added=mbsync "$AERC_ACCOUNT:$AERC_FOLDER" &
714
715#
716# Executed when aerc starts
717#aerc-startup=aerc :terminal calcurse && aerc :next-tab
718
719#
720# Executed when aerc shuts down.
721#aerc-shutdown=
722
723[templates]
724# Templates are used to populate email bodies automatically.
725#
726
727# The directories where the templates are stored. It takes a colon-separated
728# list of directories. If this is unset or if a template cannot be found, the
729# following paths will be used as a fallback in that order:
730#
731# ${XDG_CONFIG_HOME:-~/.config}/aerc/templates
732# ${XDG_DATA_HOME:-~/.local/share}/aerc/templates
733# /usr/local/share/aerc/templates
734# /usr/share/aerc/templates
735#
736#template-dirs=
737
738# The default template to be used for new messages.
739#
740# default: new_message
741#new-message=new_message
742
743# The default template to be used for quoted replies.
744#
745# default: quoted_reply
746#quoted-reply=quoted_reply
747
748# The default template to be used for forward as body.
749#
750# default: forward_as_body
751#forwards=forward_as_body
1#
2# aerc main configuration
3
4[general]
5#
6# Used as a default path for save operations if no other path is specified.
7# ~ is expanded to the current user home dir.
8#
9default-save-path=~/Downloads
11# If set to "gpg", aerc will use system gpg binary and keystore for all crypto
12# operations. If set to "internal", the internal openpgp keyring will be used.
13# If set to "auto", the system gpg will be preferred unless the internal
14# keyring already exists, in which case the latter will be used.
15#
16# Default: auto
17#pgp-provider=auto
19# By default, the file permissions of accounts.conf must be restrictive and
20# only allow reading by the file owner (0600). Set this option to true to
21# ignore this permission check. Use this with care as it may expose your
22# credentials.
23#
24# Default: false
25#unsafe-accounts-conf=false
27# Output log messages to specified file. A path starting with ~/ is expanded to
28# the user home dir. When redirecting aerc's output to a file using > shell
29# redirection, this setting is ignored and log messages are printed to stdout.
30#
31#log-file=
33# Only log messages above the specified level to log-file. Supported levels
34# are: trace, debug, info, warn and error. When redirecting aerc's output to
35# a file using > shell redirection, this setting is ignored and the log level
36# is forced to trace.
37#
38# Default: info
39#log-level=info
41# Set the $TERM environment variable used for the embedded terminal.
42#
43# Default: xterm-256color
44#term=xterm-256color
46# Default shell command to use for :menu. This will be executed with sh -c and
47# will run in an popover dialog.
48#
49# Any occurrence of %f will be replaced by a temporary file path where the
50# command is expected to write output lines to be consumed by :menu. Otherwise,
51# the lines will be read from the command's standard output.
52#
53# Examples:
54# default-menu-cmd=fzf
55# default-menu-cmd=fzf --multi
56# default-menu-cmd=dmenu -l 20
57# default-menu-cmd=ranger --choosefiles=%f
58#
59default-menu-cmd=yazi --chooser-file %f
61[ui]
62#
63# Describes the format for each row in a mailbox view. This is a comma
64# separated list of column names with an optional align and width suffix. After
65# the column name, one of the '<' (left), ':' (center) or '>' (right) alignment
66# characters can be added (by default, left) followed by an optional width
67# specifier. The width is either an integer representing a fixed number of
68# characters, or a percentage between 1% and 99% representing a fraction of the
69# terminal width. It can also be one of the '*' (auto) or '=' (fit) special
70# width specifiers. Auto width columns will be equally attributed the remaining
71# terminal width. Fit width columns take the width of their contents. If no
72# width specifier is set, '*' is used by default.
73#
74# Default: date<20,name<17,flags>4,subject<*
75index-columns=date<6,flags>4,name<24,subject<*
77#
78# Each name in index-columns must have a corresponding column-$name setting.
79# All column-$name settings accept golang text/template syntax. See
80# aerc-templates(7) for available template attributes and functions.
81#
82# Here are some examples to show the To field instead of the From field for
83# an email (modifying column-name):
84#
85# 1. a generic one
86# column-name={{ .Peer | names | join ", " }}
87# 2. based upon the selected folder
88# column-name={{if match .Folder "^(Gesendet|Sent)$"}}{{index (.To | names) 0}}{{else}}{{index (.From | names) 0}}{{end}}
89#
90# Default settings
91#column-date={{.DateAutoFormat .Date.Local}}
92#column-name={{index (.From | names) 0}}
93#column-flags={{.Flags | join ""}}
94#column-subject={{.ThreadPrefix}}{{if .ThreadFolded}}{{printf "{%d}" .ThreadCount}}{{end}}{{.Subject}}
96#
97# String separator inserted between columns. When the column width specifier is
98# an exact number of characters, the separator is added to it (i.e. the exact
99# width will be fully available for the column contents).
100#
101# Default: " "
102column-separator=" 𝄀"
104#
105# See time.Time#Format at https://godoc.org/time#Time.Format
106#
107# Default: 2006-01-02 03:04 PM (ISO 8601 + 12 hour time)
108#timestamp-format=2006-01-02 03:04 PM
109timestamp-format=02.01.2006 03:04h
110# FIXME it would be nice to have different formats for the viewer
112#
113# Index-only time format for messages that were received/sent today.
114# If this is not specified, timestamp-format is used instead.
115#
116this-day-time-format=03:04h
118#
119# Index-only time format for messages that were received/sent within the last
120# 7 days. If this is not specified, timestamp-format is used instead.
121#
122this-week-time-format=02.01
124#
125# Index-only time format for messages that were received/sent this year.
126# If this is not specified, timestamp-format is used instead.
127#
128this-year-time-format=01.2006
130#
131# Width of the sidebar, including the border.
132#
133# Default: 20
134sidebar-width=24
136#
137# Message to display when viewing an empty folder.
138#
139# Default: (no messages)
140#empty-message=(no messages)
142# Message to display when no folders exists or are all filtered
143#
144# Default: (no folders)
145#empty-dirlist=(no folders)
146#
147# Value to set {{.Subject}} template to when subject is empty.
148#
149# Default: (no subject)
150#empty-subject=(no subject)
152# Enable mouse events in the ui, e.g. clicking and scrolling with the mousewheel
153#
154# Default: false
155mouse-enabled=true
157#
158# Ring the bell when new messages are received
159#
160# Default: true
161#new-message-bell=true
163#
164# Template to use for Account tab titles
165#
166# Default: {{.Account}}
167#tab-title-account={{.Account}}
169# Marker to show before a pinned tab's name.
170#
171# Default: `
172#pinned-tab-marker='`'
174# Template for the left side of the directory list.
175# See aerc-templates(7) for all available fields and functions.
176#
177# Default: {{.Folder}}
178dirlist-left={{.Folder}}{{if .Recent}} 󰺻{{end}}
180# Template for the right side of the directory list.
181# See aerc-templates(7) for all available fields and functions.
182#
183# Default: {{if .Unread}}{{humanReadable .Unread}}/{{end}}{{if .Exists}}{{humanReadable .Exists}}{{end}}
184#dirlist-right={{if .Unread}}{{humanReadable .Unread}}/{{end}}{{if .Exists}}{{humanReadable .Exists}}{{end}}
186# Delay after which the messages are actually listed when entering a directory.
187# This avoids loading messages when skipping over folders and makes the UI more
188# responsive. If you do not want that, set it to 0s.
189#
190# Default: 200ms
191dirlist-delay=100ms
193# Display the directory list as a foldable tree that allows to collapse and
194# expand the folders.
195#
196# Default: false
197dirlist-tree=true
199# If dirlist-tree is enabled, set level at which folders are collapsed by
200# default. Set to 0 to disable.
201#
202# Default: 0
203dirlist-collapse=3
205# List of space-separated criteria to sort the messages by, see *sort*
206# command in *aerc*(1) for reference. Prefixing a criterion with "-r "
207# reverses that criterion.
208#
209# Example: "from -r date"
210#
211sort=-r date from
213# Moves to next message when the current message is deleted
214#
215# Default: true
216#next-message-on-delete=true
218# Automatically set the "seen" flag when a message is opened in the message
219# viewer.
220#
221# Default: true
222#auto-mark-read=true
224# The directories where the stylesets are stored. It takes a colon-separated
225# list of directories. If this is unset or if a styleset cannot be found, the
226# following paths will be used as a fallback in that order:
227#
228# ${XDG_CONFIG_HOME:-~/.config}/aerc/stylesets
229# ${XDG_DATA_HOME:-~/.local/share}/aerc/stylesets
230# /usr/local/share/aerc/stylesets
231# /usr/share/aerc/stylesets
232#
233stylesets-dirs=~/.nugu-runtime/aerc
235# Uncomment to use box-drawing characters for vertical and horizontal borders.
236#
237# Default: " "
238border-char-vertical="│"
239border-char-horizontal="─"
241# Sets the styleset to use for the aerc ui elements.
242#
243# Default: default
244styleset-name=nugu
246# Activates fuzzy search in commands and their arguments: the typed string is
247# searched in the command or option in any position, and need not be
248# consecutive characters in the command or option.
249#
250# Default: false
251fuzzy-complete=true
253# How long to wait after the last input before auto-completion is triggered.
254#
255# Default: 250ms
256#completion-delay=250ms
258# The minimum required characters to allow auto-completion to be triggered after
259# completion-delay.
260#
261# Setting this to "manual" disables automatic completion, leaving only the
262# manually triggered completion with the $complete key (see aerc-binds(5) for
263# more details).
264#
265# Default: 1
266#completion-min-chars=1
268#
269# Global switch for completion popovers
270#
271# Default: true
272#completion-popovers=true
274# Uncomment to use UTF-8 symbols to indicate PGP status of messages
275#
276# Default: ASCII
277icon-unencrypted=󰇷
278icon-encrypted=✔
279icon-signed=✔
280icon-signed-encrypted=✔
281icon-unknown=✘
282icon-invalid=⚠
284# Reverses the order of the message list. By default, the message list is
285# ordered with the newest (highest UID) message on top. Reversing the order
286# will put the oldest (lowest UID) message on top. This can be useful in cases
287# where the backend does not support sorting.
288#
289# Default: false
290#reverse-msglist-order = false
292# Reverse display of the mesage threads. Default order is the the intial
293# message is on the top with all the replies being displayed below. The
294# reverse option will put the initial message at the bottom with the
295# replies on top.
296#
297# Default: false
298#reverse-thread-order=false
300# Sort the thread siblings according to the sort criteria for the messages. If
301# sort-thread-siblings is false, the thread siblings will be sorted based on
302# the message UID in ascending order. This option is only applicable for
303# client-side threading with a backend that enables sorting. Note that there's
304# a performance impact when sorting is activated.
305#
306# Default: false
307#sort-thread-siblings=false
309[ui:account=oliver]
310#
311# Enable a threaded view of messages. If this is not supported by the backend
312# (IMAP server or notmuch), threads will be built by the client.
313#
314# Default: false
315threading-enabled=true
317# Force client-side thread building
318#
319# Default: false
320#force-client-threads=false
322# Show thread context enables messages which do not match the current query (or
323# belong to the current mailbox) to be shown for context. These messages can be
324# styled separately using "msglist_thread_context" in a styleset. This feature
325# is not supported by all backends
326#
327# Default: false
328#show-thread-context=false
330# Debounce client-side thread building
331#
332# Default: 50ms
333#client-threads-delay=50ms
335#
336# Thread prefix customization:
338#
339# Customize the thread prefix appearance by selecting the arrow head.
340#
341# Default: ">"
342#thread-prefix-tip = ">"
344#
345# Customize the thread prefix appearance by selecting the arrow indentation.
346#
347# Default: " "
348#thread-prefix-indent = " "
350#
351# Customize the thread prefix appearance by selecting the vertical extension of
352# the arrow.
353#
354# Default: "│"
355#thread-prefix-stem = "│"
357#
358# Customize the thread prefix appearance by selecting the horizontal extension
359# of the arrow.
360#
361# Default: ""
362#thread-prefix-limb = ""
364#
365# Customize the thread prefix appearance by selecting the folded thread
366# indicator.
367#
368# Default: ""
369#thread-prefix-folded = ""
371#
372# Customize the thread prefix appearance by selecting the unfolded thread
373# indicator.
374#
375# Default: ""
376#thread-prefix-unfolded = ""
378#
379# Customize the thread prefix appearance by selecting the first child connector.
380#
381# Default: ""
382#thread-prefix-first-child = ""
384#
385# Customize the thread prefix appearance by selecting the connector used if
386# the message has siblings.
387#
388# Default: "├─"
389#thread-prefix-has-siblings = "├─"
391#
392# Customize the thread prefix appearance by selecting the connector used if the
393# message has no parents and no children.
394#
395# Default: ""
396#thread-prefix-lone = ""
398#
399# Customize the thread prefix appearance by selecting the connector used if the
400# message has no parents and has children.
401#
402# Default: ""
403#thread-prefix-orphan = ""
405#
406# Customize the thread prefix appearance by selecting the connector for the last
407# sibling.
408#
409# Default: "└─"
410#thread-prefix-last-sibling = "└─"
412#
413# Customize the reversed thread prefix appearance by selecting the connector for
414# the last sibling.
415#
416# Default: "┌─"
417#thread-prefix-last-sibling-reverse = "┌─"
419#
420# Customize the reversed thread prefix appearance by selecting the first child
421# connector.
422#
423# Default: ""
424#thread-prefix-first-child-reverse = ""
426#
427# Customize the reversed thread prefix appearance by selecting the connector
428# used if the message has no parents and has children.
429#
430# Default: ""
431#thread-prefix-orphan-reverse = ""
433[statusline]
434#
435# Describes the format for the status line. This is a comma separated list of
436# column names with an optional align and width suffix. See [ui].index-columns
437# for more details. To completely mute the status line except for push
438# notifications, explicitly set status-columns to an empty string.
439#
440# Default: left<*,center:=,right>*
441#status-columns=left<*,center:=,right>*
443#
444# Each name in status-columns must have a corresponding column-$name setting.
445# All column-$name settings accept golang text/template syntax. See
446# aerc-templates(7) for available template attributes and functions.
447#
448# Default settings
449#column-left=[{{.Account}}] {{.StatusInfo}}
450#column-center={{.PendingKeys}}
451#column-right={{.TrayInfo}}
453#
454# String separator inserted between columns.
455# See [ui].column-separator for more details.
456#
457#column-separator=" "
459# Specifies the separator between grouped statusline elements.
460#
461# Default: " | "
462#separator=" | "
464# Defines the mode for displaying the status elements.
465# Options: text, icon
466#
467# Default: text
468#display-mode=text
470[viewer]
471#
472# Specifies the pager to use when displaying emails. Note that some filters
473# may add ANSI codes to add color to rendered emails, so you may want to use a
474# pager which supports ANSI codes.
475#
476# Default: less -Rc
477#pager=less -Rc
479#
480# If an email offers several versions (multipart), you can configure which
481# mimetype to prefer. For example, this can be used to prefer plaintext over
482# html emails.
483#
484# Default: text/plain,text/html
485#alternatives=text/plain,text/html
487#
488# Default setting to determine whether to show full headers or only parsed
489# ones in message viewer.
490#
491# Default: false
492#show-headers=false
494#
495# Layout of headers when viewing a message. To display multiple headers in the
496# same row, separate them with a pipe, e.g. "From|To". Rows will be hidden if
497# none of their specified headers are present in the message.
498#
499# Default: From|To,Cc|Bcc,Date,Subject
500#header-layout=From|To,Cc|Bcc,Date,Subject
502# Whether to always show the mimetype of an email, even when it is just a single part
503#
504# Default: false
505#always-show-mime=false
507# Define the maximum height of the mimetype switcher before a scrollbar is used.
508# The height of the mimetype switcher is restricted to half of the display
509# height. If the provided value for the height is zero, the number of parts will
510# be used as the height of the type switcher.
511#
512# Default: 0
513#max-mime-height = 0
515# Parses and extracts http links when viewing a message. Links can then be
516# accessed with the open-link command.
517#
518# Default: true
519#parse-http-links=true
521[compose]
522#
523# Specifies the command to run the editor with. It will be shown in an embedded
524# terminal, though it may also launch a graphical window if the environment
525# supports it. Defaults to $EDITOR, or vi.
526editor=nvim
528#
529# When set, aerc will create and read .eml files for composing that have
530# non-standard \n linebreaks. This is only relevant if the used editor does not
531# support CRLF linebreaks.
532#
533#lf-editor=false
535#
536# Default header fields to display when composing a message. To display
537# multiple headers in the same row, separate them with a pipe, e.g. "To|From".
538#
539# Default: To|From,Subject
540#header-layout=To|From,Subject
542#
543# Edit headers into the text editor instead than separate fields.
544#
545# When this is true, address-book-cmd is not supported and address completion
546# is left to the editor itself. Also, displaying multiple headers on the same
547# line is not possible.
548#
549# Default: false
550#edit-headers=false
552#
553# Specifies the command to be used to tab-complete email addresses. Any
554# occurrence of "%s" in the address-book-cmd will be replaced with what the
555# user has typed so far.
556#
557# The command must output the completions to standard output, one completion
558# per line. Each line must be tab-delimited, with an email address occurring as
559# the first field. Only the email address field is required. The second field,
560# if present, will be treated as the contact name. Additional fields are
561# ignored.
562#
563# This parameter can also be set per account in accounts.conf.
564#address-book-cmd=
566# Specifies the command to be used to select attachments. Any occurrence of
567# '%s' in the file-picker-cmd will be replaced with the argument <arg>
568# to :attach -m <arg>. Any occurence of '%f' will be replaced by the
569# location of a temporary file, from which aerc will read the selected files.
570#
571# If '%f' is not present, the command must output the selected files to
572# standard output, one file per line. If it is present, then aerc does not
573# capture the standard output and instead reads the files from the temporary
574# file which should have the same format.
575file-picker-cmd=yazi --chooser-file %f
577#
578# Allow to address yourself when replying
579#
580# Default: true
581#reply-to-self=true
583# Warn before sending an email with an empty subject.
584#
585# Default: false
586empty-subject-warning=true
588#
589# Warn before sending an email that matches the specified regexp but does not
590# have any attachments. Leave empty to disable this feature.
591#
592# Uses Go's regexp syntax, documented at https://golang.org/s/re2syntax. The
593# "(?im)" flags are set by default (case-insensitive and multi-line).
594#
595# Example:
596# no-attachment-warning=^[^>]*attach(ed|ment)
597#
598no-attachment-warning=^[^>]*(attach|attached|attachment|anhang)
600#
601# When set, aerc will generate "format=flowed" bodies with a content type of
602# "text/plain; format=flowed" as described in RFC3676. This format is easier to
603# handle for some mailing software, and generally just looks like ordinary
604# text. To actually make use of this format's features, you'll need support in
605# your editor.
606#
607format-flowed=true
609[multipart-converters]
610#
611# Converters allow to generate multipart/alternative messages by converting the
612# main text/plain part into any other MIME type. Only exact MIME types are
613# accepted. The commands are invoked with sh -c and are expected to output
614# valid UTF-8 text.
615#
616# Example (obviously, this requires that you write your main text/plain body
617# using the markdown syntax):
618#text/html=pandoc -f markdown -t html --standalone
620[filters]
621#
622# Filters allow you to pipe an email body through a shell command to render
623# certain emails differently, e.g. highlighting them with ANSI escape codes.
624#
625# The commands are invoked with sh -c. The following folders are prepended to
626# the system $PATH to allow referencing filters from their name only:
627#
628# ${XDG_CONFIG_HOME:-~/.config}/aerc/filters
629# ~/.local/libexec/aerc/filters
630# ${XDG_DATA_HOME:-~/.local/share}/aerc/filters
631# $PREFIX/libexec/aerc/filters
632# $PREFIX/share/aerc/filters
633# /usr/libexec/aerc/filters
634# /usr/share/aerc/filters
635#
636# If you want to run a program in your default $PATH which has the same name
637# as a builtin filter (e.g. /usr/bin/colorize), use its absolute path.
638#
639# The following variables are defined in the filter command environment:
640#
641# AERC_MIME_TYPE the part MIME type/subtype
642# AERC_FORMAT the part content type format= parameter
643# AERC_FILENAME the attachment filename (if any)
644# AERC_SUBJECT the message Subject header value
645# AERC_FROM the message From header value
646#
647# The first filter which matches the email's mimetype will be used, so order
648# them from most to least specific.
649#
650# You can also match on non-mimetypes, by prefixing with the header to match
651# against (non-case-sensitive) and a comma, e.g. subject,text will match a
652# subject which contains "text". Use header,~regex to match against a regex.
653#
654text/plain=colorize
655text/calendar=calendar
656message/delivery-status=colorize
657message/rfc822=colorize
658text/html=pandoc -f html -t plain | colorize
659#text/html=html | colorize
660#text/*=bat -fP --file-name="$AERC_FILENAME"
661#application/x-sh=bat -fP -l sh
662image/*=wezterm imgcat --width $(tput cols)
663#subject,~Git(hub|lab)=lolcat -f
664#from,thatguywhodoesnothardwraphismessages=wrap -w 100 | colorize
666# This special filter is only used to post-process email headers when
667# [viewer].show-headers=true
668# By default, headers are piped directly into the pager.
669#
670.headers=colorize
672[openers]
673#
674# Openers allow you to specify the command to use for the :open and :open-link
675# actions on a per-MIME-type basis. The :open-link URL scheme is used to
676# determine the MIME type as follows: x-scheme-handler/<scheme>.
677#
678# {} is expanded as the temporary filename or URL to be opened with proper
679# shell quoting. If it is not encountered in the command, the filename/URL will
680# be appended to the end of the command. The command will then be executed with
681# `sh -c`.
682#
683# Like [filters], openers support basic shell globbing. The first opener which
684# matches the part's MIME type (or URL scheme handler MIME type) will be used,
685# so order them from most to least specific.
686#
687# Examples:
688x-scheme-handler/irc=weechat
689# x-scheme-handler/http*=printf '%s' {} | wl-copy
690# text/html=surf -dfgms
691# text/plain=gvim {} +125
692# message/rfc822=thunderbird
694[hooks]
695#
696# Hooks are triggered whenever the associated event occurs.
698#
699# Executed when a new email arrives in the selected folder
700mail-received=notify-send "📫 [$AERC_ACCOUNT/$AERC_FOLDER] New mail from $AERC_FROM_NAME" "$AERC_SUBJECT"
702#
703# Executed when mail is deleted from a folder
704#mail-deleted=mbsync "$AERC_ACCOUNT:$AERC_FOLDER" &
706#
707# Executed when aerc adds mail to a folder
708#mail-added=mbsync "$AERC_ACCOUNT:$AERC_FOLDER" &
710#
711# Executed when aerc starts
712#aerc-startup=aerc :terminal calcurse && aerc :next-tab
714#
715# Executed when aerc shuts down.
716#aerc-shutdown=
718[templates]
719# Templates are used to populate email bodies automatically.
720#
722# The directories where the templates are stored. It takes a colon-separated
723# list of directories. If this is unset or if a template cannot be found, the
724# following paths will be used as a fallback in that order:
725#
726# ${XDG_CONFIG_HOME:-~/.config}/aerc/templates
727# ${XDG_DATA_HOME:-~/.local/share}/aerc/templates
728# /usr/local/share/aerc/templates
729# /usr/share/aerc/templates
730#
731#template-dirs=
733# The default template to be used for new messages.
734#
735# default: new_message
736#new-message=new_message
738# The default template to be used for quoted replies.
739#
740# default: quoted_reply
741#quoted-reply=quoted_reply
743# The default template to be used for forward as body.
744#
745# default: forward_as_body
746#forwards=forward_as_body

aerc/binds.conf

Modified

+180 / −180 text lines

1# Binds are of the form <key sequence> = <command to run>
2# To use '=' in a key sequence, substitute it with "Eq": "<Ctrl+Eq>"
3# If you wish to bind #, you can wrap the key sequence in quotes: "#" = quit
4<C-p> = :prev-tab<Enter>
5<C-PgUp> = :prev-tab<Enter>
6<C-n> = :next-tab<Enter>
7<C-PgDn> = :next-tab<Enter>
8\[t = :prev-tab<Enter>
9\]t = :next-tab<Enter>
10<C-t> = :term<Enter>
11? = :help keys<Enter>
12<C-c> = :prompt 'Quit?' quit<Enter>
13<C-q> = :prompt 'Quit?' quit<Enter>
14<C-z> = :suspend<Enter>
15
16[messages]
17q = :prompt 'Quit?' quit<Enter>
18
19j = :next<Enter>
20<Down> = :next<Enter>
21<C-d> = :next 50%<Enter>
22<C-f> = :next 100%<Enter>
23<PgDn> = :next 100%<Enter>
24
25k = :prev<Enter>
26<Up> = :prev<Enter>
27<C-u> = :prev 50%<Enter>
28<C-b> = :prev 100%<Enter>
29<PgUp> = :prev 100%<Enter>
30g = :select 0<Enter>
31G = :select -1<Enter>
32
33J = :next-folder<Enter>
34<C-Down> = :next-folder<Enter>
35K = :prev-folder<Enter>
36<C-Up> = :prev-folder<Enter>
37H = :collapse-folder<Enter>
38<C-Left> = :collapse-folder<Enter>
39L = :expand-folder<Enter>
40<C-Right> = :expand-folder<Enter>
41
42v = :mark -t<Enter>
43<Space> = :mark -t<Enter>:next<Enter>
44V = :mark -v<Enter>
45
46T = :toggle-threads<Enter>
47zc = :fold<Enter>
48zo = :unfold<Enter>
49za = :fold -t<Enter>
50zM = :fold -a<Enter>
51zR = :unfold -a<Enter>
52<tab> = :fold -t<Enter>
53
54<Enter> = :view<Enter>
55d = :prompt 'Really delete this message?' 'delete-message'<Enter>
56D = :delete<Enter>
57a = :archive flat<Enter>
58A = :unmark -a<Enter>:mark -T<Enter>:archive flat<Enter>
59
60C = :compose<Enter>
61m = :compose<Enter>
62
63rr = :reply -a<Enter>
64rq = :reply -aq<Enter>
65Rr = :reply<Enter>
66Rq = :reply -q<Enter>
67
68c = :cf<space>
69$ = :term<space>
70! = :term<space>
71| = :pipe<space>
72
73/ = :search<space>
74\ = :filter<space>
75n = :next-result<Enter>
76N = :prev-result<Enter>
77<Esc> = :clear<Enter>
78
79s = :split<Enter>
80S = :vsplit<Enter>
81
82pl = :patch list<Enter>
83pa = :patch apply <Tab>
84pd = :patch drop <Tab>
85pb = :patch rebase<Enter>
86pt = :patch term<Enter>
87ps = :patch switch <Tab>
88
89[messages:folder=Drafts]
90<Enter> = :recall<Enter>
91
92[view]
93/ = :toggle-key-passthrough<Enter>/
94q = :close<Enter>
95O = :open<Enter>
96o = :open<Enter>
97E = :pipe -p nvim -R -n -c 'setlocal ft=mail nomodifiable' -<Enter>
98S = :save<space>
99Y = :pipe -pb ~/.config/aerc/copy-to-clipboard current-part<Enter>
100M = :pipe -mb ~/.config/aerc/copy-to-clipboard full-message<Enter>
101| = :pipe<space>
102D = :delete<Enter>
103A = :archive flat<Enter>
104
105<C-l> = :open-link <space>
106
107f = :forward<Enter>
108rr = :reply -a<Enter>
109rq = :reply -aq<Enter>
110Rr = :reply<Enter>
111Rq = :reply -q<Enter>
112
113H = :toggle-headers<Enter>
114<C-k> = :prev-part<Enter>
115<C-Up> = :prev-part<Enter>
116<C-j> = :next-part<Enter>
117<C-Down> = :next-part<Enter>
118J = :next<Enter>
119<C-Right> = :next<Enter>
120K = :prev<Enter>
121<C-Left> = :prev<Enter>
122
123[view::passthrough]
124$noinherit = true
125$ex = <C-x>
126<Esc> = :toggle-key-passthrough<Enter>
127
128[compose]
129# Keybindings used when the embedded terminal is not selected in the compose
130# view
131$noinherit = true
132$ex = <C-x>
133$complete = <C-o>
134<C-k> = :prev-field<Enter>
135<C-Up> = :prev-field<Enter>
136<C-j> = :next-field<Enter>
137<C-Down> = :next-field<Enter>
138<A-p> = :switch-account -p<Enter>
139<C-Left> = :switch-account -p<Enter>
140<A-n> = :switch-account -n<Enter>
141<C-Right> = :switch-account -n<Enter>
142<tab> = :next-field<Enter>
143<backtab> = :prev-field<Enter>
144<C-p> = :prev-tab<Enter>
145<C-PgUp> = :prev-tab<Enter>
146<C-n> = :next-tab<Enter>
147<C-PgDn> = :next-tab<Enter>
148
149[compose::editor]
150# Keybindings used when the embedded terminal is selected in the compose view
151$noinherit = true
152$ex = <C-x>
153<C-k> = :prev-field<Enter>
154<C-Up> = :prev-field<Enter>
155<C-j> = :next-field<Enter>
156<C-Down> = :next-field<Enter>
157<C-p> = :prev-tab<Enter>
158<C-PgUp> = :prev-tab<Enter>
159<C-n> = :next-tab<Enter>
160<C-PgDn> = :next-tab<Enter>
161
162[compose::review]
163# Keybindings used when reviewing a message to be sent
164y = :send<Enter>
165n = :abort<Enter>
166v = :preview<Enter>
167p = :postpone<Enter>
168q = :choose -o d discard abort -o p postpone postpone<Enter>
169e = :edit<Enter>
170a = :attach<space>
171d = :detach<space>
172
173[terminal]
174$noinherit = true
175$ex = <C-x>
176
177<C-p> = :prev-tab<Enter>
178<C-n> = :next-tab<Enter>
179<C-PgUp> = :prev-tab<Enter>
180<C-PgDn> = :next-tab<Enter>
1# Binds are of the form <key sequence> = <command to run>
2# To use '=' in a key sequence, substitute it with "Eq": "<Ctrl+Eq>"
3# If you wish to bind #, you can wrap the key sequence in quotes: "#" = quit
4<C-p> = :prev-tab<Enter>
5<C-PgUp> = :prev-tab<Enter>
6<C-n> = :next-tab<Enter>
7<C-PgDn> = :next-tab<Enter>
8\[t = :prev-tab<Enter>
9\]t = :next-tab<Enter>
10<C-t> = :term<Enter>
11? = :help keys<Enter>
12<C-c> = :prompt 'Quit?' quit<Enter>
13<C-q> = :prompt 'Quit?' quit<Enter>
14<C-z> = :suspend<Enter>
16[messages]
17q = :prompt 'Quit?' quit<Enter>
19j = :next<Enter>
20<Down> = :next<Enter>
21<C-d> = :next 50%<Enter>
22<C-f> = :next 100%<Enter>
23<PgDn> = :next 100%<Enter>
25k = :prev<Enter>
26<Up> = :prev<Enter>
27<C-u> = :prev 50%<Enter>
28<C-b> = :prev 100%<Enter>
29<PgUp> = :prev 100%<Enter>
30g = :select 0<Enter>
31G = :select -1<Enter>
33J = :next-folder<Enter>
34<C-Down> = :next-folder<Enter>
35K = :prev-folder<Enter>
36<C-Up> = :prev-folder<Enter>
37H = :collapse-folder<Enter>
38<C-Left> = :collapse-folder<Enter>
39L = :expand-folder<Enter>
40<C-Right> = :expand-folder<Enter>
42v = :mark -t<Enter>
43<Space> = :mark -t<Enter>:next<Enter>
44V = :mark -v<Enter>
46T = :toggle-threads<Enter>
47zc = :fold<Enter>
48zo = :unfold<Enter>
49za = :fold -t<Enter>
50zM = :fold -a<Enter>
51zR = :unfold -a<Enter>
52<tab> = :fold -t<Enter>
54<Enter> = :view<Enter>
55d = :prompt 'Really delete this message?' 'delete-message'<Enter>
56D = :delete<Enter>
57a = :archive flat<Enter>
58A = :unmark -a<Enter>:mark -T<Enter>:archive flat<Enter>
60C = :compose<Enter>
61m = :compose<Enter>
63rr = :reply -a<Enter>
64rq = :reply -aq<Enter>
65Rr = :reply<Enter>
66Rq = :reply -q<Enter>
68c = :cf<space>
69$ = :term<space>
70! = :term<space>
71| = :pipe<space>
73/ = :search<space>
74\ = :filter<space>
75n = :next-result<Enter>
76N = :prev-result<Enter>
77<Esc> = :clear<Enter>
79s = :split<Enter>
80S = :vsplit<Enter>
82pl = :patch list<Enter>
83pa = :patch apply <Tab>
84pd = :patch drop <Tab>
85pb = :patch rebase<Enter>
86pt = :patch term<Enter>
87ps = :patch switch <Tab>
89[messages:folder=Drafts]
90<Enter> = :recall<Enter>
92[view]
93/ = :toggle-key-passthrough<Enter>/
94q = :close<Enter>
95O = :open<Enter>
96o = :open<Enter>
97E = :pipe -p nvim -R -n -c 'setlocal ft=mail nomodifiable' -<Enter>
98S = :save<space>
99Y = :pipe -pb ~/.config/aerc/copy-to-clipboard current-part<Enter>
100M = :pipe -mb ~/.config/aerc/copy-to-clipboard full-message<Enter>
101| = :pipe<space>
102D = :delete<Enter>
103A = :archive flat<Enter>
105<C-l> = :open-link <space>
107f = :forward<Enter>
108rr = :reply -a<Enter>
109rq = :reply -aq<Enter>
110Rr = :reply<Enter>
111Rq = :reply -q<Enter>
113H = :toggle-headers<Enter>
114<C-k> = :prev-part<Enter>
115<C-Up> = :prev-part<Enter>
116<C-j> = :next-part<Enter>
117<C-Down> = :next-part<Enter>
118J = :next<Enter>
119<C-Right> = :next<Enter>
120K = :prev<Enter>
121<C-Left> = :prev<Enter>
123[view::passthrough]
124$noinherit = true
125$ex = <C-x>
126<Esc> = :toggle-key-passthrough<Enter>
128[compose]
129# Keybindings used when the embedded terminal is not selected in the compose
130# view
131$noinherit = true
132$ex = <C-x>
133$complete = <C-o>
134<C-k> = :prev-field<Enter>
135<C-Up> = :prev-field<Enter>
136<C-j> = :next-field<Enter>
137<C-Down> = :next-field<Enter>
138<A-p> = :switch-account -p<Enter>
139<C-Left> = :switch-account -p<Enter>
140<A-n> = :switch-account -n<Enter>
141<C-Right> = :switch-account -n<Enter>
142<tab> = :next-field<Enter>
143<backtab> = :prev-field<Enter>
144<C-p> = :prev-tab<Enter>
145<C-PgUp> = :prev-tab<Enter>
146<C-n> = :next-tab<Enter>
147<C-PgDn> = :next-tab<Enter>
149[compose::editor]
150# Keybindings used when the embedded terminal is selected in the compose view
151$noinherit = true
152$ex = <C-x>
153<C-k> = :prev-field<Enter>
154<C-Up> = :prev-field<Enter>
155<C-j> = :next-field<Enter>
156<C-Down> = :next-field<Enter>
157<C-p> = :prev-tab<Enter>
158<C-PgUp> = :prev-tab<Enter>
159<C-n> = :next-tab<Enter>
160<C-PgDn> = :next-tab<Enter>
162[compose::review]
163# Keybindings used when reviewing a message to be sent
164y = :send<Enter>
165n = :abort<Enter>
166v = :preview<Enter>
167p = :postpone<Enter>
168q = :choose -o d discard abort -o p postpone postpone<Enter>
169e = :edit<Enter>
170a = :attach<space>
171d = :detach<space>
173[terminal]
174$noinherit = true
175$ex = <C-x>
177<C-p> = :prev-tab<Enter>
178<C-n> = :next-tab<Enter>
179<C-PgUp> = :prev-tab<Enter>
180<C-PgDn> = :next-tab<Enter>

bash/bashrc

Modified

+27 / −38 text lines

1# Bash interactive config from dotfiles.
1export CARGO_HOME="$HOME/.cargo"
2export PATH="$CARGO_HOME/bin:$PATH"
3case "$-" in
4 *i*) ;;
5 *) return ;;
4export GO_HOME="$HOME/go"
5export PATH="$GO_HOME/bin:$PATH"
6
7export PATH="$HOME/.local/bin:$PATH"
8
9
10export TERMUX_X11_XSTARTUP="wezterm"
12eval "$(zoxide init bash)"
13eval "$(JUST_COMPLETE=bash just)"
16# Termux/Android node-gyp workaround for native npm packages like node-pty.
17# node-gyp's Android config expects android_ndk_path; keep this safe to source repeatedly.
18_node_gyp_android_ndk="$HOME/.termux-node-gyp-android-ndk"
19mkdir -p "$_node_gyp_android_ndk/sources/android/cpufeatures" 2>/dev/null || true
20case " ${GYP_DEFINES:-} " in
21 *" android_ndk_path=$_node_gyp_android_ndk "*) ;;
22 *) export GYP_DEFINES="android_ndk_path=$_node_gyp_android_ndk${GYP_DEFINES:+ $GYP_DEFINES}" ;;
623esac
24unset _node_gyp_android_ndk
8# Linux virtual console colors. No sudo, no effect in terminal emulators.
9_nugu_console_theme() {
10 [ "${TERM:-}" = linux ] || return 0
12 local mode="${1:-light}"
13 local theme="$HOME/.config/bash/linux-console/nugu-$mode.sh"
15 if [ ! -r "$theme" ]; then
16 printf 'missing theme: %s\n' "$theme" >&2
17 return 1
18 fi
20 . "$theme"
21 clear
22}
24tt() {
25 case "${1:-toggle}" in
26 dark|light) _nugu_console_theme "$1" ;;
27 toggle)
28 case "${NUGU_CONSOLE_THEME:-light}" in
29 light) _nugu_console_theme dark ;;
30 dark) _nugu_console_theme light ;;
31 *) _nugu_console_theme light ;;
32 esac
33 ;;
34 *)
35 printf 'usage: tt [dark|light]\n' >&2
36 return 2
37 ;;
38 esac
39}
41_nugu_console_theme light
26_bash_secrets="${XDG_CONFIG_HOME:-$HOME/.config}/bash/secrets.bash"
27if [[ -r "$_bash_secrets" ]]; then
28 source "$_bash_secrets"
29fi
30unset _bash_secrets

bash/secrets.bash

Added
new file mode 100644

Binary size (old → new): 0 → 89 bytes.

bat/config

Modified

+14 / −14 text lines

1# apply colors from my terminal color scheme
2--theme=ansi
3--style=full
4
5--tabs 2
6#--show-all
7#--nonprintable-notation=unicode
8
9# use features of modern terminals
10--italic-text=always
11
12# Map some unknown file types to (hopefully similar) known ones
13--map-syntax "*.nu:Rust"
14--map-syntax ".stignore:Git Ignore"
1# apply colors from my terminal color scheme
2--theme=ansi
3--style=full
4
5--tabs 2
6#--show-all
7#--nonprintable-notation=unicode
8
9# use features of modern terminals
10--italic-text=always
12# Map some unknown file types to (hopefully similar) known ones
13--map-syntax "*.nu:Rust"
14--map-syntax ".stignore:Git Ignore"

bootstripper.java

Modified

+607 / −157 text lines

44import java.io.IOException;
55import java.net.InetAddress;
66import java.nio.charset.StandardCharsets;
7import java.nio.file.AtomicMoveNotSupportedException;
78import java.nio.file.Files;
89import java.nio.file.LinkOption;
910import java.nio.file.Path;
10import java.nio.file.attribute.PosixFilePermission;
11import java.nio.file.StandardCopyOption;
1112import java.nio.file.attribute.PosixFilePermissions;
1213import java.security.SecureRandom;
1314import java.util.ArrayList;
1415import java.util.Arrays;
16import java.time.LocalDateTime;
17import java.time.format.DateTimeFormatter;
1518import java.util.Base64;
1619import java.util.HashSet;
1720import java.util.List;
18import java.util.Set;
19import java.util.regex.Pattern;
21import java.util.LinkedHashMap;
22import java.util.LinkedHashSet;
2023import java.util.stream.Collectors;
2124import javax.crypto.SecretKeyFactory;
2225import javax.crypto.spec.PBEKeySpec;
2528 private final static String operating_system = System.getProperty("os.name");
2629 private final static boolean win32 = operating_system.toLowerCase().contains("win");
2730 private final static String filter_name = "dotfiles-aes";
28 private final static String key_file = ".git/dotfiles-aes.key";
31 private final static String key_file = "dotfiles-aes.key";
32 private final static String aes_cache_file = "dotfiles-aes.java";
2933 private final static String salt_file = ".dotfiles-aes-salt";
3034 private final static String secrets_file = ".secrets";
3135 private final static String attributes_begin = "# BEGIN bootstripper secrets";
3236 private final static String attributes_end = "# END bootstripper secrets";
37 private final static String hook_marker = "# Managed by dorkfiles bootstripper.java";
3338 private final static byte[] aes_magic = new byte[] { 'D', 'F', 'A', 'E', 'S', '1' };
3439 private final static int salt_bytes = 32;
3540 private final static int derived_key_bits = 512;
3641 private final static int pbkdf2_iterations = 310_000;
42 private final static List<String> warnings = new ArrayList<>();
43 private final static List<String> errors = new ArrayList<>();
3845 public static void main(String[] arguments) throws Throwable {
3946 var command = "bootstrap";
6269 return;
6370 }
6471 if ("check".equals(command)) {
65 setup_crypto(root, false);
72 setup_crypto(root);
73 install_repo_settings(root);
6674 check(root);
6775 return;
6876 }
6977 if ("pre-commit".equals(command)) {
70 setup_crypto(root, false);
7178 pre_commit(root);
7279 return;
7380 }
81 if ("pre-push".equals(command)) {
82 pre_push(root);
83 return;
84 }
7485 if ("install-hooks".equals(command)) {
7586 require_git_repo(root);
76 require_normal_gitdir(root);
7787 install_hooks(root);
7888 return;
7989 }
8595 return;
8696 }
88 setup_crypto(root, true);
98 if ("link".equals(command)) {
99 var symlinks_file = symlinks_file(root);
100 check_symlink_sources(root);
101 converge_crypto(root);
102 install_repo_settings(root);
103 install_hooks(root);
104 create_symlinks(root, symlinks_file);
105 print_attention(false);
106 return;
107 }
109 if ("setup-crypto".equals(command)) {
110 converge_crypto(root);
111 return;
112 }
113 var symlinks_file = symlinks_file(root);
114 check_symlink_sources(root);
115 converge_crypto(root);
116 install_repo_settings(root);
89117 install_hooks(root);
90118 check(root);
91 var symlinks_file = symlinks_file(root);
92119 create_symlinks(root, symlinks_file);
120 print_attention(false);
93121 }
95123 static boolean is_command(String argument) {
96 return "bootstrap".equals(argument) || "clean".equals(argument) || "check".equals(argument) || "pre-commit".equals(argument) || "install-hooks".equals(argument) || "init-crypto".equals(argument);
124 return "bootstrap".equals(argument) || "link".equals(argument) || "clean".equals(argument) || "check".equals(argument) || "pre-commit".equals(argument) || "pre-push".equals(argument) || "install-hooks".equals(argument) || "init-crypto".equals(argument) || "setup-crypto".equals(argument);
97125 }
99127 static void init_crypto(Path root) throws Throwable {
109137 log("Created crypto salt: {0}", emphasize_local(salt_file));
110138 }
112 static void setup_crypto(Path root, boolean restore) throws Throwable {
140 static List<String> setup_crypto(Path root) throws Throwable {
113141 require_git_repo(root);
114142 var secrets = read_secrets(root);
115143 if (secrets.isEmpty())
116 return;
117 require_normal_gitdir(root);
144 return secrets;
145 validate_secret_paths(root, secrets);
146 install_aes_tool(root);
147 ensure_key(root, secrets);
118148 install_filter(root);
119149 write_attributes(root, secrets);
120 ensure_key(root);
121 self_test_aes(root);
122 if (restore)
123 restore_tracked_secrets(root, secrets);
150 remove_local_attributes(root);
124151 apply_secret_permissions(root, secrets);
152 return secrets;
153 }
155 static void converge_crypto(Path root) throws Throwable {
156 var secrets = setup_crypto(root);
157 if (!secrets.isEmpty())
158 restore_tracked_secrets(root, secrets);
125159 }
127161 static void require_git_repo(Path root) throws Throwable {
128162 run(root, List.of("git", "rev-parse", "--is-inside-work-tree"), null, false);
129163 }
131 static void require_normal_gitdir(Path root) throws Throwable {
132 if (!Files.isDirectory(root.resolve(".git")))
133 throw fail("Expected normal .git directory. Linked worktrees are not supported yet.");
165 static Path git_common_path(Path root, String path) throws Throwable {
166 var common = run(root, List.of("git", "rev-parse", "--git-common-dir"), null, false).text().strip();
167 var common_path = Path.of(common);
168 if (!common_path.isAbsolute())
169 common_path = root.resolve(common_path).normalize();
170 return common_path.resolve(path).toAbsolutePath();
171 }
173 static Path key_path(Path root) throws Throwable {
174 return git_common_path(root, key_file);
175 }
177 static String key_argument(Path root) throws Throwable {
178 return key_path(root).toString();
179 }
181 static String aes_tool_argument(Path root) throws Throwable {
182 return git_common_path(root, aes_cache_file).toString();
183 }
185 static String clean_filter_command(Path root) throws Throwable {
186 return "java " + quote_shell(aes_tool_argument(root)) + " encrypt --key-file " + quote_shell(key_argument(root));
187 }
189 static String smudge_filter_command(Path root) throws Throwable {
190 return "java " + quote_shell(aes_tool_argument(root)) + " decrypt --key-file " + quote_shell(key_argument(root));
191 }
193 static String merge_filter_command(Path root) throws Throwable {
194 return "java " + quote_shell(aes_tool_argument(root)) + " merge --key-file " + quote_shell(key_argument(root))
195 + " " + quote_shell("%O") + " " + quote_shell("%A") + " " + quote_shell("%B");
134196 }
136198 static List<String> read_secrets(Path root) throws IOException {
142204 var line = raw.strip();
143205 if (line.isEmpty() || line.startsWith("#"))
144206 continue;
145 if (line.contains(" ") || line.contains("\t") || line.startsWith("/") || line.contains("\\"))
207 if (line.contains(" ") || line.contains("\t") || line.startsWith("/") || line.contains("\\")
208 || line.startsWith(":") || line.contains("*") || line.contains("?") || line.contains("["))
146209 throw new IllegalArgumentException("invalid secret path: " + line);
147210 secrets.add(line);
148211 }
149212 return secrets;
150213 }
215 static void install_aes_tool(Path root) throws Throwable {
216 var source = root.resolve("tools/aes.java");
217 if (!Files.isRegularFile(source, LinkOption.NOFOLLOW_LINKS))
218 throw fail("Expected a regular AES tool source at: {0}", source);
219 var target = git_common_path(root, aes_cache_file);
220 if (Files.exists(target, LinkOption.NOFOLLOW_LINKS)) {
221 if (!Files.isRegularFile(target, LinkOption.NOFOLLOW_LINKS))
222 throw fail("Refusing to replace non-file cached AES tool: {0}", target);
223 if (Files.mismatch(source, target) == -1L)
224 return;
225 }
226 Files.createDirectories(target.getParent());
227 var temporary = Files.createTempFile(target.getParent(), "." + aes_cache_file + ".", ".tmp");
228 try {
229 Files.copy(source, temporary, StandardCopyOption.REPLACE_EXISTING);
230 try {
231 Files.move(temporary, target, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING);
232 } catch (AtomicMoveNotSupportedException ignored) {
233 Files.move(temporary, target, StandardCopyOption.REPLACE_EXISTING);
234 }
235 } finally {
236 Files.deleteIfExists(temporary);
237 }
238 }
240 static void validate_secret_paths(Path root, List<String> secrets) throws Throwable {
241 for (var secret : secrets) {
242 var original = Path.of(secret);
243 for (var component : original)
244 if (component.toString().equals(".."))
245 throw fail("Secret path must not contain parent components: {0}", secret);
246 var relative = original.normalize();
247 if (relative.isAbsolute() || relative.startsWith(".."))
248 throw fail("Secret path must stay inside the repository: {0}", secret);
249 var current = root;
250 for (var component : relative) {
251 current = current.resolve(component);
252 if (Files.isSymbolicLink(current))
253 throw fail("Secret path must not contain symlinks: {0}", secret);
254 }
255 if (Files.exists(current, LinkOption.NOFOLLOW_LINKS) && !Files.isRegularFile(current, LinkOption.NOFOLLOW_LINKS))
256 throw fail("Secret path must name a regular file: {0}", secret);
257 }
258 }
152260 static void install_filter(Path root) throws Throwable {
153 run(root, List.of("git", "config", "--local", "filter." + filter_name + ".clean",
154 "java tools/aes.java encrypt --key-file " + key_file), null, false);
155 run(root, List.of("git", "config", "--local", "filter." + filter_name + ".smudge",
156 "java tools/aes.java decrypt --key-file " + key_file), null, false);
157 run(root, List.of("git", "config", "--local", "filter." + filter_name + ".required", "true"), null, false);
261 set_local_config(root, "filter." + filter_name + ".clean", clean_filter_command(root));
262 set_local_config(root, "filter." + filter_name + ".smudge", smudge_filter_command(root));
263 set_local_config(root, "filter." + filter_name + ".required", "true");
264 set_local_config(root, "merge." + filter_name + ".driver", merge_filter_command(root));
265 }
267 // Autostash is a trap in this repository: the worktree is nearly always dirty, so
268 // every rebase or merge stashes first, and the required crypto filter plus the Git
269 // hooks can abort the operation before the stash is restored. The changes then sit
270 // in a silent `autostash` stash entry while the files look deleted. Refuse instead.
271 static void install_repo_settings(Path root) throws Throwable {
272 set_local_config(root, "rebase.autostash", "false");
273 set_local_config(root, "merge.autostash", "false");
274 }
276 static void check_repo_settings(Path root) throws Throwable {
277 check_local_config(root, "rebase.autostash", "false");
278 check_local_config(root, "merge.autostash", "false");
279 }
281 static void check_local_config(Path root, String name, String value) throws Throwable {
282 var current = run(root, List.of("git", "config", "--local", "--get", name), null, false, false);
283 if (current.exit != 0 || !current.text().strip().equals(value))
284 throw fail("Local Git setting {0} must be {1}. Run `mise run link`.", name, value);
285 }
287 static void set_local_config(Path root, String name, String value) throws Throwable {
288 var current = run(root, List.of("git", "config", "--local", "--get", name), null, false, false);
289 if (current.exit != 0 || !current.text().strip().equals(value))
290 run(root, List.of("git", "config", "--local", name, value), null, false);
291 }
293 static String quote_shell(String argument) {
294 return "'" + argument.replace("'", "'\\''") + "'";
158295 }
160297 static void write_attributes(Path root, List<String> secrets) throws IOException {
161 var attributes = root.resolve(".git/info/attributes");
162 Files.createDirectories(attributes.getParent());
163 var previous = Files.exists(attributes) ? Files.readString(attributes) : "";
298 var attributes = root.resolve(".gitattributes");
299 var content = Files.exists(attributes) ? without_managed_attributes(Files.readString(attributes)) : "";
300 if (!content.isEmpty() && !content.endsWith("\n"))
301 content += "\n";
302 var lines = new ArrayList<String>();
303 lines.add(attributes_begin);
304 for (var secret : secrets)
305 lines.add(secret + " -text filter=" + filter_name + " -diff merge=" + filter_name);
306 lines.add(attributes_end);
307 var desired = content + String.join("\n", lines) + "\n";
308 if (!Files.exists(attributes) || !Files.readString(attributes).equals(desired))
309 Files.writeString(attributes, desired, StandardCharsets.UTF_8);
310 }
312 static void remove_local_attributes(Path root) throws Throwable {
313 var attributes = git_common_path(root, "info/attributes");
314 if (!Files.exists(attributes))
315 return;
316 var previous = Files.readString(attributes);
317 var content = without_managed_attributes(previous);
318 if (!content.equals(previous))
319 Files.writeString(attributes, content, StandardCharsets.UTF_8);
320 }
322 static String without_managed_attributes(String content) {
164323 var lines = new ArrayList<String>();
165324 var in_block = false;
166 for (var line : previous.split("\n", -1)) {
325 for (var line : content.split("\\R", -1)) {
167326 if (attributes_begin.equals(line)) {
168327 in_block = true;
169328 continue;
172331 in_block = false;
173332 continue;
174333 }
175 if (!in_block && !line.isEmpty())
334 if (!in_block)
176335 lines.add(line);
177336 }
178 lines.add(attributes_begin);
179 for (var secret : secrets)
180 lines.add(secret + " -text filter=" + filter_name + " -diff");
181 lines.add(attributes_end);
182 Files.writeString(attributes, String.join("\n", lines) + "\n", StandardCharsets.UTF_8);
337 return String.join("\n", lines);
183338 }
185 static void ensure_key(Path root) throws Throwable {
186 var key = root.resolve(key_file);
187 if (Files.exists(key))
340 static void ensure_key(Path root, List<String> secrets) throws Throwable {
341 var key = key_path(root);
342 if (Files.exists(key, LinkOption.NOFOLLOW_LINKS)) {
343 validate_key(key);
344 ensure_permissions(key, "rw-------");
188345 return;
189 var salt = read_salt(root);
190 var passphrase = passphrase();
191 try {
192 var factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256");
193 var spec = new PBEKeySpec(passphrase, salt, pbkdf2_iterations, derived_key_bits);
194 var encoded = factory.generateSecret(spec).getEncoded();
195 Files.writeString(key, Base64.getEncoder().encodeToString(encoded) + "\n", StandardCharsets.UTF_8);
196 chmod(key, "rw-------");
197 log("Cached dotfiles AES key in {0}", emphasize_local(key_file));
198 } finally {
199 Arrays.fill(passphrase, '\0');
200346 }
347 Files.createDirectories(key.getParent());
348 var temporary = Files.createTempFile(key.getParent(), key_file + ".", ".tmp");
349 char[] passphrase = null;
350 try {
351 passphrase = passphrase();
352 var factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256");
353 var spec = new PBEKeySpec(passphrase, read_salt(root), pbkdf2_iterations, derived_key_bits);
354 var encoded = factory.generateSecret(spec).getEncoded();
355 Files.writeString(temporary, Base64.getEncoder().encodeToString(encoded) + "\n", StandardCharsets.UTF_8);
356 ensure_permissions(temporary, "rw-------");
357 if (!authenticate_key(root, secrets, temporary))
358 self_test_aes(root, temporary);
359 try {
360 Files.move(temporary, key, StandardCopyOption.ATOMIC_MOVE);
361 } catch (AtomicMoveNotSupportedException ignored) {
362 Files.move(temporary, key);
363 }
364 log("Cached dotfiles AES key in {0}", emphasize_local(key.toString()));
365 } finally {
366 if (passphrase != null)
367 Arrays.fill(passphrase, '\0');
368 Files.deleteIfExists(temporary);
369 }
370 }
372 static void validate_key(Path key) throws IOException {
373 if (!Files.isRegularFile(key, LinkOption.NOFOLLOW_LINKS) || !Files.isReadable(key))
374 throw new IllegalStateException("Dotfiles AES key must be a readable regular file: " + key);
375 try {
376 if (Base64.getDecoder().decode(Files.readString(key).trim()).length != derived_key_bits / 8)
377 throw new IllegalStateException("Dotfiles AES key has the wrong length: " + key);
378 } catch (IllegalArgumentException problem) {
379 throw new IllegalStateException("Dotfiles AES key is not valid Base64: " + key);
380 }
381 }
383 static boolean authenticate_key(Path root, List<String> secrets, Path key) throws Throwable {
384 String encrypted_secret = null;
385 for (var secret : secrets) {
386 var committed = run(root, List.of("git", "cat-file", "blob", "HEAD:" + secret), null, false, false);
387 if (committed.exit != 0 || !starts_with(committed.stdout, aes_magic))
388 continue;
389 encrypted_secret = secret;
390 var decrypted = run(root, List.of("java", aes_tool_argument(root), "decrypt", "--key-file", key.toString()), committed.stdout, false, false);
391 if (decrypted.exit == 0)
392 return true;
393 }
394 if (encrypted_secret != null)
395 throw new IllegalStateException("Passphrase does not decrypt committed secrets, including: " + encrypted_secret);
396 return false;
201397 }
203399 static byte[] read_salt(Path root) throws IOException {
222418 return first;
223419 }
225 static void self_test_aes(Path root) throws Throwable {
421 static void self_test_aes(Path root, Path key) throws Throwable {
226422 var plain = "bootstripper self-test".getBytes(StandardCharsets.UTF_8);
227 var encrypted = run(root, List.of("java", "tools/aes.java", "encrypt", "--key-file", key_file), plain, false).stdout;
228 if (!starts_with(encrypted, aes_magic))
229 throw fail("AES self-test did not produce expected magic header.");
230 var decrypted = run(root, List.of("java", "tools/aes.java", "decrypt", "--key-file", key_file), encrypted, false).stdout;
231 if (!Arrays.equals(plain, decrypted))
232 throw fail("AES self-test failed to round-trip.");
423 var aes = aes_tool_argument(root);
424 var encrypted = run(root, List.of("java", aes, "encrypt", "--key-file", key.toString()), plain, false, false);
425 if (encrypted.exit != 0 || !starts_with(encrypted.stdout, aes_magic))
426 throw new IllegalStateException("AES self-test encryption failed: " + encrypted.error().strip());
427 var decrypted = run(root, List.of("java", aes, "decrypt", "--key-file", key.toString()), encrypted.stdout, false, false);
428 if (decrypted.exit != 0 || !Arrays.equals(plain, decrypted.stdout))
429 throw new IllegalStateException("AES self-test decryption failed: " + decrypted.error().strip());
233430 }
235432 static void restore_tracked_secrets(Path root, List<String> secrets) throws Throwable {
236 var tracked = new ArrayList<String>();
237 for (var secret : secrets) {
238 var result = run(root, List.of("git", "cat-file", "-e", "HEAD:" + secret), null, false, false);
239 if (result.exit == 0) {
240 tracked.add(secret);
241 var path = root.resolve(secret);
242 if (Files.exists(path) && starts_with(Files.readAllBytes(path), aes_magic))
243 Files.delete(path);
244 }
245 }
433 var tree_command = new ArrayList<>(List.of("git", "--literal-pathspecs", "ls-tree", "--name-only", "-z", "HEAD", "--"));
434 tree_command.addAll(secrets);
435 var tracked_output = run(root, tree_command, null, false, false);
436 if (tracked_output.exit != 0)
437 return;
438 var tracked = new LinkedHashSet<String>();
439 for (var path : new String(tracked_output.stdout, StandardCharsets.UTF_8).split("\u0000"))
440 if (!path.isEmpty()) tracked.add(path);
246441 if (tracked.isEmpty())
247442 return;
248 var command = new ArrayList<String>();
249 command.addAll(List.of("git", "restore", "--source=HEAD", "--worktree", "--"));
250 command.addAll(tracked);
251 run(root, command, null, false);
444 var staged_command = new ArrayList<>(List.of("git", "--literal-pathspecs", "diff", "--cached", "--quiet", "HEAD", "--"));
445 staged_command.addAll(tracked);
446 if (run(root, staged_command, null, false, false).exit != 0) {
447 for (var secret : tracked)
448 if (run(root, List.of("git", "--literal-pathspecs", "diff", "--cached", "--quiet", "HEAD", "--", secret), null, false, false).exit != 0)
449 throw fail("Refusing to restore locally changed secret: {0}", secret);
450 }
452 var current = new LinkedHashMap<String, byte[]>();
453 var needs_restoration = false;
454 for (var secret : tracked) {
455 var path = root.resolve(secret);
456 if (!Files.isRegularFile(path, LinkOption.NOFOLLOW_LINKS))
457 throw fail("Refusing to restore locally changed secret: {0}", secret);
458 var bytes = Files.readAllBytes(path);
459 current.put(secret, bytes);
460 needs_restoration |= starts_with(bytes, aes_magic);
461 }
462 if (!needs_restoration)
463 return;
465 var pending = new LinkedHashMap<Path, byte[]>();
466 for (var secret : tracked) {
467 var committed = run(root, List.of("git", "cat-file", "blob", "HEAD:" + secret), null, false);
468 var plain = run(root, List.of("java", aes_tool_argument(root), "decrypt", "--key-file", key_argument(root)), committed.stdout, false).stdout;
469 var bytes = current.get(secret);
470 if (Arrays.equals(bytes, committed.stdout))
471 pending.put(root.resolve(secret), plain);
472 else if (!Arrays.equals(bytes, plain))
473 throw fail("Refusing to restore locally changed secret: {0}", secret);
474 }
475 for (var entry : pending.entrySet())
476 Files.write(entry.getKey(), entry.getValue());
252477 }
254479 static void apply_secret_permissions(Path root, List<String> secrets) throws IOException {
255480 for (var secret : secrets) {
256481 var path = root.resolve(secret);
257482 if (Files.exists(path) && secret.startsWith("ssh/") && secret.endsWith(".key"))
258 chmod(path, "rw-------");
483 ensure_permissions(path, "rw-------");
259484 }
260485 }
262 static void install_hooks(Path root) throws IOException {
263 var hooks = root.resolve(".git/hooks");
487 static void install_hooks(Path root) throws Throwable {
488 var hooks = git_hooks_path(root);
489 var pre_commit = hooks.resolve("pre-commit");
490 var pre_push = hooks.resolve("pre-push");
491 var legacy_pre_commit = "#!/bin/sh\ncd \"$(git rev-parse --show-toplevel)\" || exit 1\nexec java bootstripper.java pre-commit\n";
492 var pre_commit_content = hook_content("pre-commit");
493 var pre_push_content = hook_content("pre-push");
494 check_hook_destination(pre_commit, pre_commit_content, legacy_pre_commit);
495 check_hook_destination(pre_push, pre_push_content, null);
496 install_hook(hooks, pre_commit, pre_commit_content);
497 install_hook(hooks, pre_push, pre_push_content);
498 }
500 static Path git_hooks_path(Path root) throws Throwable {
501 var configured = run(root, List.of("git", "config", "--show-scope", "--get", "core.hooksPath"), null, false, false);
502 if (configured.exit == 0 && !configured.text().matches("(?s)^(local|worktree)\\s+.*"))
503 throw fail("Refusing to modify inherited core.hooksPath. Configure a repository-local hooks path or unset it.");
504 var result = run(root, List.of("git", "rev-parse", "--path-format=absolute", "--git-path", "hooks"), null, false).text().strip();
505 var hooks = Path.of(result).toAbsolutePath().normalize();
506 if (hooks.equals(Path.of("/dev/null")) || Files.exists(hooks, LinkOption.NOFOLLOW_LINKS) && !Files.isDirectory(hooks, LinkOption.NOFOLLOW_LINKS))
507 throw fail("Invalid Git hooks directory: {0}", hooks);
508 return hooks;
509 }
511 static String hook_content(String command) {
512 return "#!/bin/sh\n" + hook_marker + "\ncd \"$(git rev-parse --show-toplevel)\" || exit 1\nexec java bootstripper.java " + command + "\n";
513 }
515 static void check_hook_destination(Path hook, String expected, String legacy) throws Throwable {
516 if (!Files.exists(hook, LinkOption.NOFOLLOW_LINKS))
517 return;
518 if (Files.isSymbolicLink(hook) || !Files.isRegularFile(hook, LinkOption.NOFOLLOW_LINKS))
519 throw fail("Refusing to replace non-file Git hook: {0}", hook);
520 var content = Files.readString(hook);
521 if (content.equals(expected) || content.equals(legacy) || content.contains("\n" + hook_marker + "\n"))
522 return;
523 throw fail("Refusing to replace unmanaged Git hook: {0}", hook);
524 }
526 static void install_hook(Path hooks, Path hook, String content) throws Throwable {
527 var content_matches = Files.isRegularFile(hook, LinkOption.NOFOLLOW_LINKS) && Files.readString(hook).equals(content);
528 var permissions_match = hook_permissions_match(hook);
529 if (content_matches && permissions_match)
530 return;
264531 Files.createDirectories(hooks);
265 var hook = hooks.resolve("pre-commit");
266 Files.writeString(hook, "#!/bin/sh\ncd \"$(git rev-parse --show-toplevel)\" || exit 1\nexec java bootstripper.java pre-commit\n", StandardCharsets.UTF_8);
267 chmod(hook, "rwxr-xr-x");
268 log("Installed Git hook: {0}", emphasize_local(".git/hooks/pre-commit"));
532 if (!content_matches) {
533 var temporary = Files.createTempFile(hooks, "." + hook.getFileName() + ".", ".tmp");
534 try {
535 Files.writeString(temporary, content, StandardCharsets.UTF_8);
536 chmod(temporary, "rwxr-xr-x");
537 try {
538 Files.move(temporary, hook, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING);
539 } catch (AtomicMoveNotSupportedException ignored) {
540 Files.move(temporary, hook, StandardCopyOption.REPLACE_EXISTING);
541 }
542 } finally {
543 Files.deleteIfExists(temporary);
544 }
545 } else {
546 chmod(hook, "rwxr-xr-x");
547 }
548 log("Installed Git hook: {0}", emphasize_local(hook.toString()));
549 }
551 static boolean hook_permissions_match(Path hook) throws IOException {
552 if (win32)
553 return true;
554 try {
555 return Files.exists(hook) && Files.getPosixFilePermissions(hook).equals(PosixFilePermissions.fromString("rwxr-xr-x"));
556 } catch (UnsupportedOperationException ignored) {
557 return Files.isExecutable(hook);
558 }
269559 }
271561 static void pre_commit(Path root) throws Throwable {
562 run_gitleaks(root, List.of("--pre-commit", "--staged"));
563 check_staged_matches_worktree(root, secrets_file);
564 check_staged_matches_worktree(root, ".gitattributes");
272565 check(root);
273566 }
568 static void pre_push(Path root) throws Throwable {
569 for (var line : new String(System.in.readAllBytes(), StandardCharsets.UTF_8).lines().toList()) {
570 if (line.isBlank())
571 continue;
572 var fields = line.strip().split("\\s+");
573 if (fields.length != 4)
574 throw fail("Invalid pre-push input: expected four fields.");
575 var local_oid = fields[1];
576 var remote_oid = fields[3];
577 if (is_zero_oid(local_oid))
578 continue;
579 if (!is_oid(local_oid) || !is_oid(remote_oid))
580 throw fail("Invalid object ID in pre-push input.");
581 var local_commit = resolve_commit(root, local_oid, "local");
582 var remote_commit = run(root, List.of("git", "rev-parse", "--verify", remote_oid + "^{commit}"), null, false, false);
583 var revisions = is_zero_oid(remote_oid) || remote_commit.exit != 0
584 ? local_commit
585 : remote_commit.text().strip() + ".." + local_commit;
586 var log_options = "--full-history --diff-merges=first-parent --no-ext-diff --no-textconv " + revisions;
587 run_gitleaks(root, List.of("--platform=none", "--log-opts=" + log_options));
588 }
589 }
591 static boolean is_oid(String value) {
592 return value.matches("[0-9a-fA-F]{40}|[0-9a-fA-F]{64}");
593 }
595 static boolean is_zero_oid(String value) {
596 return is_oid(value) && value.chars().allMatch(character -> character == '0');
597 }
599 static String resolve_commit(Path root, String oid, String label) throws Throwable {
600 var result = run(root, List.of("git", "rev-parse", "--verify", oid + "^{commit}"), null, false, false);
601 if (result.exit != 0)
602 throw fail("Pre-push {0} object is not a commit: {1}", label, oid);
603 return result.text().strip();
604 }
606 static void run_gitleaks(Path root, List<String> scan_arguments) throws Throwable {
607 var command = new ArrayList<>(List.of("gitleaks", "git"));
608 command.addAll(scan_arguments);
609 command.addAll(List.of("--redact=100", "--no-banner"));
610 Result result;
611 try {
612 result = run(root, command, null, true, false);
613 } catch (IOException error) {
614 throw fail("Gitleaks is required for Git hooks. Install Gitleaks, ensure it is on Git''s PATH, then retry.");
615 }
616 if (result.exit != 0)
617 throw fail("Gitleaks blocked the operation (exit {0}). Review its redacted output.", result.exit);
618 }
620 static void check_staged_matches_worktree(Path root, String path) throws Throwable {
621 var tracked = run(root, List.of("git", "ls-files", "--error-unmatch", "--", path), null, false, false);
622 var changed = run(root, List.of("git", "-c", "diff.autoRefreshIndex=false", "diff", "--no-ext-diff", "--no-textconv", "--quiet", "--", path), null, false, false);
623 if (tracked.exit != 0 || changed.exit != 0)
624 throw fail("{0} must match the staged version.", path);
625 }
275627 static void check(Path root) throws Throwable {
276628 var secrets = read_secrets(root);
277 if (secrets.isEmpty())
278 return;
279 check_filter(root);
280 check_attributes(root, secrets);
281 check_key_not_tracked(root);
282 check_staged_secrets(root, secrets);
629 if (!secrets.isEmpty()) {
630 if (!Files.isReadable(key_path(root)))
631 throw fail("Dotfiles AES key is unavailable. Run `mise run setup-crypto`, then retry.");
632 check_filter(root);
633 check_attributes(root, secrets);
634 check_secrets_not_ignored(root, secrets);
635 check_worktree_secrets_decrypted(root, secrets);
636 check_key_not_tracked(root);
637 check_staged_secrets(root, secrets);
638 }
639 check_repo_settings(root);
283640 check_symlink_sources(root);
284 check_no_tresor_refs(root);
285 check_staged_plaintext_patterns(root);
286641 log("OK bootstripper check passed.");
287642 }
290645 var clean = run(root, List.of("git", "config", "--local", "--get", "filter." + filter_name + ".clean"), null, false).text().strip();
291646 var smudge = run(root, List.of("git", "config", "--local", "--get", "filter." + filter_name + ".smudge"), null, false).text().strip();
292647 var required = run(root, List.of("git", "config", "--local", "--get", "filter." + filter_name + ".required"), null, false).text().strip();
293 if (!clean.equals("java tools/aes.java encrypt --key-file " + key_file))
648 var merge = run(root, List.of("git", "config", "--local", "--get", "merge." + filter_name + ".driver"), null, false).text().strip();
649 if (!clean.equals(clean_filter_command(root)))
294650 throw fail("Unexpected clean filter: {0}", clean);
295 if (!smudge.equals("java tools/aes.java decrypt --key-file " + key_file))
651 if (!smudge.equals(smudge_filter_command(root)))
296652 throw fail("Unexpected smudge filter: {0}", smudge);
297653 if (!required.equals("true"))
298654 throw fail("Filter is not required.");
655 if (!merge.equals(merge_filter_command(root)))
656 throw fail("Unexpected merge driver: {0}", merge);
299657 }
301659 static void check_attributes(Path root, List<String> secrets) throws Throwable {
302660 for (var secret : secrets) {
303 var output = run(root, List.of("git", "check-attr", "text", "filter", "diff", "--", secret), null, false).text();
661 var output = run(root, List.of("git", "--literal-pathspecs", "check-attr", "text", "filter", "diff", "merge", "--", secret), null, false).text();
304662 if (!output.contains(secret + ": text: unset"))
305663 throw fail("Missing -text attribute for {0}: {1}", secret, output.strip());
306664 if (!output.contains(secret + ": filter: " + filter_name))
307665 throw fail("Missing filter attribute for {0}: {1}", secret, output.strip());
308666 if (!output.contains(secret + ": diff: unset"))
309667 throw fail("Missing -diff attribute for {0}: {1}", secret, output.strip());
668 if (!output.contains(secret + ": merge: " + filter_name))
669 throw fail("Missing merge attribute for {0}: {1}", secret, output.strip());
670 }
671 }
673 static void check_secrets_not_ignored(Path root, List<String> secrets) throws Throwable {
674 var command = new ArrayList<String>(List.of("git", "check-ignore", "--no-index", "--verbose", "--"));
675 command.addAll(secrets);
676 var result = run(root, command, null, false, false);
677 if (result.exit == 0)
678 throw fail("Secret paths are matched by ignore rules, so they can never be encrypted or staged: {0}", result.text().strip());
679 if (result.exit != 1)
680 throw fail("Unable to check ignore rules for secrets: {0}", result.text().strip());
681 }
683 static void check_worktree_secrets_decrypted(Path root, List<String> secrets) throws Throwable {
684 for (var secret : secrets) {
685 var path = root.resolve(secret);
686 if (Files.exists(path) && starts_with(Files.readAllBytes(path), aes_magic))
687 throw fail("Worktree secret is encrypted; smudge failed: {0}", secret);
310688 }
311689 }
313691 static void check_key_not_tracked(Path root) throws Throwable {
314 var bad = run(root, List.of("git", "ls-files", "--", key_file), null, false).text().strip();
692 var bad = run(root, List.of("git", "ls-files", "--", ".git/" + key_file, key_file), null, false).text().strip();
315693 if (!bad.isEmpty())
316694 throw fail("Key file is tracked: {0}", key_file);
317 var staged = run(root, List.of("git", "diff", "--cached", "--name-only", "--", key_file), null, false).text().strip();
695 var staged = run(root, List.of("git", "diff", "--cached", "--name-only", "--", ".git/" + key_file, key_file), null, false).text().strip();
318696 if (!staged.isEmpty())
319697 throw fail("Key file is staged: {0}", key_file);
320698 }
322700 static void check_staged_secrets(Path root, List<String> secrets) throws Throwable {
323701 for (var secret : secrets) {
324 var status = run(root, List.of("git", "diff", "--cached", "--name-status", "--", secret), null, false).text().strip();
702 var status = run(root, List.of("git", "--literal-pathspecs", "diff", "--cached", "--name-status", "--", secret), null, false).text().strip();
325703 if (status.isEmpty() || status.startsWith("D"))
326704 continue;
327705 var blob = run(root, List.of("git", "show", ":" + secret), null, false).stdout;
328706 if (!starts_with(blob, aes_magic))
329707 throw fail("Staged secret is not encrypted: {0}", secret);
330 run(root, List.of("java", "tools/aes.java", "decrypt", "--key-file", key_file), blob, false);
708 run(root, List.of("java", aes_tool_argument(root), "decrypt", "--key-file", key_argument(root)), blob, false);
331709 }
332710 }
335713 try (var stream = Files.list(root)) {
336714 var files = stream.filter(path -> path.getFileName().toString().endsWith(".symlinks")).collect(Collectors.toList());
337715 for (var file : files) {
716 var targets = new HashSet<Path>();
338717 var lines = Files.readAllLines(file);
339718 String source = null;
719 var source_line = 0;
340720 var line_number = 0;
341721 for (var raw : lines) {
342722 line_number++;
345725 continue;
346726 if (source == null) {
347727 source = line;
728 source_line = line_number;
348729 continue;
349730 }
350731 var source_path = root.resolve(source);
351732 if (!Files.exists(source_path, LinkOption.NOFOLLOW_LINKS))
352 throw fail("Missing symlink source: {0}:{1}: {2}", file.getFileName(), line_number - 1, source);
733 throw fail("Missing symlink source: {0}:{1}: {2}", file.getFileName(), source_line, source);
734 var target_path = expand_target(line).normalize();
735 if (!targets.add(target_path))
736 throw fail("Duplicate symlink target: {0}:{1}: {2}", file.getFileName(), line_number, line);
353737 source = null;
354738 }
355739 if (source != null)
358742 }
359743 }
361 static void check_no_tresor_refs(Path root) throws IOException {
362 try (var stream = Files.list(root)) {
363 var files = stream.filter(path -> path.getFileName().toString().endsWith(".symlinks")).collect(Collectors.toList());
364 for (var file : files) {
365 var line_number = 0;
366 for (var line : Files.readAllLines(file)) {
367 line_number++;
368 if (line.strip().startsWith("tresor/"))
369 throw new IllegalStateException("tresor reference remains: " + file.getFileName() + ":" + line_number);
370 }
371 }
372 }
373 }
375 static void check_staged_plaintext_patterns(Path root) throws Throwable {
376 var diff = run(root, List.of("git", "diff", "--cached", "-U0"), null, false).text();
377 var patterns = List.of(
378 Pattern.compile("gh[pousr]_[A-Za-z0-9_]{20,}"),
379 Pattern.compile("github_personal_access_token\\s*\\\":\\s*\\\"[^<G][^\\\"]+\\\""),
380 Pattern.compile("oauth_(access|refresh)_token\\s*=\\s*\\S+"),
381 Pattern.compile("Authorization\\s*[:=]\\s*Bearer\\s+[A-Za-z0-9._-]{20,}", Pattern.CASE_INSENSITIVE));
382 for (var pattern : patterns) {
383 var matcher = pattern.matcher(diff);
384 if (matcher.find())
385 throw fail("Potential plaintext secret in staged diff.");
386 }
387 }
389745 static Path symlinks_file(Path root) throws Throwable {
390746 var hostname = hostname();
391747 var manifest = symlinks_manifest(root, hostname);
401757 var explicit = System.getenv("DOTFILES_SYMLINKS");
402758 if (explicit != null && !explicit.isBlank())
403759 return explicit.replaceFirst("\\.symlinks$", "");
404 if (is_wsl() && Files.exists(root.resolve("wsl.symlinks")))
405 return "wsl";
406760 return hostname;
407761 }
409 static boolean is_wsl() {
410 var distro = System.getenv("WSL_DISTRO_NAME");
411 if (distro != null && !distro.isBlank())
412 return true;
413 try {
414 var release = Files.readString(Path.of("/proc/sys/kernel/osrelease"), StandardCharsets.UTF_8).toLowerCase();
415 return release.contains("microsoft") || release.contains("wsl");
416 } catch (IOException ignored) {
417 return false;
418 }
419 }
421763 static void create_symlinks(Path root, Path symlinks_file) throws Throwable {
422764 log("Creating symlinks as defined in {0} file.", emphasize_local(symlinks_file.getFileName().toString()));
423765 var lines = Files.readAllLines(symlinks_file);
445787 }
447789 static void link(Path root, String source, String target) throws Throwable {
448 var source_path = root.resolve(source).toAbsolutePath();
790 var source_path = root.resolve(source).toAbsolutePath().normalize();
449791 if (!Files.exists(source_path)) {
450792 log("\n{0} does not exist anymore in my dorkfiles. Have I yeeted it?", emphasize_global(source_path.toString()));
451793 return;
452794 }
795 var expected = source_path.toRealPath();
796 require_inside_home(expected, "Symlink source");
453797 var target_path = expand_target(target);
454798 if (Files.exists(target_path, LinkOption.NOFOLLOW_LINKS)) {
455799 if (Files.isSymbolicLink(target_path)) {
456 var actual = target_path.toRealPath();
457 var expected = source_path.toRealPath();
458 if (actual.equals(expected)) {
459 log("\nOK {0} -> {1}.", emphasize_global(target_path.toString()), emphasize_local(source_path.toString()));
460 return;
800 var raw_actual = symlink_target_path(target_path);
801 if (!inside_home(raw_actual))
802 throw fail("Target symlink points outside HOME: {0} -> {1}. Move it manually.", target_path, raw_actual);
803 if (!Files.exists(target_path)) {
804 log("\nRELINK {0}: broken symlink.", emphasize_global(target_path.toString()));
805 remove_owned_symlink(target_path);
806 } else {
807 var actual = target_path.toRealPath();
808 if (actual.equals(expected)) {
809 log("\nOK {0} -> {1}.", emphasize_global(target_path.toString()), emphasize_local(source_path.toString()));
810 return;
811 }
812 if (!inside_home(actual))
813 throw fail("Target symlink points outside HOME: {0} -> {1}. Move it manually.", target_path, actual);
814 else {
815 if (!actual.startsWith(root.toRealPath()))
816 throw fail("Target symlink points outside dorkfiles: {0} -> {1}. Move it manually.", target_path, actual);
817 log("\nRELINK {0}: {1} -> {2}.", emphasize_global(target_path.toString()), emphasize_local(actual.toString()), emphasize_local(expected.toString()));
818 remove_owned_symlink(target_path);
819 }
461820 }
462 log("\nRELINK {0}: {1} -> {2}.", emphasize_global(target_path.toString()), emphasize_local(actual.toString()), emphasize_local(expected.toString()));
463 Files.delete(target_path);
464821 } else if (Files.exists(target_path)) {
465822 var actual = target_path.toRealPath();
466 var expected = source_path.toRealPath();
467823 if (actual.equals(expected)) {
468824 log("\nOK {0} resolves to {1}.", emphasize_global(target_path.toString()), emphasize_local(source_path.toString()));
469825 return;
470826 }
471 throw fail("Target exists but is not a symlink: {0}. Move it away or run clean first.", target_path);
827 var backup = sibling_backup_path(target_path);
828 var message = format("BACKUP {0} TO {1}.", target_path, backup);
829 log("\n{0}", message);
830 warn(message);
831 Files.move(target_path, backup);
472832 } else {
473833 log("\nNOPE {0} exists, but it points into nirvana. Removing broken link!", target_path.toString());
474834 Files.delete(target_path);
481841 Files.createSymbolicLink(target_path, source_path);
482842 }
484 static Path expand_target(String target) {
485 var home = System.getProperty("user.home");
486 if ("~".equals(target))
487 return Path.of(home).toAbsolutePath();
488 if (target.startsWith("~/"))
489 return Path.of(home).resolve(target.substring(2)).toAbsolutePath();
490 return Path.of(target).toAbsolutePath();
844 static void remove_owned_symlink(Path target_path) throws Throwable {
845 if (!win32) {
846 Files.delete(target_path);
847 return;
848 }
849 var retired = sibling_path(target_path, "replaced");
850 Files.move(target_path, retired);
851 try {
852 Files.delete(retired);
853 } catch (IOException error) {
854 log("WIN32 kept retired link for later cleanup: {0}", retired);
855 }
856 }
858 static Path symlink_target_path(Path target_path) throws IOException {
859 var link = Files.readSymbolicLink(target_path);
860 var resolved = link.isAbsolute() ? link : target_path.getParent().resolve(link);
861 return resolved.toAbsolutePath().normalize();
862 }
864 static Path sibling_backup_path(Path target_path) throws Throwable {
865 return sibling_path(target_path, "backup");
866 }
868 static Path sibling_path(Path target_path, String kind) throws Throwable {
869 var stamp = DateTimeFormatter.ofPattern("yyyyMMdd-HHmmss").format(LocalDateTime.now());
870 var base = target_path.resolveSibling(target_path.getFileName() + ".dorkfiles-" + kind + "-" + stamp);
871 var candidate = base;
872 var suffix = 1;
873 while (Files.exists(candidate, LinkOption.NOFOLLOW_LINKS)) {
874 candidate = Path.of(base + "." + suffix);
875 suffix++;
876 }
877 return candidate;
878 }
880 static Path expand_target(String target) throws Throwable {
881 var path = switch (target) {
882 case "~" -> target_home_path();
883 default -> target.startsWith("~/") ? target_home_path().resolve(target.substring(2)) : Path.of(target).toAbsolutePath();
884 };
885 path = path.normalize();
886 require_inside_home(path, "Symlink target");
887 return path;
888 }
890 static Path target_home_path() {
891 return Path.of(System.getProperty("user.home")).toAbsolutePath().normalize();
892 }
894 static Path home_path() {
895 var home = System.getenv("HOME");
896 if (home == null || home.isBlank())
897 home = System.getProperty("user.home");
898 return Path.of(home).toAbsolutePath().normalize();
899 }
901 static boolean inside_home(Path path) {
902 return path.toAbsolutePath().normalize().startsWith(home_path());
903 }
905 static void require_inside_home(Path path, String label) throws Throwable {
906 if (!inside_home(path))
907 throw fail("{0} outside HOME: {1}", label, path.toAbsolutePath().normalize());
491908 }
493910 static String hostname() throws Exception {
494 if (is_wsl())
495 return "wsl";
496911 var computername = System.getenv("COMPUTERNAME");
497912 if (computername != null && !computername.isBlank())
498913 return computername;
914 var wsl_distro = System.getenv("WSL_DISTRO_NAME");
915 if (wsl_distro != null && !wsl_distro.isBlank())
916 return wsl_distro;
499917 var hostname = System.getenv("HOSTNAME");
500918 if (hostname != null && !hostname.isBlank() && !"localhost".equals(hostname))
501919 return hostname;
505923 return detected;
506924 }
926 static void ensure_permissions(Path path, String permissions) throws IOException {
927 if (win32)
928 return;
929 try {
930 var desired = PosixFilePermissions.fromString(permissions);
931 if (!Files.getPosixFilePermissions(path).equals(desired))
932 Files.setPosixFilePermissions(path, desired);
933 } catch (UnsupportedOperationException ignored) {}
934 }
508936 static void chmod(Path path, String permissions) throws IOException {
509937 if (win32)
510938 return;
551979 static void usage() {
552980 log("Bootstraps bugabingas {0}.", emphasize_local("dorkfiles"));
553 log("{0}: java bootstripper.java [init-crypto|check|pre-commit|install-hooks|clean] [dotfiles root path]", emphasize_global("Usage"));
981 log("{0}: java bootstripper.java [bootstrap|link|init-crypto|setup-crypto|check|pre-commit|pre-push|install-hooks|clean] [dotfiles root path]", emphasize_global("Usage"));
554982 }
556984 static String emphasize_global(String message) {
561989 return "\033[3m" + message + "\033[0m";
562990 }
992 static void warn(String message) {
993 warnings.add(message);
994 }
996 static void error(String message) {
997 errors.add(message);
998 }
1000 static void print_attention(boolean fatal) {
1001 if (warnings.isEmpty() && errors.isEmpty())
1002 return;
1003 var color = fatal || !errors.isEmpty() ? "\033[31m" : "\033[33m";
1004 System.out.println();
1005 System.out.println(color + "ATTENTION");
1006 for (var warning : warnings)
1007 System.out.println("- " + warning);
1008 for (var error : errors)
1009 System.out.println("- " + error);
1010 System.out.println("\033[0m");
1011 }
5641013 static Throwable fail(String message, Object... arguments) {
565 log(message, arguments);
1014 error(format(message, arguments));
5661015 return fail();
5691018 static Throwable fail() {
1019 print_attention(true);
5701020 System.exit(-1);
5711021 return new Throwable("use 'throw fail()' for control flow");

bottom/bottom.toml

Modified

+141 / −141 text lines

1
2# This is a default config file for bottom. All of the settings are commented
3# out by default; if you wish to change them uncomment and modify as you see
4# fit.
5
6# This group of options represents a command-line flag/option. Flags explicitly
7# added when running (ie: btm -a) will override this config file if an option
8# is also set here.
9[flags]
10
11# Whether to hide the average cpu entry.
12#hide_avg_cpu = false
13
14# Whether to use dot markers rather than braille.
15dot_marker = true
16
17# The update rate of the application.
18rate = 350
19
20# Whether to put the CPU legend to the left.
21left_legend = true
22
23# Whether to set CPU% on a process to be based on the total CPU or just current usage.
24#current_usage = false
25
26# Whether to group processes with the same name together by default.
27group_processes = true
28
29# Whether to make process searching case sensitive by default.
30#case_sensitive = false
31
32# Whether to make process searching look for matching the entire word by default.
33#whole_word = false
34
35# Whether to make process searching use regex by default.
36#regex = false
37
38# Defaults to Celsius. Temperature is one of:
39#temperature_type = "k"
40#temperature_type = "f"
41#temperature_type = "c"
42#temperature_type = "kelvin"
43#temperature_type = "fahrenheit"
44temperature_type = "celsius"
45
46# The default time interval (in milliseconds).
47#default_time_value = 60000
48
49# The time delta on each zoom in/out action (in milliseconds).
50#time_delta = 15000
51
52# Override layout default widget
53#default_widget_type = "proc"
54#default_widget_count = 1
55
56# Use basic mode
57#basic = false
58
59# Use the old network legend style
60#use_old_network_legend = false
61
62# Remove space in tables
63#hide_table_gap = false
64
65##########################################################
66
67# These are all the components that support custom theming. Note that colour support
68# will, at the end of the day, depend on terminal support - for example, the
69# macOS default Terminal does NOT like custom colours and it will glitch out.
70[colors]
71
72# Represents the colour of table headers (processes, CPU, disks, temperature).
73#table_header_color="LightBlue"
74
75# Represents the colour of the label each widget has.
76widget_title_color = "Blue"
77
78# Represents the average CPU color.
79#avg_cpu_color="Red"
80
81# Represents the colour the core will use in the CPU legend and graph.
82#cpu_core_colors=["LightMagenta", "LightYellow", "LightCyan", "LightGreen", "LightBlue", "LightRed", "Cyan", "Green", "Blue", "Red"]
83
84# Represents the colour RAM will use in the memory legend and graph.
85ram_color = "LightGreen"
86
87# Represents the colour SWAP will use in the memory legend and graph.
88#swap_color="LightYellow"
89
90# Represents the colour rx will use in the network legend and graph.
91#rx_color="LightCyan"
92
93# Represents the colour tx will use in the network legend and graph.
94#tx_color="LightGreen"
95
96# Represents the colour of the border of unselected widgets.
97border_color = "Blue"
98
99# Represents the colour of the border of selected widgets.
100#highlighted_border_color="LightBlue"
101
102# Represents the colour of most text.
103text_color = "Blue"
104
105# Represents the colour of text that is selected.
106#selected_text_color="Black"
107
108# Represents the background colour of text that is selected.
109#selected_bg_color="LightBlue"
110
111# Represents the colour of the lines and text of the graph.
112graph_color = "Blue"
113
114# Represents the colours of the battery based on charge
115#battery_colors = ["red", "yellow", "yellow", "green", "green", "green"]
116
117
118##########################################################
119
120# Layout - layouts follow a pattern like this:
121# [[row]] represents a row in the application.
122# [[row.child]] represents either a widget or a column.
123# [[row.child.child]] represents a widget.
124#
125# All widgets must have the type value set to one of ["cpu", "mem", "proc", "net", "temp", "disk", "empty"].
126# All layout components have a ratio value - if this is not set, then it defaults to 1.
127
128# The default widget layout:
129[[row]]
130ratio = 60
131[[row.child]]
132type = "proc"
133default = true
134[[row]]
135ratio = 20
136[[row.child]]
137type = "cpu"
138[[row]]
139ratio = 10
140[[row.child]]
141type = "mem"
1
2# This is a default config file for bottom. All of the settings are commented
3# out by default; if you wish to change them uncomment and modify as you see
4# fit.
5
6# This group of options represents a command-line flag/option. Flags explicitly
7# added when running (ie: btm -a) will override this config file if an option
8# is also set here.
9[flags]
11# Whether to hide the average cpu entry.
12#hide_avg_cpu = false
14# Whether to use dot markers rather than braille.
15dot_marker = true
17# The update rate of the application.
18rate = 350
20# Whether to put the CPU legend to the left.
21left_legend = true
23# Whether to set CPU% on a process to be based on the total CPU or just current usage.
24#current_usage = false
26# Whether to group processes with the same name together by default.
27group_processes = true
29# Whether to make process searching case sensitive by default.
30#case_sensitive = false
32# Whether to make process searching look for matching the entire word by default.
33#whole_word = false
35# Whether to make process searching use regex by default.
36#regex = false
38# Defaults to Celsius. Temperature is one of:
39#temperature_type = "k"
40#temperature_type = "f"
41#temperature_type = "c"
42#temperature_type = "kelvin"
43#temperature_type = "fahrenheit"
44temperature_type = "celsius"
46# The default time interval (in milliseconds).
47#default_time_value = 60000
49# The time delta on each zoom in/out action (in milliseconds).
50#time_delta = 15000
52# Override layout default widget
53#default_widget_type = "proc"
54#default_widget_count = 1
56# Use basic mode
57#basic = false
59# Use the old network legend style
60#use_old_network_legend = false
62# Remove space in tables
63#hide_table_gap = false
65##########################################################
67# These are all the components that support custom theming. Note that colour support
68# will, at the end of the day, depend on terminal support - for example, the
69# macOS default Terminal does NOT like custom colours and it will glitch out.
70[colors]
72# Represents the colour of table headers (processes, CPU, disks, temperature).
73#table_header_color="LightBlue"
75# Represents the colour of the label each widget has.
76widget_title_color = "Blue"
78# Represents the average CPU color.
79#avg_cpu_color="Red"
81# Represents the colour the core will use in the CPU legend and graph.
82#cpu_core_colors=["LightMagenta", "LightYellow", "LightCyan", "LightGreen", "LightBlue", "LightRed", "Cyan", "Green", "Blue", "Red"]
84# Represents the colour RAM will use in the memory legend and graph.
85ram_color = "LightGreen"
87# Represents the colour SWAP will use in the memory legend and graph.
88#swap_color="LightYellow"
90# Represents the colour rx will use in the network legend and graph.
91#rx_color="LightCyan"
93# Represents the colour tx will use in the network legend and graph.
94#tx_color="LightGreen"
96# Represents the colour of the border of unselected widgets.
97border_color = "Blue"
99# Represents the colour of the border of selected widgets.
100#highlighted_border_color="LightBlue"
102# Represents the colour of most text.
103text_color = "Blue"
105# Represents the colour of text that is selected.
106#selected_text_color="Black"
108# Represents the background colour of text that is selected.
109#selected_bg_color="LightBlue"
111# Represents the colour of the lines and text of the graph.
112graph_color = "Blue"
114# Represents the colours of the battery based on charge
115#battery_colors = ["red", "yellow", "yellow", "green", "green", "green"]
118##########################################################
120# Layout - layouts follow a pattern like this:
121# [[row]] represents a row in the application.
122# [[row.child]] represents either a widget or a column.
123# [[row.child.child]] represents a widget.
124#
125# All widgets must have the type value set to one of ["cpu", "mem", "proc", "net", "temp", "disk", "empty"].
126# All layout components have a ratio value - if this is not set, then it defaults to 1.
128# The default widget layout:
129[[row]]
130ratio = 60
131[[row.child]]
132type = "proc"
133default = true
134[[row]]
135ratio = 20
136[[row.child]]
137type = "cpu"
138[[row]]
139ratio = 10
140[[row.child]]
141type = "mem"

claude/RTK.md

Modified

+29 / −29 text lines

1# RTK - Rust Token Killer
2
3**Usage**: Token-optimized CLI proxy (60-90% savings on dev operations)
4
5## Meta Commands (always use rtk directly)
6
7```bash
8rtk gain # Show token savings analytics
9rtk gain --history # Show command usage history with savings
10rtk discover # Analyze Claude Code history for missed opportunities
11rtk proxy <cmd> # Execute raw command without filtering (for debugging)
12```
13
14## Installation Verification
15
16```bash
17rtk --version # Should show: rtk X.Y.Z
18rtk gain # Should work (not "command not found")
19which rtk # Verify correct binary
20```
21
22⚠️ **Name collision**: If `rtk gain` fails, you may have reachingforthejack/rtk (Rust Type Kit) installed instead.
23
24## Hook-Based Usage
25
26All other commands are automatically rewritten by the Claude Code hook.
27Example: `git status` → `rtk git status` (transparent, 0 tokens overhead)
28
29Refer to CLAUDE.md for full command reference.
1# RTK - Rust Token Killer
2
3**Usage**: Token-optimized CLI proxy (60-90% savings on dev operations)
4
5## Meta Commands (always use rtk directly)
6
7```bash
8rtk gain # Show token savings analytics
9rtk gain --history # Show command usage history with savings
10rtk discover # Analyze Claude Code history for missed opportunities
11rtk proxy <cmd> # Execute raw command without filtering (for debugging)
12```
14## Installation Verification
16```bash
17rtk --version # Should show: rtk X.Y.Z
18rtk gain # Should work (not "command not found")
19which rtk # Verify correct binary
20```
22⚠️ **Name collision**: If `rtk gain` fails, you may have reachingforthejack/rtk (Rust Type Kit) installed instead.
24## Hook-Based Usage
26All other commands are automatically rewritten by the Claude Code hook.
27Example: `git status` → `rtk git status` (transparent, 0 tokens overhead)
29Refer to CLAUDE.md for full command reference.

claude/STATUSLINE.md

Added
new file mode 100644

+141 / −0 text lines

1# Claude Code Statusline
2
3Eine einzeilige, Statusline für Claude Code.
4Reines Node (stdlib), ein Renderer + ein Hook. Cross-Plattform (win/mac/linux).
5
6Beispielausgabe:
7
8```
9 RD-1950 · Opus 4.8 · xhigh · RD-1950 · 5h ██▋░░░░░ 33%·2h44m · 7d █▏░░░░░░ 14% · 🔥$26.68/hr · $0.499 $136.54Σ $486.13☾ · caveman:full
10```
12Segmente (v.l.n.r.): Verzeichnis · Modell · Effort · Git/JJ-Branch · 5h-Limit ·
137d-Limit · Burn-Rate ($/h) · Kosten (Turn / Session Σ / Monat ☾) · Caveman-Badge.
15---
17## Voraussetzungen
19| Dep | Pflicht | Zweck |
20|-----|---------|-------|
21| **Node ≥ 18** | ✅ | Laufzeit. Nur stdlib (`fs/os/path/crypto/child_process`), keine npm-Pakete. |
22| **Claude Code** | ✅ | Liefert den JSON-Payload (inkl. Kosten) via stdin. |
23| **git** oder **jj** | ➖ | Branch-Segment. Muss im `PATH` sein. Ohne → Segment entfällt. |
24| **Nerd Font** | ➖ (empfohlen) | Glyphen ``, Balken `█▏░`, Icons. Ohne → Tofu (`□`). |
25| **caveman-Plugin** | ➖ | Caveman-Badge. Ohne → Badge entfällt. |
27---
29## Dateien
31| Datei | Rolle |
32|-------|-------|
33| [`statusline.js`](./statusline.js) | Renderer. Liest stdin-JSON, gibt eine Zeile aus. |
34| [`cc-statusline-hook.js`](./cc-statusline-hook.js) | Hook. Setzt Turn-Marker + Workflow-Badge. |
36Beide nach `~/.claude/` kopieren oder symlinken:
38```bash
39ln -s "$PWD/statusline.js" ~/.claude/statusline.js
40ln -s "$PWD/cc-statusline-hook.js" ~/.claude/cc-statusline-hook.js
41```
43---
45## Installation
471. Node ≥ 18 installieren, im `PATH`.
482. Beide Dateien nach `~/.claude/` (s.o.).
493. `~/.claude/settings.json` ergänzen (Auszug unten).
504. Nerd Font im Terminal aktivieren (sonst Tofu statt Glyphen).
515. Claude Code neu starten.
53### settings.json (Auszug)
55```jsonc
56{
57 "statusLine": {
58 "type": "command",
59 "command": "node ~/.claude/statusline.js"
60 },
61 "hooks": {
62 // Turn-Marker: Basis für die "Turn"-Kosten (Δ seit letztem Prompt)
63 "UserPromptSubmit": [
64 {
65 "hooks": [
66 { "type": "command", "command": "node ~/.claude/cc-statusline-hook.js" }
67 ]
68 }
69 ],
70 // Workflow-Badge: NUR beim Workflow-Tool feuern (matcher scoped!)
71 "PreToolUse": [
72 {
73 "matcher": "Workflow",
74 "hooks": [
75 { "type": "command", "command": "node ~/.claude/cc-statusline-hook.js" }
76 ]
77 }
78 ]
79 }
80}
81```
83Der Hook ist **ein** Skript für beide Events; es verzweigt über `hook_event_name`.
85---
87## Funktionsweise
89- Claude Code spawnt `statusline.js` **pro Render** (frischer Prozess, Payload via
90 stdin, 300 ms Debounce, event-getriggert: neue Assistant-Nachricht, `/compact`,
91 Permission-/Vim-Mode-Wechsel). Per-Render-Spawn ist von der API erzwungen.
92- Renderer baut Segmente, jeweils eigener `try/catch` (ein Crash darf die Zeile nicht
93 leeren), und schreibt **ohne** Trailing-Newline.
94- **Turn-Kosten**: Der Hook legt bei `UserPromptSubmit` eine Marker-Datei
95 `~/.claude/.cc-turn-<session>` an. Der nächste Render liest sie, rebaselined den
96 Turn-Start und löscht den Marker.
97- **Workflow-Badge**: Bei `PreToolUse(Workflow)` schreibt der Hook eine selbst-
98 ablaufende Zeile nach `~/.claude/.cc-statusline-extra` (TTL 120 s), die der Renderer
99 rendert.
100- **Kosten-Ledger** `~/.claude/.cc-cost-ledger.json`: Turn / Session / Monat (monats-
101 übergreifend kumuliert). Idle-Renders (keine Kostenänderung) schreiben nicht.
102 Selbst-GC räumt alte `.cc-*.tmp` / `.cc-turn-*` (> 1 Tag) auf.
104---
106## Anpassung
108Tunables stehen oben in `statusline.js` im `CONFIG`-Block:
110| Schlüssel | Default | Bedeutung |
111|-----------|---------|-----------|
112| `sep` | `" · "` | Trenner zwischen Segmenten. |
113| `barWidth` | `8` | Zellen pro Usage-Balken. |
114| `costStyle` | `"icon"` | `"icon"` = helle `$Zahl` + gedämpftes Glyph; `"slash"` = `$x/turn`. |
115| `gitCacheTtlMs` | `8000` | Cache für `git status` (Spawn ist ~400 ms kalt auf win32). |
116| `contextWarnPct`/`CritPct` | `70`/`90` | Schwellen Kontext-Balken (gelb/rot). |
117| `usageWarnPct`/`CritPct` | `50`/`80` | Schwellen Rate-Limit-Balken. |
118| `burnWindowMs` | `10 min` | Fenster für die Burn-Rate ($/h). |
120---
122## Performance (win32)
124- Harte Untergrenze ist **nicht** das Skript, sondern der Node-Kaltstart:
125 `node -e 0` ≈ **120 ms** (Prozess-Spawn + V8-Init). Nicht durch Flags reduzierbar.
126- **< 100 ms ist mit Node unmöglich.** Nur ein kompiliertes Binary (Go/Rust ~10–20 ms)
127 unterbietet das — kostet aber Cross-Plattform (per-OS-Builds) + zweite Codebase.
128 Bun (win32) und Deno sind langsamer als Node; LLRT kann kein stdin lesen. → Node.
129- Die Bar ist asynchron und blockiert keine Eingabe; ~120–140 ms sind unsichtbar.
131---
133## Troubleshooting
135| Symptom | Ursache / Fix |
136|---------|---------------|
137| `□`/Tofu statt Glyphen | Nerd Font nicht aktiv im Terminal. |
138| Keine Kosten | Alte Claude-Code-Version ohne `cost` im Payload. |
139| Kein Branch-Segment | `git`/`jj` nicht im `PATH`, oder nicht in einem Repo. |
140| Keine Turn-Kosten | Hook nicht in `UserPromptSubmit` registriert. |
141| Statusline leer | `statusline.js` wirft beim Start — manuell testen: `echo '{}' \| node ~/.claude/statusline.js`. |

claude/settings.json

Modified

+13 / −41 text lines

11{
2 "cleanupPeriodDays": 99999,
3 "env": {
4 "CLAUDE_CODE_AUTO_COMPACT_WINDOW": "300000"
5 },
6 "attribution": {
7 "commit": "",
8 "pr": ""
9 },
210 "permissions": {
311 "defaultMode": "bypassPermissions"
412 },
3846 "type": "command",
3947 "command": "node ~/.claude/statusline.js"
4048 },
41 "enabledPlugins": {
42 "context7@claude-plugins-official": true,
43 "code-review@claude-plugins-official": true,
44 "code-simplifier@claude-plugins-official": true,
45 "github@claude-plugins-official": false,
46 "skill-creator@claude-plugins-official": true,
47 "feature-dev@claude-plugins-official": true,
48 "commit-commands@claude-plugins-official": true,
49 "atlassian@claude-plugins-official": true,
50 "jdtls-lsp@claude-plugins-official": true,
51 "remember@claude-plugins-official": false,
52 "caveman@caveman": true,
53 "superpowers@claude-plugins-official": true,
54 "frontend-design@claude-plugins-official": true,
55 "learning-output-style@claude-plugins-official": true,
56 "coderabbit@claude-plugins-official": true,
57 "desktop-commander@claude-plugins-official": true,
58 "code-modernization@claude-plugins-official": true
59 },
60 "extraKnownMarketplaces": {
61 "claude-code-plugins": {
62 "source": {
63 "source": "github",
64 "repo": "anthropics/claude-code"
65 }
66 },
67 "caveman": {
68 "source": {
69 "source": "github",
70 "repo": "JuliusBrussee/caveman"
71 }
72 }
73 },
74 "effortLevel": "xhigh",
75 "advisorModel": "opus",
49 "enabledPlugins": {},
50 "outputStyle": "Concise",
7651 "promptSuggestionEnabled": false,
52 "awaySummaryEnabled": false,
7753 "tui": "fullscreen",
7854 "skipDangerousModePermissionPrompt": true,
7955 "theme": "auto",
8157 "verbose": true,
8258 "inputNeededNotifEnabled": true,
8359 "agentPushNotifEnabled": true,
84 "skipAutoPermissionPrompt": true,
85 "cleanupPeriodDays": 99999,
86 "env": {
87 "CLAUDE_CODE_AUTO_COMPACT_WINDOW": "300000"
88 }
89}
60 "switchModelsOnFlag": false
61}No final newline

claude/statusline.js

Modified

+192 / −84 text lines

11#!/usr/bin/env node
22// Claude Code statusline (Node). Reads session JSON from stdin, prints one line.
33//
4// <dir> · <model> · <effort> · <git|jj> · <5h bar> · <7d bar> · <cost> · <cm> · <extra>
4// <dir> · <model> · <effort> · <git|jj> · <ctx bar> · <5h bar> · <7d bar> · <burn> · <cost> · <caveman> · <extra>
55//
66// Cost shows turn (Δ since last user prompt), session, and month-to-date.
77// Month-to-date is a cross-session ledger: each render adds the session's new
2121// ─── CONFIG ──────────────────────────────────────────────────────────────────
2222const CONFIG = {
23 sep: " · ", // segment padding
23 sep: " · ", // segment padding (single-space around the dot — tight)
2424 barWidth: 8, // usage bar cells
2525 contextWarnPct: 70,
2626 contextCritPct: 90,
2727 usageAlways: true,
2828 usageWarnPct: 50,
2929 usageCritPct: 80,
30 costStyle: "icon", // "slash" → $0.15/turn | "icon" → ⟳$0.15
31 gitCacheTtlMs: 3000,
31 costStyle: "icon", // "slash" → $0.15/turn | "icon" → bright $0.15 + dim trailing glyph
32 gitCacheTtlMs: 8000, // git status spawn is ~400ms cold on win32 — cache harder
3233 extraTtlMs: 120000,
3334 cmdTimeoutMs: 2500,
3435 ledgerPruneDays: 40,
3637 burnWindowMs: 10 * 60000, // sliding window of cost samples to rate over
3738 burnMinSpanMs: 60000, // need ≥ this much elapsed inside window before showing
3839 burnMaxSamples: 60, // cap stored samples per session (keeps ledger small)
40 // burn-rate color: truecolor gradient stops ($/hr). grounded in this ledger
41 // (median ~$9.5, p90 ~$19, peak intervals ~$50) + Opus 4.8 pricing ($5/$25/MTok):
42 // ~$8 calm single-stream · ~$18 heavy/active · ~$36+ parallel-agent burn.
43 // smooth lerp between stops — these are gradient anchors, not hard tiers.
44 burnCool: 8, // ≤ this → pure green (calm)
45 burnWarn: 18, // amber midpoint (≈ p90 — notably elevated)
46 burnHot: 36, // ≥ this → pure red (HOT — deep tail)
47 burnBold: 28, // ≥ this → bold weight (visual alarm)
3948};
4150const claudeDir = process.env.CLAUDE_CONFIG_DIR || path.join(os.homedir(), ".claude");
5261 blue: (s) => `${E}[34m${s}${R}`,
5362 dim: (s) => `${E}[2m${s}${R}`,
5463 white: (s) => `${E}[97m${s}${R}`,
55 orange: (s) => `${E}[38;5;172m${s}${R}`,
64 accent: (s) => `${E}[93m${s}${R}`, // bright yellow — warm badge accent (no orange in the 16-index palette)
5665};
57const pctColor = (p, warn, crit) => (p >= crit ? c.red : p >= warn ? c.yellow : c.green);
59const PARTIALS = ["", "▏", "▎", "▍", "▌", "▋", "▊", "▉"];
60function bar(pct, width, color) {
61 let p = Math.max(0, Math.min(100, pct));
62 let filled = (p / 100) * width;
63 let full = Math.floor(filled);
64 let pIdx = Math.round((filled - full) * 8);
65 if (pIdx === 8) {
66 full += 1;
67 pIdx = 0;
68 }
69 if (full > width) full = width;
70 const partial = pIdx > 0 && full < width ? PARTIALS[pIdx] : "";
71 const used = full + (partial ? 1 : 0);
72 const empty = Math.max(0, width - used);
73 return color("█".repeat(full) + partial) + c.dim("░".repeat(empty));
67const lerp = (a, b, t) => Math.round(a + (b - a) * t); // single channel
68const mix = (from, to, t) => from.map((v, i) => lerp(v, to[i], t)); // 3-channel lerp
70// Shared color basis. Base colors are ANSI 16-index (38;5;N, N<16) so the terminal THEME
71// remaps them on dark↔light. A gradient between two indices can't itself be an index, so
72// it's lerp'd in truecolor from each index's reference RGB — only the transient middle of
73// a ramp is non-adaptive; every anchor follows the theme.
74const IDX = { calm: 12, warn: 13, crit: 9 }; // bars: blue → magenta → red (all theme-adaptive)
75const BURN = { cool: 2, warm: 3, hot: 1 }; // 🔥 burn: green → yellow → red (kept distinct from bars)
76const IDX_RGB = { 1: [205, 0, 0], 2: [0, 205, 0], 3: [205, 205, 0], 9: [255, 0, 0], 13: [255, 0, 255] }; // xterm refs — lerp blends only
77const sgr = (code, s) => `${E}[${code}m${s}${R}`;
78const idxColor = (n, bold) => (s) => sgr(`${bold ? "1;" : ""}38;5;${n}`, s); // adaptive anchor
79const rgbColor = (rgb, bold) => (s) => sgr(`${bold ? "1;" : ""}38;2;${rgb[0]};${rgb[1]};${rgb[2]}`, s); // blend
81// 🔥 burn-rate color: green (calm) → yellow → red (HOT, bold past burnBold). anchors are
82// indices; the warming middle is a truecolor blend. render gates on burnRate>0 (no NaN).
83function burnColor(rate, label) {
84 const { burnCool, burnWarn, burnHot, burnBold } = CONFIG;
85 const bold = rate >= burnBold;
86 if (rate <= burnCool) return idxColor(BURN.cool, bold)(label);
87 if (rate >= burnHot) return idxColor(BURN.hot, bold)(label);
88 const rgb =
89 rate <= burnWarn
90 ? mix(IDX_RGB[BURN.cool], IDX_RGB[BURN.warm], (rate - burnCool) / (burnWarn - burnCool))
91 : mix(IDX_RGB[BURN.warm], IDX_RGB[BURN.hot], (rate - burnWarn) / (burnHot - burnWarn));
92 return rgbColor(rgb, bold)(label);
93}
95const trough = idxColor(IDX.calm, false); // empty cells — same adaptive index as calm, ░ glyph separates
96// severity → colorizer. all three anchors are ANSI indices (theme-adaptive); only the
97// strictly-between warn→crit blend is truecolor (lerp of the two anchors' reference RGB).
98function meterColor(pct, warn, crit) {
99 if (pct < warn) return idxColor(IDX.calm, false); // calm — blue
100 if (pct >= crit) return idxColor(IDX.crit, true); // crit — red + bold
101 const t = (pct - warn) / (crit - warn);
102 if (t === 0) return idxColor(IDX.warn, false); // exactly at warn — yellow
103 return rgbColor(mix(IDX_RGB[IDX.warn], IDX_RGB[IDX.crit], t), false); // smooth blend
104}
105// fill bar with shade-density leading edge (░▒▓); color from meterColor (index-based).
106function bar(pct, width, warn, crit) {
107 const p = Math.max(0, Math.min(100, pct));
108 const filled = (p / 100) * width;
109 const full = Math.min(width, Math.floor(filled));
110 const frac = filled - full;
111 const tip = frac > 0 && full < width ? (frac < 1 / 3 ? "░" : frac < 2 / 3 ? "▒" : "▓") : "";
112 const empty = Math.max(0, width - full - (tip ? 1 : 0));
113 return meterColor(p, warn, crit)("█".repeat(full) + tip) + trough("░".repeat(empty));
75115const money = (n) => (n < 1 ? n.toFixed(3) : n.toFixed(2));
117// label + 8-cell bar + pct% — shared by ctx and usage. severity drives color (subtle→loud).
118const meter = (label, pct, warn, crit) =>
119 `${c.dim(label)} ${bar(pct, CONFIG.barWidth, warn, crit)} ${meterColor(pct, warn, crit)(pct + "%")}`;
120// drop control chars (ANSI-injection / newline guard) before printing untrusted file text.
121const stripCtl = (s) => s.replace(/[\x00-\x1F]/g, "");
123// ─── crash-safe IO helpers (all swallow — a failed read/write must never blank the bar) ──
124// atomic write: tmp + rename so a concurrent reader never sees a half-written file.
125function atomicWrite(file, data) {
126 try {
127 const tmp = `${file}.${process.pid}.tmp`;
128 fs.writeFileSync(tmp, data);
129 fs.renameSync(tmp, file);
130 } catch {}
131}
132// read a small plain file as text, or null. rejects symlinks (don't follow a planted
133// link out of the config dir) and oversized files; lstat keeps the symlink unfollowed.
134function readSmallFile(file, maxSize) {
135 try {
136 const st = fs.lstatSync(file);
137 if (st.isSymbolicLink() || st.size > maxSize) return null;
138 return fs.readFileSync(file, "utf8");
139 } catch {
140 return null;
141 }
142}
143// parse a JSON file, or null on missing/corrupt.
144function readJson(file) {
145 try {
146 return JSON.parse(fs.readFileSync(file, "utf8"));
147 } catch {
148 return null;
149 }
150}
77152// ─── stdin ───────────────────────────────────────────────────────────────────
78153let d = {};
79154try {
87162const push = (s) => {
88163 if (s) parts.push(s);
89164};
165const cwd = d?.workspace?.current_dir || d?.cwd;
91167// ─── 1. dir ──────────────────────────────────────────────────────────────────
92168try {
93 const cwd = d?.workspace?.current_dir || d?.cwd;
94169 if (cwd) push(c.cyan(path.basename(cwd) || cwd));
95170} catch {}
97172// ─── 2. model ──────────────────────────────────────────────────────────────────
98173try {
99 if (d?.model?.display_name) push(c.magenta(d.model.display_name));
174 // strip the " (1M context)" / any trailing parenthetical — keep just "Opus 5.5"
175 if (d?.model?.display_name) push(c.magenta(d.model.display_name.replace(/\s*\([^)]*\)\s*$/, "")));
100176} catch {}
102178// ─── 3. effort / thinking ──────────────────────────────────────────────────────
105181 if (lvl) {
106182 const on = d?.thinking?.enabled !== false;
107183 const col = lvl === "max" || lvl === "xhigh" ? c.magenta : lvl === "high" ? c.blue : c.dim;
108 push(on ? col(`⚡${lvl}`) : c.dim(`⚡${lvl}`));
184 push(on ? col(lvl) : c.dim(lvl)); // no ⚡ glyph — level word alone
109185 }
110186} catch {}
112188// ─── 4. git / jj (smart-cached) ────────────────────────────────────────────────
113push(gitOrJjSegment(d?.workspace?.current_dir || d?.cwd));
189push(gitOrJjSegment(cwd));
115191// ─── 5. context (gated) ────────────────────────────────────────────────────────
116192try {
193 // used_percentage is model-aware (relative to context_window_size: 1M for extended models).
194 // Do NOT use exceeds_200k_tokens — it's a fixed 200k threshold, so it falsely reads 100%
195 // on a 1M-window model once a long session passes 200k tokens.
117196 const cw = d?.context_window || {};
118197 let pct = cw.used_percentage;
119198 if (pct == null && cw.context_window_size && cw.total_input_tokens != null) {
120199 pct = (cw.total_input_tokens / cw.context_window_size) * 100;
121200 }
122 const exceeds = d?.exceeds_200k_tokens === true;
123 if (exceeds || (pct != null && pct >= CONFIG.contextWarnPct)) {
124 const shown = pct != null ? Math.round(pct) : 100;
125 const col = exceeds || shown >= CONFIG.contextCritPct ? c.red : c.yellow;
126 push(`${c.dim("ctx")} ${bar(shown, CONFIG.barWidth, col)} ${col(shown + "%")}`);
201 if (pct != null) {
202 let seg = meter("ctx", Math.round(pct), CONFIG.contextWarnPct, CONFIG.contextCritPct);
203 // absolute size helps on 1M windows, where 10% is already 100k tokens
204 const tok = cw.total_input_tokens ?? (cw.context_window_size ? (pct / 100) * cw.context_window_size : null);
205 if (tok != null) seg += c.dim("·" + fmtTokens(tok));
206 push(seg);
127207 }
128208} catch {}
135215 if (win && typeof win.used_percentage === "number") {
136216 const p = Math.round(win.used_percentage);
137217 if (CONFIG.usageAlways || p >= CONFIG.usageWarnPct) {
138 const col = pctColor(p, CONFIG.usageWarnPct, CONFIG.usageCritPct);
139 let seg = `${c.dim(label)} ${bar(p, CONFIG.barWidth, col)} ${col(p + "%")}`;
218 let seg = meter(label, p, CONFIG.usageWarnPct, CONFIG.usageCritPct);
140219 // resets_at is UNIX EPOCH SECONDS — ×1000 to compare with Date.now() (ms)
141220 if (withReset && typeof win.resets_at === "number") {
142221 const left = win.resets_at * 1000 - Date.now();
158237 if (typeof total === "number") {
159238 const { turn, month, burnRate } = updateLedger(sid, total);
160239 // 🔥 burn rate: own segment, before the cost cluster (matches bars · 🔥 · cost)
161 if (burnRate > 0) push(c.orange(`🔥$${burnRate.toFixed(2)}/hr`));
162 // icon: semantic glyph (⟳ turn / Σ session / ☾ month). slash: <num>/<type>.
163 const fmt = (n, type, icon, color) =>
164 CONFIG.costStyle === "icon" ? color(`${icon}$${money(n)}`) : color(`$${money(n)}/${type}`);
240 if (burnRate > 0) push(burnColor(burnRate, `$${burnRate.toFixed(2)}/hr`));
241 // icon style: bright $number (emphasis) + dim trailing glyph (muted icon).
242 // turn has no glyph (bare $num); session Σ / month ☾. slash: $num/type.
243 const fmt = (n, type, icon) =>
244 CONFIG.costStyle === "icon"
245 ? c.white(`$${money(n)}`) + (icon ? c.dim(icon) : "")
246 : c.white(`$${money(n)}/${type}`);
165247 const seg = [];
166 if (turn > 0) seg.push(fmt(turn, "turn", "⟳", c.white));
167 seg.push(fmt(total, "session", "Σ", c.dim));
168 if (month > 0) seg.push(fmt(month, "month", "☾", c.dim));
248 if (turn > 0) seg.push(fmt(turn, "turn", ""));
249 seg.push(fmt(total, "session", "Σ"));
250 // month only adds information once other sessions have contributed to it
251 if (month > 0 && money(month) !== money(total)) seg.push(fmt(month, "month", "☾"));
169252 push(seg.join(" "));
170253 }
171254} catch {}
176259// ─── 9. extra badges (hooks: workflow, …) ──────────────────────────────────────
177260try {
178 const f = path.join(claudeDir, ".cc-statusline-extra");
179 const st = fs.lstatSync(f);
180 if (!st.isSymbolicLink() && st.size <= 4096) {
261 const content = readSmallFile(path.join(claudeDir, ".cc-statusline-extra"), 4096);
262 if (content) {
181263 const now = Date.now();
182 for (const line of fs.readFileSync(f, "utf8").split(/\r?\n/)) {
264 for (const line of content.split(/\r?\n/)) {
183265 const i = line.indexOf("|");
184266 if (i <= 0) continue;
185267 const ts = Number(line.slice(0, i));
186268 if (!Number.isFinite(ts) || now - ts > CONFIG.extraTtlMs) continue;
187 const text = line.slice(i + 1).replace(/[\x00-\x1F]/g, "").slice(0, 60);
188 if (text) push(c.orange(text));
269 const text = stripCtl(line.slice(i + 1)).slice(0, 60);
270 if (text) push(c.accent(text));
189271 }
190272 }
191273} catch {}
206288 const now = Date.now();
207289 const mk = monthKey();
208290 let L = { month: mk, monthTotal: 0, sessions: {} };
209 try {
210 L = JSON.parse(fs.readFileSync(file, "utf8"));
211 } catch {}
291 const parsed = readJson(file);
292 if (parsed) L = parsed;
212293 if (!L.sessions) L.sessions = {};
294 let dirty = false; // persist (disk write) only when something material changed
214296 // New month → reset the bucket, KEEP per-session baselines so a session that
215297 // straddles midnight only contributes its post-boundary spend.
216298 if (L.month !== mk) {
217299 L.month = mk;
218300 L.monthTotal = 0;
301 dirty = true;
219302 }
221304 // Prune stale sessions.
233316 if (fs.existsSync(marker)) {
234317 s.turnStart = total;
235318 fs.unlinkSync(marker);
319 dirty = true;
236320 }
237321 } catch {}
323 // Session cost went backwards (counter restarted, e.g. on resume): rebaseline,
324 // otherwise new spend is silently dropped until it exceeds the old high-water mark.
325 if (total < (s.total ?? 0)) {
326 s.total = 0;
327 s.turnStart = Math.min(s.turnStart ?? total, total);
328 s.samples = [];
329 dirty = true;
330 }
239332 // Month bucket gets only the new spend since this session was last seen.
240333 const delta = total - (s.total ?? 0);
241 if (delta > 0) L.monthTotal = (L.monthTotal || 0) + delta;
334 if (delta > 0) {
335 L.monthTotal = (L.monthTotal || 0) + delta;
336 dirty = true;
337 }
243339 const turn = Math.max(0, total - (s.turnStart ?? total));
244 s.total = total;
245 s.ts = now;
247 // Timestamped cost samples for the burn rate. Append, drop anything older than
248 // the window (so idle time falls off instead of dragging the rate down), cap.
341 // Burn-rate samples: only record a new (ts,total) when spend actually moved.
342 // Idle re-renders carry no new info and would force a needless disk write.
249343 if (!Array.isArray(s.samples)) s.samples = [];
250 s.samples.push([now, total]);
344 if (delta > 0) {
345 s.total = total;
346 s.ts = now;
347 s.samples.push([now, total]);
348 if (s.samples.length > CONFIG.burnMaxSamples) s.samples = s.samples.slice(-CONFIG.burnMaxSamples);
349 }
350 // Prune the window in-memory every render (cheap, no disk) so even an idle
351 // render shows a current-window rate rather than a stale one.
251352 const wcut = now - CONFIG.burnWindowMs;
252353 s.samples = s.samples.filter((p) => p[0] >= wcut);
253 if (s.samples.length > CONFIG.burnMaxSamples) s.samples = s.samples.slice(-CONFIG.burnMaxSamples);
254354 const burnRate = computeBurnRate(s.samples);
256356 L.sessions[sid] = s;
258 try {
259 const tmp = `${file}.${process.pid}.tmp`;
260 fs.writeFileSync(tmp, JSON.stringify(L));
261 fs.renameSync(tmp, file);
262 } catch {}
358 // Persist only when something changed — skips stringify+write+rename (the bulk
359 // of this function's cost) on the common idle re-render path.
360 if (dirty) {
361 atomicWrite(file, JSON.stringify(L));
362 // Opportunistic GC (write-path only, so throttled to active turns): cancelled
363 // renders leave `.cc-*.tmp` atomic-write orphans; ended sessions leave
364 // `.cc-turn-*` markers. Sweep our own debris older than a day.
365 try {
366 const stale = now - 864e5;
367 for (const f of fs.readdirSync(claudeDir)) {
368 if (!((f.startsWith(".cc-") && f.endsWith(".tmp")) || f.startsWith(".cc-turn-"))) continue;
369 const fp = path.join(claudeDir, f);
370 try {
371 if (fs.statSync(fp).mtimeMs < stale) fs.unlinkSync(fp);
372 } catch {}
373 }
374 } catch {}
375 }
264377 return { turn, month: L.monthTotal || 0, burnRate };
282395 return (spend / span) * 3600000; // $/ms → $/hr
398// Compact token count: "850", "42k", "1.2M".
399function fmtTokens(n) {
400 if (n >= 1e6) return `${(n / 1e6).toFixed(1).replace(/\.0$/, "")}M`;
401 if (n >= 1e3) return `${Math.round(n / 1e3)}k`;
402 return `${Math.round(n)}`;
403}
285405// Compact duration: "2h45m" (minutes zero-padded) above an hour, else "45m".
286406function fmtDuration(ms) {
287407 const m = Math.floor(ms / 60000);
316436 if (!repo) return "";
317437 const key = crypto.createHash("sha1").update(repo.kind + ":" + repo.root).digest("hex").slice(0, 12);
318438 const cacheFile = path.join(os.tmpdir(), `cc-statusline-${key}.json`);
319 try {
320 const o = JSON.parse(fs.readFileSync(cacheFile, "utf8"));
321 if (Date.now() - o.ts < CONFIG.gitCacheTtlMs) return o.text;
322 } catch {}
439 const cached = readJson(cacheFile);
440 if (cached && Date.now() - cached.ts < CONFIG.gitCacheTtlMs) return cached.text;
323441 let text = "";
324442 try {
325443 text = repo.kind === "jj" ? jjSegment(repo.root) : gitSegment(repo.root);
326444 } catch {
327445 text = "";
328446 }
329 try {
330 const tmp = `${cacheFile}.${process.pid}.tmp`;
331 fs.writeFileSync(tmp, JSON.stringify({ ts: Date.now(), text }));
332 fs.renameSync(tmp, cacheFile);
333 } catch {}
447 atomicWrite(cacheFile, JSON.stringify({ ts: Date.now(), text }));
334448 return text;
356470 }
357471 if (branch === "(detached)") branch = "detached";
358472 const col = dirty > 0 ? c.yellow : c.green;
359 let s = col(`⎇${branch}`);
473 let s = col(` ${branch}`); // U+E0A0 powerline branch glyph (Nerd Font)
360474 if (dirty > 0) s += c.yellow(`●${dirty}`);
361475 if (ahead) s += c.cyan(`↑${ahead}`);
362476 if (behind) s += c.cyan(`↓${behind}`);
380494// ════════════════════════════════════════════════════════════════════════════
381// caveman badge — terse: full→"cm", else "cm:<first-letter>"
495// caveman badge — "caveman:<mode>" (+ optional savings suffix)
382496// ════════════════════════════════════════════════════════════════════════════
383497function cavemanBadge() {
384498 try {
385 const flag = path.join(claudeDir, ".caveman-active");
386 const st = fs.lstatSync(flag);
387 if (st.isSymbolicLink() || st.size > 64) return "";
388 let mode = (fs.readFileSync(flag, "utf8").split(/\r?\n/)[0] ?? "")
499 const raw = readSmallFile(path.join(claudeDir, ".caveman-active"), 64);
500 if (raw == null) return "";
501 let mode = (raw.split(/\r?\n/)[0] ?? "")
389502 .trim()
390503 .toLowerCase()
391504 .replace(/[^a-z0-9-]/g, "");
395508 "commit", "review", "compress",
396509 ]);
397510 if (!valid.has(mode) || mode === "off") return "";
398 let out = c.orange(mode || "full");
511 let out = c.dim("caveman:") + c.accent(mode); // muted label, bright value
399512 if (process.env.CAVEMAN_STATUSLINE_SAVINGS !== "0") {
400 try {
401 const sf = path.join(claudeDir, ".caveman-statusline-suffix");
402 const sst = fs.lstatSync(sf);
403 if (!sst.isSymbolicLink() && sst.size <= 64) {
404 const sv = fs.readFileSync(sf, "utf8").replace(/[\x00-\x1F]/g, "").trimEnd();
405 if (sv) out += " " + c.orange(sv);
406 }
407 } catch {}
513 const sraw = readSmallFile(path.join(claudeDir, ".caveman-statusline-suffix"), 64);
514 const sv = sraw && stripCtl(sraw).trimEnd();
515 if (sv) out += " " + c.accent(sv);
408516 }
409517 return out;
410518 } catch {

clipse/config.json

Deleted
deleted file mode 100644

+0 / −35 text lines

1{
2 "allowDuplicates": false,
3 "historyFile": "clipboard_history.json",
4 "maxHistory": 100,
5 "logFile": "clipse.log",
6 "themeFile": "nugu.json",
7 "tempDir": "tmp_files",
8 "keyBindings": {
9 "choose": "enter",
10 "clearSelected": "S",
11 "down": "down",
12 "end": "end",
13 "filter": "/",
14 "home": "home",
15 "more": "?",
16 "nextPage": "right",
17 "prevPage": "left",
18 "preview": " ",
19 "quit": "q",
20 "remove": "x",
21 "selectDown": "ctrl+down",
22 "selectSingle": "s",
23 "selectUp": "ctrl+up",
24 "togglePin": "p",
25 "togglePinned": "tab",
26 "up": "up",
27 "yankFilter": "ctrl+s"
28 },
29 "imageDisplay": {
30 "type": "kitty",
31 "scaleX": 9,
32 "scaleY": 9,
33 "heightCut": 2
34 }
35}

clipse/nugu.json

Deleted
deleted file mode 100644

+0 / −28 text lines

1{
2 "useCustomTheme": true,
3 "TitleFore": "#ffffff",
4 "TitleBack": "#6F4CBC",
5 "TitleInfo": "#3498db",
6 "NormalTitle": "#ffffff",
7 "DimmedTitle": "#808080",
8 "SelectedTitle": "#FF69B4",
9 "NormalDesc": "#808080",
10 "DimmedDesc": "#808080",
11 "SelectedDesc": "#FF69B4",
12 "StatusMsg": "#2ecc71",
13 "PinIndicatorColor": "#FFD700",
14 "SelectedBorder": "#3498db",
15 "SelectedDescBorder": "#3498db",
16 "FilteredMatch": "#ffffff",
17 "FilterPrompt": "#2ecc71",
18 "FilterInfo": "#3498db",
19 "FilterText": "#ffffff",
20 "FilterCursor": "#FFD700",
21 "HelpKey": "#999999",
22 "HelpDesc": "#808080",
23 "PageActiveDot": "#3498db",
24 "PageInactiveDot": "#808080",
25 "DividerDot": "#3498db",
26 "PreviewedText": "#ffffff",
27 "PreviewBorder": "#3498db"
28}

codex/config.toml

Modified

+31 / −26 text lines

1approval_policy = "never"
2sandbox_mode = "danger-full-access"
3permission_profile = "disabled"
4service_tier = "fast"
15project_doc_fallback_filenames = ["CLAUDE.md"]
3[projects."/home/okr"]
4trust_level = "trusted"
7[windows]
8sandbox = "elevated"
6[plugins."atlassian-rovo@openai-curated"]
7enabled = true
10[notice]
11hide_rate_limit_model_nudge = true
12hide_full_access_warning = true
9[plugins."build-web-apps@openai-curated"]
10enabled = true
14[tui]
15theme = "ansi"
16status_line = [
17 "model-with-reasoning",
18 "current-dir",
19 "project-name",
20 "git-branch",
21 "pull-request-number",
22 "branch-changes",
23 "context-used",
24 "five-hour-limit",
25 "weekly-limit",
26 "context-window-size",
27 "fast-mode",
28 "thread-title",
29 "task-progress",
30]
31status_line_use_colors = true
32session_picker_view = "comfortable"
33screen_reader_detection_done = true
12[plugins."build-web-data-visualization@openai-curated"]
13enabled = true
15[plugins."codex-security@openai-curated"]
16enabled = true
18[plugins."github@openai-curated"]
19enabled = true
21[plugins."gmail@openai-curated"]
22enabled = true
24[plugins."google-calendar@openai-curated"]
25enabled = true
27[plugins."google-drive@openai-curated"]
28enabled = true
30[plugins."superpowers@openai-curated"]
31enabled = true
35[shell_environment_policy]
36inherit = "core"

containers/systemd/einordner-stalwart-e2e.container

Deleted
deleted file mode 100644

+0 / −30 text lines

1# Podman Quadlet template for einordner Stalwart E2E.
2# Install with: just e2e-install
3# Generated unit: einordner-stalwart-e2e.service (systemd --user)
4
5[Unit]
6Description=einordner Stalwart E2E mail server
7Documentation=https://github.com/stalwartlabs/mail-server
8After=network-online.target
9Wants=network-online.target
11[Container]
12Image=docker.io/stalwartlabs/stalwart:latest
13ContainerName=einordner-stalwart-e2e
14Environment=STALWART_RECOVERY_ADMIN=admin:changeme
15PublishPort=127.0.0.1:8080:8080
16PublishPort=127.0.0.1:1025:1025
17PublishPort=127.0.0.1:1143:1143
18PublishPort=127.0.0.1:4190:4190
19Volume=/home/me/.local/state/einordner/e2e/stalwart/config/config.json:/etc/stalwart/config.json:ro,Z
20Volume=einordner-stalwart-e2e-data:/data
21WorkingDir=/data
22Exec=-c /etc/stalwart/config.json
24[Service]
25Restart=on-failure
26RestartSec=2
27TimeoutStartSec=120
29[Install]
30WantedBy=default.target

desktop.symlinks

Modified

+91 / −31 text lines

1forgejo-cli
2~/.config/forgejo-cli
3
41pi
52~/.pi
4dprint/dprint.jsonc
5~/.config/dprint/dprint.jsonc
6
7claude/settings.json
8~/.claude/settings.json
9
10claude/statusline.js
11~/.claude/statusline.js
13claude/cc-statusline-hook.js
14~/.claude/cc-statusline-hook.js
16claude/CLAUDE.md
17~/.claude/CLAUDE.md
19claude/RTK.md
20~/.claude/RTK.md
22paru/paru.conf
23~/.config/paru/paru.conf
25zed
26~/.config/zed
28jj
29~/.config/jj
31glow
32~/.config/glow
34mise
35~/.config/mise
737yazi
838~/.config/yazi
10Notes
11~/Notes
1340git/gitconfig
1441~/.config/git/config
1643git/gitattributes
1744~/.config/git/gitattributes
19git/ignore
20~/.config/git/ignore
46git/allowed_signers
47~/.config/git/allowed_signers
2249git/gitconfig.bugabinga
2350~/.config/git/.gitconfig.include
52git/ignore
53~/.config/git/ignore
2555gh
2656~/.config/gh
58forgejo-cli
59~/.config/forgejo-cli
2861cargo/config.toml
2962~/.cargo/config.toml
4073bash
4174~/.config/bash
76chawan
77~/.config/chawan
4379MangoHud
4480~/.config/MangoHud
5288containers
5389~/.config/containers
55jj
56~/.config/jj
58glow
59~/.config/glow
61mise
62~/.config/mise
64systemd/user/work.slice
65~/.config/systemd/user/work.slice
6791mpv
6892~/.config/mpv
88112wezterm
89113~/.config/wezterm
91tmux
92~/.config/tmux
94ghostty
95~/.config/ghostty
97115ssh
98116~/.ssh
103121neovide
104122~/.config/neovide
106zed
107~/.config/zed
109124niri
110125~/.config/niri
127nugu
128~/.config/nugu
130niri/niri-uwsm.desktop
131~/.local/share/wayland-sessions/niri-uwsm.desktop
112133fontconfig
113134~/.config/fontconfig
115136environment.d/50-niri-wayland.conf
116137~/.config/environment.d/50-niri-wayland.conf
139quickshell/nuguland
140~/.config/quickshell/nuguland
142systemd/user/quickshell.service
143~/.config/systemd/user/quickshell.service
145systemd/user/quickshell.service
146~/.config/systemd/user/graphical-session.target.wants/quickshell.service
148systemd/user/session-graphical.slice.d/10-desktop-resources.conf
149~/.config/systemd/user/session-graphical.slice.d/10-desktop-resources.conf
151systemd/user/app-graphical.slice.d/10-desktop-resources.conf
152~/.config/systemd/user/app-graphical.slice.d/10-desktop-resources.conf
154systemd/user/background-graphical.slice.d/10-desktop-resources.conf
155~/.config/systemd/user/background-graphical.slice.d/10-desktop-resources.conf
118157aerc
119158~/.config/aerc
124163pueue/pueued.service
125164~/.config/systemd/user/pueued.service
127wezterm/systemd/wezterm-mux-server.service
128~/.config/systemd/user/wezterm-mux-server.service
166pueue/pueued.service
167~/.config/systemd/user/default.target.wants/pueued.service
130169psd/psd.conf
131170~/.config/psd/psd.conf
172systemd/user/psd.service
173~/.config/systemd/user/psd.service
175systemd/user/psd.service
176~/.config/systemd/user/default.target.wants/psd.service
178systemd/user/work.slice
179~/.config/systemd/user/work.slice
181xdg/mimeapps.list
182~/.config/mimeapps.list
184xdg/applications/mpv-tui.desktop
185~/.local/share/applications/mpv-tui.desktop
187xdg/bin
188~/.local/override/bin
190environment.d/60-xdg-open-gio.conf
191~/.config/environment.d/60-xdg-open-gio.conf

docs/superpowers/plans/2026-05-30-yazi-nugu-dotfiles.md

Deleted
deleted file mode 100644

+0 / −941 text lines

1# Yazi Nugu Dotfiles Implementation Plan
2
3> **For agentic workers:** REQUIRED SUB-SKILL: Use /skill:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
4
5**Goal:** Build a dotfiles-managed Yazi config that uses generated Nugu flavors, tasteful Yazi-native key overrides, and a small managed plugin set.
6
7**Architecture:** Add `yazi/` as a managed dotfiles directory, generated Nugu dark/light Yazi flavors from `nugu/yazi.nu`, and minimal Yazi TOML/Lua config. Plugins are installed and locked by `ya pkg`; installed plugin directories are ignored and not vendored.
8
9**Tech Stack:** Yazi 26.5.6, `ya pkg`, Nushell, Just, TOML, Lua, dotfiles symlink manifests.
11**Roadmap:** None
13**Phase:** Single-plan implementation
15---
17## File structure
19Create or modify these files:
21- Create `nugu/yazi.nu`: generator from Nugu semantic palette to Yazi flavor TOML.
22- Modify `nugu/justfile`: add `yazi` recipe and include it in `install`.
23- Create `yazi/theme.toml`: selects generated Nugu flavors.
24- Create `yazi/yazi.toml`: minimal manager/open/preview/plugin rules.
25- Create `yazi/keymap.toml`: prepend-only key overrides.
26- Create `yazi/init.lua`: plugin setup.
27- Create `yazi/package.toml`: generated by `ya pkg add`; plugin lock source of truth.
28- Create `yazi/flavors/nugu-dark.yazi/flavor.toml`: generated artifact.
29- Create `yazi/flavors/nugu-light.yazi/flavor.toml`: generated artifact.
30- Modify `.gitignore`: ignore installed `yazi/plugins/` artifacts.
31- Modify `desktop.symlinks`, `fedora.symlinks`, `x230.symlinks`: map `yazi` to `~/.config/yazi`.
33Do not touch or add `yazi/plugins/`. Existing untracked `pi/research/**` noise must not be staged.
35---
37### Task 1: Add dotfiles ownership, ignore rules, and live symlink
39**Files:**
40- Modify: `/home/me/Workspace/dotfiles/.gitignore`
41- Modify: `/home/me/Workspace/dotfiles/desktop.symlinks`
42- Modify: `/home/me/Workspace/dotfiles/fedora.symlinks`
43- Modify: `/home/me/Workspace/dotfiles/x230.symlinks`
44- Create: `/home/me/Workspace/dotfiles/yazi/.gitkeep` temporarily if needed before config files exist
45- Live target: `/home/me/.config/yazi`
47- [ ] **Step 1: Add Yazi installed plugin ignore rule**
49Append this block to `/home/me/Workspace/dotfiles/.gitignore` near the other local runtime/package caches:
51```gitignore
52# Yazi package manager installs plugin repos here; package.toml is source of truth.
53yazi/plugins/
54```
56- [ ] **Step 2: Add Yazi to `desktop.symlinks`**
58In `/home/me/Workspace/dotfiles/desktop.symlinks`, insert this pair after the existing `pi` mapping:
60```text
61yazi
62~/.config/yazi
63```
65The beginning of the file should become:
67```text
68forgejo-cli
69~/.config/forgejo-cli
71pi
72~/.pi
74yazi
75~/.config/yazi
77Notes
78~/Notes
79```
81- [ ] **Step 3: Add Yazi to `fedora.symlinks`**
83In `/home/me/Workspace/dotfiles/fedora.symlinks`, insert this pair after the `Notes` mapping:
85```text
86yazi
87~/.config/yazi
88```
90The beginning of the file should become:
92```text
93Notes
94~/Notes
96yazi
97~/.config/yazi
99git/gitconfig
100~/.config/git/config
101```
103- [ ] **Step 4: Add Yazi to `x230.symlinks`**
105In `/home/me/Workspace/dotfiles/x230.symlinks`, insert this pair after the `Notes` mapping:
107```text
108yazi
109~/.config/yazi
110```
112The beginning of the file should become:
114```text
115Notes
116~/Notes
118yazi
119~/.config/yazi
121git/gitconfig
122~/.config/git/config
123```
125- [ ] **Step 5: Create Yazi directory skeleton**
127Run:
129```bash
130cd /home/me/Workspace/dotfiles
131mkdir -p yazi/flavors/nugu-dark.yazi yazi/flavors/nugu-light.yazi
132touch yazi/.gitkeep
133```
135Expected: directories exist. Verify:
137```bash
138test -d yazi/flavors/nugu-dark.yazi && test -d yazi/flavors/nugu-light.yazi && test -f yazi/.gitkeep && echo ok
139```
141Expected output:
143```text
144ok
145```
147- [ ] **Step 6: Back up existing live Yazi config now**
149Run:
151```bash
152if [ -e /home/me/.config/yazi ] && [ ! -L /home/me/.config/yazi ]; then
153 mv /home/me/.config/yazi /home/me/.config/yazi.noctalia-backup-$(date +%Y%m%d%H%M%S)
154fi
155```
157Expected: existing non-symlink config is moved aside; no output on success.
159- [ ] **Step 7: Bootstrap live symlink now**
161Run:
163```bash
164cd /home/me/Workspace/dotfiles
165java bootstripper.java bootstrap
166```
168Expected: bootstrap exits 0 and creates `/home/me/.config/yazi` symlink.
170- [ ] **Step 8: Verify live symlink target**
172Run:
174```bash
175realpath /home/me/.config/yazi
176```
178Expected output:
180```text
181/home/me/Workspace/dotfiles/yazi
182```
184- [ ] **Step 9: Run dotfiles manifest check**
186Run:
188```bash
189cd /home/me/Workspace/dotfiles
190java bootstripper.java check
191```
193Expected: `OK bootstripper check passed.`
195- [ ] **Step 10: Commit ownership changes**
197Run:
199```bash
200cd /home/me/Workspace/dotfiles
201git add .gitignore desktop.symlinks fedora.symlinks x230.symlinks yazi/.gitkeep
202git commit -m "chore: manage yazi dotfiles"
203```
205Expected: commit succeeds. `yazi/.gitkeep` is removed in Task 3 after real config files exist.
207---
209### Task 2: Add Nugu-to-Yazi flavor generator
211**Files:**
212- Create: `/home/me/Workspace/dotfiles/nugu/yazi.nu`
213- Modify: `/home/me/Workspace/dotfiles/nugu/justfile`
215- [ ] **Step 1: Create `nugu/yazi.nu`**
217Write this file to `/home/me/Workspace/dotfiles/nugu/yazi.nu`:
219```nu
220use palette.nu
222# Generate a Yazi flavor.toml from the Nugu semantic palette.
223export def flavor [mode: string] {
224 let nugu = (palette nugu $mode)
225 let p = $nugu.palette
227 let theme = {
228 mgr: {
229 cwd: { fg: $p.content.normal }
230 find_keyword: { fg: $p.content.accent, bold: true, italic: true, underline: true }
231 find_position: { fg: $p.content.accent, bold: true }
232 symlink_target: { fg: $p.content.minor }
234 marker_copied: { fg: $p.content.focus, bg: $p.content.focus }
235 marker_cut: { fg: $p.warning, bg: $p.warning }
236 marker_marked: { fg: $p.content.accent, bg: $p.content.accent }
237 marker_selected: { fg: $p.ui.important_local, bg: $p.ui.important_local }
239 count_copied: { fg: $p.content.backdrop, bg: $p.content.focus, bold: true }
240 count_cut: { fg: $p.content.backdrop, bg: $p.warning, bold: true }
241 count_selected: { fg: $p.ui.backdrop, bg: $p.ui.important_local, bold: true }
243 border_symbol: "│"
244 border_style: { fg: $p.ui.unfocus }
245 }
247 status: {
248 overall: { fg: $p.ui.normal, bg: $p.ui.backdrop }
249 sep_left: { open: "", close: "" }
250 sep_right: { open: "", close: "" }
251 perm_type: { fg: $p.content.important_global }
252 perm_read: { fg: $p.content.focus }
253 perm_write: { fg: $p.warning }
254 perm_exec: { fg: $p.error }
255 perm_sep: { fg: $p.content.minor }
256 progress_label: { fg: $p.content.normal, bold: true }
257 progress_normal: { fg: $p.ui.accent, bg: $p.ui.backdrop }
258 progress_error: { fg: $p.error, bg: $p.ui.backdrop }
259 }
261 mode: {
262 normal_main: { fg: $p.ui.backdrop, bg: $p.ui.accent, bold: true }
263 normal_alt: { fg: $p.ui.normal, bg: $p.ui.backdrop }
264 select_main: { fg: $p.ui.backdrop, bg: $p.ui.important_local, bold: true }
265 select_alt: { fg: $p.ui.normal, bg: $p.ui.backdrop }
266 unset_main: { fg: $p.content.backdrop, bg: $p.warning, bold: true }
267 unset_alt: { fg: $p.ui.normal, bg: $p.ui.backdrop }
268 }
270 tabs: {
271 active: { fg: $p.ui.backdrop, bg: $p.ui.accent, bold: true }
272 inactive: { fg: $p.ui.minor, bg: $p.ui.backdrop }
273 sep_inner: { open: "", close: "" }
274 sep_outer: { open: "", close: "" }
275 }
277 which: {
278 cols: 3
279 mask: { bg: $p.ui.backdrop }
280 cand: { fg: $p.ui.accent, bold: true }
281 rest: { fg: $p.ui.minor }
282 desc: { fg: $p.ui.normal }
283 separator: " → "
284 separator_style: { fg: $p.ui.minor }
285 }
287 input: {
288 border: { fg: $p.ui.unfocus }
289 title: { fg: $p.ui.accent, bold: true }
290 value: { fg: $p.content.normal }
291 selected: { fg: $p.content.backdrop, bg: $p.content.focus }
292 }
294 confirm: {
295 border: { fg: $p.warning }
296 title: { fg: $p.warning, bold: true }
297 body: { fg: $p.content.normal }
298 list: { fg: $p.content.normal }
299 btn_yes: { fg: $p.content.backdrop, bg: $p.error, bold: true }
300 btn_no: { fg: $p.ui.backdrop, bg: $p.ui.focus, bold: true }
301 btn_labels: ["yes", "no"]
302 }
304 spot: {
305 border: { fg: $p.ui.unfocus }
306 title: { fg: $p.ui.accent, bold: true }
307 tbl_col: { fg: $p.content.normal }
308 tbl_cell: { fg: $p.content.backdrop, bg: $p.content.focus }
309 }
311 pick: {
312 border: { fg: $p.ui.unfocus }
313 active: { fg: $p.ui.backdrop, bg: $p.ui.focus, bold: true }
314 inactive: { fg: $p.ui.normal }
315 }
317 cmp: {
318 border: { fg: $p.ui.unfocus }
319 active: { fg: $p.ui.backdrop, bg: $p.ui.focus, bold: true }
320 inactive: { fg: $p.ui.normal }
321 }
323 tasks: {
324 border: { fg: $p.ui.unfocus }
325 title: { fg: $p.ui.accent, bold: true }
326 hovered: { fg: $p.content.focus, bold: true }
327 }
329 help: {
330 on: { fg: $p.ui.accent, bold: true }
331 run: { fg: $p.content.important_local }
332 desc: { fg: $p.content.normal }
333 hovered: { fg: $p.ui.backdrop, bg: $p.ui.focus, bold: true }
334 footer: { fg: $p.ui.backdrop, bg: $p.ui.accent, bold: true }
335 }
337 notify: {
338 title_info: { fg: $p.info, bold: true }
339 title_warn: { fg: $p.warning, bold: true }
340 title_error: { fg: $p.error, bold: true }
341 }
343 filetype: {
344 rules: [
345 { mime: "image/*", fg: $p.content.focus }
346 { mime: "{audio,video}/*", fg: $p.content.important_local }
347 { mime: "application/{zip,rar,7z*,tar,gzip,xz,zstd,bzip*,lzma,compress,archive,cpio,arj,xar,ms-cab*}", fg: $p.content.accent }
348 { mime: "application/{pdf,doc,rtf}", fg: $p.content.important_global }
349 { mime: "*", is: "orphan", fg: $p.content.backdrop, bg: $p.error, bold: true }
350 { mime: "application/*exec*", fg: $p.error }
351 { url: "*/", fg: $p.ui.accent, bold: true }
352 { url: "*", fg: $p.content.normal }
353 ]
354 }
356 git: {
357 unknown: { fg: $p.content.minor }
358 modified: { fg: $p.warning, bold: true }
359 added: { fg: $p.content.focus, bold: true }
360 untracked: { fg: $p.content.accent, bold: true }
361 ignored: { fg: $p.content.minor }
362 deleted: { fg: $p.error, bold: true }
363 updated: { fg: $p.warning, bold: true }
364 clean: { fg: $p.content.minor }
365 unknown_sign: ""
366 modified_sign: "M "
367 added_sign: "A "
368 untracked_sign: "? "
369 ignored_sign: "I "
370 deleted_sign: "D "
371 updated_sign: "U "
372 clean_sign: ""
373 }
374 }
376 $theme | to toml
377}
378```
380- [ ] **Step 2: Check the new Nushell module parses**
382Run:
384```bash
385cd /home/me/Workspace/dotfiles/nugu
386open yazi.nu | nu-check --as-module --debug yazi.nu
387```
389Expected: `nu-check` exits 0.
391- [ ] **Step 3: Add `yazi` recipe to `nugu/justfile`**
393Add this recipe after the `ghostty` recipe:
395```just
396yazi: build
397 rm --force --recursive {{output}}/yazi
398 mkdir {{output}}/yazi
399 mkdir {{output}}/yazi/nugu-dark.yazi
400 mkdir {{output}}/yazi/nugu-light.yazi
401 use yazi.nu; yazi flavor dark | save --raw {{output}}/yazi/nugu-dark.yazi/flavor.toml
402 use yazi.nu; yazi flavor light | save --raw {{output}}/yazi/nugu-light.yazi/flavor.toml
403 mkdir ../yazi/flavors
404 mkdir ../yazi/flavors/nugu-dark.yazi
405 mkdir ../yazi/flavors/nugu-light.yazi
406 cp {{output}}/yazi/nugu-dark.yazi/flavor.toml ../yazi/flavors/nugu-dark.yazi/flavor.toml
407 cp {{output}}/yazi/nugu-light.yazi/flavor.toml ../yazi/flavors/nugu-light.yazi/flavor.toml
408```
410- [ ] **Step 4: Include Yazi in Nugu install recipe**
412Change the final recipe in `/home/me/Workspace/dotfiles/nugu/justfile` from:
414```just
415install: helix wezterm ghostty
416```
418to:
420```just
421install: helix wezterm ghostty yazi
422```
424- [ ] **Step 5: Generate Yazi flavors**
426Run:
428```bash
429cd /home/me/Workspace/dotfiles/nugu
430just yazi
431```
433Expected files:
435```text
436/home/me/Workspace/dotfiles/yazi/flavors/nugu-dark.yazi/flavor.toml
437/home/me/Workspace/dotfiles/yazi/flavors/nugu-light.yazi/flavor.toml
438```
440Verify:
442```bash
443test -s /home/me/Workspace/dotfiles/yazi/flavors/nugu-dark.yazi/flavor.toml && \
444test -s /home/me/Workspace/dotfiles/yazi/flavors/nugu-light.yazi/flavor.toml && \
445echo ok
446```
448Expected output:
450```text
451ok
452```
454- [ ] **Step 6: Commit Nugu generator**
456Run:
458```bash
459cd /home/me/Workspace/dotfiles
460git add nugu/yazi.nu nugu/justfile yazi/flavors/nugu-dark.yazi/flavor.toml yazi/flavors/nugu-light.yazi/flavor.toml
461git commit -m "feat: generate yazi nugu flavors"
462```
464Expected: commit succeeds.
466---
468### Task 3: Add base Yazi config files
470**Files:**
471- Create: `/home/me/Workspace/dotfiles/yazi/theme.toml`
472- Create: `/home/me/Workspace/dotfiles/yazi/yazi.toml`
473- Create: `/home/me/Workspace/dotfiles/yazi/keymap.toml`
474- Create: `/home/me/Workspace/dotfiles/yazi/init.lua`
476- [ ] **Step 1: Create `yazi/theme.toml`**
478Write this file:
480```toml
481[flavor]
482dark = "nugu-dark"
483light = "nugu-light"
484```
486- [ ] **Step 2: Create `yazi/yazi.toml`**
488Write this file:
490```toml
491# A TOML linter such as Tombi can use this schema to validate your config.
492#:schema https://yazi-rs.github.io/schemas/yazi.json
494[mgr]
495show_hidden = true
496sort_by = "natural"
497sort_dir_first = true
498linemode = "none"
500[opener]
501edit = [
502 { run = 'nvim %s', desc = "nvim", block = true, for = "unix" },
503]
504play = [
505 { run = 'mpv %s', desc = "mpv", orphan = true, for = "unix" },
506]
507open = [
508 { run = 'xdg-open %s1', desc = "Open", for = "linux" },
509]
510extract = [
511 { run = 'ouch d -y %s', desc = "Extract here with ouch", for = "unix" },
512]
514[open]
515prepend_rules = [
516 { mime = "text/*", use = [ "edit", "reveal" ] },
517 { mime = "application/{json,ndjson,javascript,wine-extension-ini}", use = [ "edit", "reveal" ] },
518]
520[plugin]
521prepend_fetchers = [
522 { url = "*", run = "git", group = "git" },
523 { url = "*/", run = "git", group = "git" },
524]
525prepend_previewers = [
526 { url = "*.md", mime = "text/markdown", run = 'piper -- CLICOLOR_FORCE=1 glow -w=$w -s=dark "$1"' },
527 { mime = "application/{*zip,tar,bzip2,7z*,rar,xz,zstd,java-archive}", run = "ouch" },
528]
529append_previewers = [
530 { url = "*", run = 'piper -- hexyl --border=none --terminal-width=$w "$1"' },
531]
532```
534- [ ] **Step 3: Create `yazi/keymap.toml`**
536Write this file:
538```toml
539# A TOML linter such as Tombi can use this schema to validate your config.
540#:schema https://yazi-rs.github.io/schemas/keymap.json
542[[mgr.prepend_keymap]]
543on = "l"
544run = "plugin smart-enter"
545desc = "Enter directory or open file"
547[[mgr.prepend_keymap]]
548on = "<Enter>"
549run = "plugin smart-enter"
550desc = "Enter directory or open file"
552[[mgr.prepend_keymap]]
553on = "p"
554run = "plugin smart-paste"
555desc = "Paste into hovered directory or CWD"
557[[mgr.prepend_keymap]]
558on = "f"
559run = "plugin smart-filter"
560desc = "Smart filter"
562[[mgr.prepend_keymap]]
563on = "T"
564run = "plugin toggle-pane min-preview"
565desc = "Show or hide preview pane"
567[[mgr.prepend_keymap]]
568on = "F"
569run = "plugin toggle-pane max-preview"
570desc = "Maximize or restore preview pane"
572[[mgr.prepend_keymap]]
573on = [ "c", "m" ]
574run = "plugin chmod"
575desc = "Chmod selected files"
577[[mgr.prepend_keymap]]
578on = [ "c", "D" ]
579run = "plugin diff"
580desc = "Diff selected file with hovered file"
582[[mgr.prepend_keymap]]
583on = "!"
584for = "unix"
585run = 'shell "$SHELL" --block'
586desc = "Open shell here"
588[[mgr.prepend_keymap]]
589on = [ "g", "w" ]
590run = "cd ~/Workspace"
591desc = "Go ~/Workspace"
593[[mgr.prepend_keymap]]
594on = [ "g", "k" ]
595run = "cd ~/Workspace/dotfiles"
596desc = "Go dotfiles"
598[[mgr.prepend_keymap]]
599on = [ "g", "n" ]
600run = "cd ~/Notes"
601desc = "Go notes"
603[[mgr.prepend_keymap]]
604on = [ "g", "y" ]
605run = "cd ~/.config/yazi"
606desc = "Go Yazi config"
608[[mgr.prepend_keymap]]
609on = [ "g", "r" ]
610run = 'shell -- ya emit cd "$(git rev-parse --show-toplevel 2>/dev/null || jj root 2>/dev/null || pwd)"'
611desc = "Go repository root"
613[[input.prepend_keymap]]
614on = "<Esc>"
615run = "close"
616desc = "Cancel input"
617```
619- [ ] **Step 4: Create `yazi/init.lua`**
621Write this file:
623```lua
624require("full-border"):setup { type = ui.Border.PLAIN }
625require("git"):setup { order = 1500 }
626require("yaziline"):setup { separator_style = "liney" }
627```
629- [ ] **Step 5: Remove temporary `yazi/.gitkeep` if it exists**
631Run:
633```bash
634cd /home/me/Workspace/dotfiles
635rm -f yazi/.gitkeep
636```
638Expected: command exits 0.
640- [ ] **Step 6: Commit base Yazi config**
642Run:
644```bash
645cd /home/me/Workspace/dotfiles
646git add yazi/theme.toml yazi/yazi.toml yazi/keymap.toml yazi/init.lua
647git commit -m "feat: add yazi config"
648```
650Expected: commit succeeds.
652---
654### Task 4: Install and lock Yazi plugins
656**Files:**
657- Create: `/home/me/Workspace/dotfiles/yazi/package.toml`
658- Generated but ignored: `/home/me/Workspace/dotfiles/yazi/plugins/`
660- [ ] **Step 1: Install selected plugins with `ya pkg`**
662Run:
664```bash
665cd /home/me/.config/yazi
666ya pkg add \
667 yazi-rs/plugins:full-border \
668 yazi-rs/plugins:toggle-pane \
669 yazi-rs/plugins:smart-enter \
670 yazi-rs/plugins:smart-filter \
671 yazi-rs/plugins:smart-paste \
672 yazi-rs/plugins:git \
673 yazi-rs/plugins:chmod \
674 yazi-rs/plugins:diff \
675 yazi-rs/plugins:piper \
676 ndtoan96/ouch \
677 llanosrocas/yaziline
678```
680Expected:
682- `/home/me/Workspace/dotfiles/yazi/package.toml` exists through the live symlink.
683- `/home/me/Workspace/dotfiles/yazi/plugins/` exists and is ignored.
684- The command exits 0.
686- [ ] **Step 2: Verify installed plugin dirs are ignored**
688Run:
690```bash
691cd /home/me/Workspace/dotfiles
692git status --short yazi/package.toml yazi/plugins
693```
695Expected output includes `?? yazi/package.toml` and does not list individual files under `yazi/plugins/`.
697- [ ] **Step 3: Verify package lock lists all plugin deps**
699Run:
701```bash
702cd /home/me/Workspace/dotfiles
703for dep in \
704 'yazi-rs/plugins:full-border' \
705 'yazi-rs/plugins:toggle-pane' \
706 'yazi-rs/plugins:smart-enter' \
707 'yazi-rs/plugins:smart-filter' \
708 'yazi-rs/plugins:smart-paste' \
709 'yazi-rs/plugins:git' \
710 'yazi-rs/plugins:chmod' \
711 'yazi-rs/plugins:diff' \
712 'yazi-rs/plugins:piper' \
713 'ndtoan96/ouch' \
714 'llanosrocas/yaziline'; do
715 grep -F "use = \"$dep\"" yazi/package.toml >/dev/null || { echo "missing $dep"; exit 1; }
716done
717echo ok
718```
720Expected output:
722```text
723ok
724```
726- [ ] **Step 4: Commit package lock**
728Run:
730```bash
731cd /home/me/Workspace/dotfiles
732git add yazi/package.toml
733git commit -m "feat: lock yazi plugins"
734```
736Expected: commit succeeds and `yazi/plugins/` remains untracked/ignored.
738---
740### Task 5: Validate generated Nugu and Yazi config
742**Files:**
743- Verify: `/home/me/Workspace/dotfiles/nugu/yazi.nu`
744- Verify: `/home/me/Workspace/dotfiles/yazi/*.toml`
745- Verify: `/home/me/Workspace/dotfiles/yazi/init.lua`
747- [ ] **Step 1: Run Nugu checks**
749Run:
751```bash
752cd /home/me/Workspace/dotfiles/nugu
753just check
754```
756Expected: `just check` exits 0 and reports Nugu color contrast results.
758- [ ] **Step 2: Regenerate Yazi flavors and check drift**
760Run:
762```bash
763cd /home/me/Workspace/dotfiles/nugu
764just yazi
765cd /home/me/Workspace/dotfiles
766git diff -- yazi/flavors/nugu-dark.yazi/flavor.toml yazi/flavors/nugu-light.yazi/flavor.toml
767```
769Expected: no diff.
771- [ ] **Step 3: Validate Yazi can print debug config**
773Run:
775```bash
776yazi --debug >/tmp/yazi-debug.txt
777head -40 /tmp/yazi-debug.txt
778```
780Expected:
782- Command exits 0.
783- Output contains Yazi debug information.
784- No TOML parse error appears.
786- [ ] **Step 4: Verify plugin restore from lock works**
788Run:
790```bash
791cd /home/me/.config/yazi
792ya pkg install
793```
795Expected: command exits 0.
797- [ ] **Step 5: Run dotfiles pre-commit check**
799Run:
801```bash
802cd /home/me/Workspace/dotfiles
803just pre-commit
804```
806Expected: command exits 0 with no leaked secrets or manifest failures.
808- [ ] **Step 6: Commit validation fixups if any**
810If any validation step required fixes, run:
812```bash
813cd /home/me/Workspace/dotfiles
814git add .gitignore desktop.symlinks fedora.symlinks x230.symlinks nugu/yazi.nu nugu/justfile yazi/theme.toml yazi/yazi.toml yazi/keymap.toml yazi/init.lua yazi/package.toml yazi/flavors/nugu-dark.yazi/flavor.toml yazi/flavors/nugu-light.yazi/flavor.toml
815git commit -m "fix: validate yazi nugu config"
816```
818Expected: commit succeeds only if there were fixups. If there were no changes, skip this step.
820---
822### Task 6: Smoke-test live config interactively
824**Files:**
825- Live target: `/home/me/.config/yazi`
826- Source: `/home/me/Workspace/dotfiles/yazi`
828- [ ] **Step 1: Verify live config is already symlinked**
830Run:
832```bash
833realpath /home/me/.config/yazi
834```
836Expected output:
838```text
839/home/me/Workspace/dotfiles/yazi
840```
842- [ ] **Step 2: Install locked plugins in live config**
844Run:
846```bash
847cd /home/me/.config/yazi
848ya pkg install
849```
851Expected: command exits 0.
853- [ ] **Step 3: Launch Yazi smoke session**
855Run:
857```bash
858YAZI_LOG=debug yazi /home/me/Workspace/dotfiles
859```
861In Yazi, verify manually:
863- Hidden files are visible immediately.
864- `~` or `<F1>` opens help and custom bindings appear.
865- `l` and `<Enter>` enter dirs/open files through smart-enter.
866- `p` runs smart-paste behavior.
867- `f` opens smart-filter.
868- `T` hides/shows preview.
869- `F` maximizes/restores preview.
870- `c m` opens chmod plugin.
871- `c D` opens diff plugin when a file is selected and another is hovered.
872- `!` opens `$SHELL` and returns to Yazi when the shell exits.
873- `g w`, `g k`, `g n`, `g y`, `g r` navigate to the expected directories.
874- Markdown files preview through glow.
875- Archives preview through ouch.
876- Git signs appear in the file list inside the dotfiles repo.
877- Yaziline statusline uses liney separators.
878- Plain full border is visible.
880Quit with `q`.
882- [ ] **Step 4: Inspect Yazi log if smoke test fails**
884Run:
886```bash
887tail -200 /home/me/.local/state/yazi/yazi.log
888```
890Expected: no Lua stack traces for configured plugins after any needed fixes.
892- [ ] **Step 5: Commit smoke-test fixes if any**
894If the smoke test required config changes, run:
896```bash
897cd /home/me/Workspace/dotfiles
898git add yazi/theme.toml yazi/yazi.toml yazi/keymap.toml yazi/init.lua yazi/package.toml yazi/flavors/nugu-dark.yazi/flavor.toml yazi/flavors/nugu-light.yazi/flavor.toml nugu/yazi.nu nugu/justfile
899git commit -m "fix: smoke test yazi config"
900```
902Expected: commit succeeds only if there were fixes. If there were no changes, skip this step.
904---
906### Task 7: Final repository verification
908**Files:**
909- Verify all changed files from previous tasks.
911- [ ] **Step 1: Check concise Git status**
913Run:
915```bash
916cd /home/me/Workspace/dotfiles
917git status --short .gitignore desktop.symlinks fedora.symlinks x230.symlinks nugu/yazi.nu nugu/justfile yazi docs/superpowers/specs/2026-05-30-yazi-nugu-dotfiles-design.md docs/superpowers/plans/2026-05-30-yazi-nugu-dotfiles.md
918```
920Expected: no unstaged changes for these paths. `yazi/plugins/` must not appear.
922- [ ] **Step 2: Run full dotfiles check**
924Run:
926```bash
927cd /home/me/Workspace/dotfiles
928just check
929```
931Expected: command exits 0.
933- [ ] **Step 3: Record final notes**
935If all validation passes, add a short note to the final response:
937```text
938Implemented Yazi dotfiles config with generated Nugu flavors, managed plugin lock, Yazi-native key overrides, and live symlink install. Deferred jj plugin/lazygit/bookmarks/sessions as planned.
939```
941No file change is required for this step.

docs/superpowers/specs/2026-05-30-yazi-nugu-dotfiles-design.md

Deleted
deleted file mode 100644

+0 / −261 text lines

1# Yazi Nugu dotfiles design
2
3Date: 2026-05-30
4
5## Goal
6
7Make Yazi a first-class, dotfiles-managed terminal file manager configuration that uses the personal Nugu theme and integrates tastefully with existing tools. The result should feel native to the rest of the dotfiles without turning Yazi into a large plugin project.
8
9## Non-goals
11- Do not vendor third-party plugin repositories into dotfiles.
12- Do not add bookmarks or session/autosession plugins.
13- Do not replace Yazi defaults wholesale.
14- Do not add a Space leader layer; keep Space for selection.
15- Do not implement Jujutsu (`jj`) Yazi plugin support in v1.
16- Do not add heavyweight statusline alternatives beyond the chosen minimal statusline plugin.
18## Current context
20- Live Yazi config currently lives in `~/.config/yazi` and contains only:
21 - `theme.toml`, selecting the `noctalia` flavor.
22 - `flavors/noctalia.yazi/flavor.toml`.
23- Dotfiles do not currently manage `~/.config/yazi`.
24- Nugu already provides generated themes for Ghostty, Helix, and WezTerm.
25- Existing dotfiles favor declarative config, Nushell automation, generated theme artifacts, and symlink manifests.
26- Relevant available tools include `nvim`, `git`, `jj`, `glow`, `bat`, `mpv`, `wl-copy`, `fzf`, `zoxide`, `fd`, `rg`, `jq`, `7z`, `ffmpeg`, `magick`, `resvg`, `pdftoppm`, `ouch`, and `hexyl`.
28## Architecture
30### Dotfiles ownership
32Create a new `yazi/` directory in the dotfiles repository. It will be symlinked to `~/.config/yazi` through the host symlink manifests, consistent with other applications.
34Planned files:
36```text
37yazi/
38├── theme.toml
39├── yazi.toml
40├── keymap.toml
41├── init.lua
42├── package.toml
43└── flavors/
44 ├── nugu-dark.yazi/
45 │ └── flavor.toml
46 └── nugu-light.yazi/
47 └── flavor.toml
48```
50The symlink manifest should map:
52```text
53yazi
54~/.config/yazi
55```
57Linux desktop host manifests should receive this mapping: `desktop.symlinks`, `fedora.symlinks`, and `x230.symlinks`. `termux.symlinks` and Windows manifests can be added later if Yazi is used there.
59### Plugin package hygiene
61Yazi plugins will be managed with `ya pkg`. The committed source of truth is `yazi/package.toml`, not the installed plugin directories.
63- Commit `package.toml`.
64- Ignore `yazi/plugins/`.
65- Do not vendor plugin repositories.
66- Restore plugins on a new machine with `ya pkg install`.
68The generated Nugu flavors are not third-party plugin clutter. They are first-party generated artifacts and should be committed.
70### Nugu integration
72Add a `nugu/yazi.nu` generator that maps Nugu palette roles to Yazi's flavor schema.
74Extend `nugu/justfile` with a `yazi` recipe that:
761. Builds or reads the Nugu palette.
772. Generates dark and light flavor files under `output/yazi/` or directly writes `../yazi/flavors/nugu-{dark,light}.yazi/flavor.toml`.
783. Keeps generated Yazi flavor output reproducible.
80Extend `nugu/justfile install` to include the Yazi generation step.
82`yazi/theme.toml` will select Nugu:
84```toml
85[flavor]
86dark = "nugu-dark"
87light = "nugu-light"
88```
90Yazi will use separate generated Nugu dark and light flavors so terminal light/dark switching has matching colors.
92## Theme mapping
94The Yazi flavor should use Nugu semantic palette roles rather than raw arbitrary colors.
96Suggested role mapping:
98- App/status backgrounds: `ui.backdrop`.
99- Main text: `content.normal`.
100- File manager borders: `ui.unfocus` or `ui.minor`.
101- Active UI elements: `ui.accent` and `ui.important_local`.
102- Selected counts/markers: `content.focus` and `ui.important_local`.
103- Warnings/errors: `warning` and `error`.
104- Git signs:
105 - modified: `warning`
106 - added: `content.focus`
107 - untracked: `content.accent`
108 - deleted: `error`
109 - ignored: `content.minor`
111The initial flavor should style enough of Yazi to feel intentionally Nugu without duplicating the full Noctalia icon table. Existing Yazi default icons can remain unless they clash visually.
113## Yazi behavior config
115`yazi/yazi.toml` should be minimal and override defaults only where the dotfiles imply a preference.
117Planned manager settings:
119```toml
120[mgr]
121show_hidden = true
122sort_by = "natural"
123sort_dir_first = true
124linemode = "none"
125```
127Use default pane ratio `[1, 4, 3]` unless testing shows preview feels cramped.
129Preview/opening behavior:
131- Keep built-in JSON, PDF, image, video, and archive previews where they work well.
132- Use `piper` selectively for tools already present:
133 - Markdown preview via `glow`.
134 - Fallback binary preview via `hexyl`.
135- Use `ouch` for archive preview/extract behavior where it improves over defaults.
136- Use `nvim` as blocking editor.
137- Use `mpv` for media.
138- Use `xdg-open` for general open behavior.
140Git integration:
142- Configure `git.yazi` fetchers for files and directories.
143- Do not configure `vcs-files` in v1.
144- Do not attempt inline `jj` status in v1.
146## Lua initialization
148`yazi/init.lua` should only initialize selected plugins and avoid custom UI rewrites.
150Planned setup:
152```lua
153require("full-border"):setup { type = ui.Border.PLAIN }
154require("git"):setup { order = 1500 }
155require("yaziline"):setup { separator_style = "liney" }
156```
158Additional plugin setup can be added only if required by the chosen plugin's documented API. Avoid overriding core Yazi UI build functions.
160## Keymap design
162Use `[[mgr.prepend_keymap]]` only. Preserve Yazi defaults and add targeted improvements.
164Principles:
166- Space remains selection.
167- `g`, `t`, `c`, and existing Yazi prefix groups remain native Yazi-style groups.
168- No full keymap replacement.
169- Avoid terminal-fragile Alt bindings when a normal sequence is available.
171Planned bindings:
173| Key | Action |
174| --- | --- |
175| `l` | `plugin smart-enter` |
176| `<Enter>` | `plugin smart-enter` |
177| `p` | `plugin smart-paste` |
178| `f` | `plugin smart-filter` |
179| `T` | `plugin toggle-pane min-preview` |
180| `F` | `plugin toggle-pane max-preview` |
181| `c m` | `plugin chmod` |
182| `c D` | `plugin diff` |
183| `!` | blocking `$SHELL` in current directory |
184| `g w` | `cd ~/Workspace` |
185| `g k` | `cd ~/Workspace/dotfiles` |
186| `g n` | `cd ~/Notes` |
187| `g y` | `cd ~/.config/yazi` |
188| `g r` | change to repo root using `git rev-parse --show-toplevel` or `jj root` |
190Input behavior:
192- Override input `<Esc>` to close the input immediately, avoiding Yazi input's vi-normal mode when the intent is simple cancellation.
194## Plugin set
196Install and lock these plugins in `yazi/package.toml`:
198- `yazi-rs/plugins:full-border`
199- `yazi-rs/plugins:toggle-pane`
200- `yazi-rs/plugins:smart-enter`
201- `yazi-rs/plugins:smart-filter`
202- `yazi-rs/plugins:smart-paste`
203- `yazi-rs/plugins:git`
204- `yazi-rs/plugins:chmod`
205- `yazi-rs/plugins:diff`
206- `yazi-rs/plugins:piper`
207- `ndtoan96/ouch`
208- `llanosrocas/yaziline`
210Deferred plugins and integrations:
212- Custom `jj` plugin.
213- `vcs-files` and `git-files`.
214- Bookmark plugins.
215- Session/autosession plugins.
216- `lazygit` plugin until the `lazygit` binary is installed.
217- `starship`, `yatline`, `simple-status`, and other statusline alternatives.
218- `mount`, `sudo`, and clipboard plugins.
220## Validation strategy
222Functional validation:
2241. Generate Nugu Yazi flavor.
2252. Run `ya pkg install` from the Yazi config directory.
2263. Run `yazi --debug` to inspect merged config and schema issues.
2274. Launch Yazi with `YAZI_LOG=debug` if plugin errors occur.
2285. Check keybindings in Yazi help.
2296. Smoke-test:
230 - hidden files visible by default
231 - `l`/Enter smart-enter behavior
232 - `p` smart-paste behavior
233 - `f` smart-filter behavior
234 - `T` and `F` pane behavior
235 - `c m` chmod prompt
236 - `c D` diff behavior
237 - Markdown preview via glow
238 - archive handling via ouch
239 - git signs in a Git repo
241Repo validation:
2431. Ensure `yazi/plugins/` is ignored.
2442. Ensure `yazi/flavors/nugu-dark.yazi/flavor.toml` and `yazi/flavors/nugu-light.yazi/flavor.toml` are tracked.
2453. Ensure symlink manifest tests still pass.
2464. Ensure regenerating Nugu Yazi flavor produces no unexpected diff.
248## Implementation phases
2501. Add Yazi dotfiles skeleton and symlink manifest entries.
2512. Add Nugu Yazi generator and generated flavor.
2523. Add Yazi config files (`theme.toml`, `yazi.toml`, `keymap.toml`, `init.lua`).
2534. Install and lock selected plugins via `ya pkg`.
2545. Add ignore rules for installed plugin artifacts.
2556. Validate with Yazi, Nugu generation, and dotfiles checks.
257## Open follow-ups after v1
259- Add a local custom Yazi plugin for `jj` changed files or inline status signs.
260- Consider adding a `just yazi` or root-level dotfiles recipe for Yazi validation.
261- Consider adding `lazygit` integration if the binary is installed later.

dprint/dprint.jsonc

Added
new file mode 100644

+63 / −0 text lines

1{
2 "typescript": {
3 },
4 "json": {
5 },
6 "markdown": {
7 },
8 "toml": {
9 },
10 "dockerfile": {
11 },
12 "ruff": {
13 },
14 "gofumpt": {
15 },
16 "malva": {
17 },
18 "markup": {
19 },
20 "yaml": {
21 },
22 "sql": {
23 },
24 "exec": {
25 "cwd": "${configDir}",
26 "commands": [
27 {
28 "command": "rustfmt",
29 "exts": ["rs"]
30 },
31 {
32 "command": "clang-format",
33 "exts": ["c", "cc", "cpp", "cxx", "h", "hpp", "hxx", "m", "mm"]
34 },
35 {
36 "command": "shfmt",
37 "exts": ["sh", "bash"]
38 },
39 {
40 "command": "zig fmt --stdin",
41 "exts": ["zig"]
42 }
43 ]
44 },
45 "excludes": [
46 "**/node_modules",
47 "**/*-lock.json"
48 ],
49 "plugins": [
50 "npm:@dprint/typescript@0.96.1",
51 "npm:@dprint/json@0.24.0",
52 "npm:@dprint/markdown@0.24.0",
53 "npm:@dprint/toml@0.8.0",
54 "npm:@dprint/dockerfile@0.6.0",
55 "npm:@dprint/ruff@0.8.8",
56 "npm:@jakebailey/dprint-plugin-gofumpt@0.0.18",
57 "npm:dprint-plugin-malva@0.16.0",
58 "npm:dprint-plugin-markup@0.27.3",
59 "npm:dprint-plugin-yaml@0.6.0",
60 "npm:lax-sql@0.3.0",
61 "npm:@dprint/exec@0.7.3/plugin.json@704701df449dd7e942a71144773778ac529d68c2e4657bfc236d393b898b9a67"
62 ]
63}

enable_user_services.nu

Deleted
deleted file mode 100644

+0 / −33 text lines

1
2if ($nu.os-info.name != linux) {
3 return
4}
5
6const services = [
7 [profile-sync-daemon psd psd.service]
8 [pueued pueued pueued.service]
9 [hypridle hypridle hypridle.service]
10 [hyprsunset hyprsunset hyprsunset.service]
11 [hyprpolkitagent /usr/lib/hyprpolkitagent/hyprpolkitagent hyprpolkitagent.service]
12 [mako mako mako.service]
13 [cliphist cliphist cliphist.service]
14 [wl-clip-persist wl-clip-persist wl-clip-persist.service]
15 [wezterm-mux-server wezterm-mux-server wezterm-mux-server.service]
16 [nugu-theme lua nugu-theme.service]
17 [ironbar ironbar ironbar.service]
18 [ironbar-workspaces python ironbar-workspaces.service]
19]
21$services | each { | service |
22 let name = $service.0
23 let binary = $service.1
24 let service_name = $service.2
25 let found = if ($binary | str starts-with "/") { $binary | path exists } else { which $binary | is-not-empty }
26 if $found {
27 print $"Found program ($name). Enabling service now."
28 systemctl --user enable --now $service_name
29 null
30 }
31}
33null

environment.d/60-xdg-open-gio.conf

Added
new file mode 100644

+3 / −0 text lines

1# Put the gio-backed xdg-open shim (xdg/bin) ahead of /usr/bin/xdg-open for the session.
2# Dedicated directory: nothing else in it can shadow system tools.
3PATH=${HOME}/.local/override/bin:${PATH}

fuzzel/fuzzel.ini

Deleted
deleted file mode 100644

+0 / −25 text lines

1# Fuzzel Configuration
2# See: https://codeberg.org/dnkl/fuzzel#configuration
3# ~/.config/fuzzel/fuzzel.ini
4
5[main]
6width=69
7prompt="󱓞 "
8layer=overlay
9anchor=center
10lines=8
11terminal=wezterm
12font=Monaspace Krypton Var:style=Regular:size=24
13use-bold=true
14dpi-aware=auto
16# TODO: nugu
17[colors]
18background=2e3440ff
19text=eceff4ff
20selection=4c566aff
21selection-text=d8dee9ff
22border=88c0d0ff
24[border]
25width=4

gh/hosts.yml

Modified

Binary size (old → new): 118 → 121 bytes.

ghostty/TODO.md

Deleted
deleted file mode 100644

+0 / −59 text lines

1# Ghostty Migration TODO
2
3Features from wezterm config not yet ported. Check off as ghostty adds support.
4
5## Blocked: Needs Ghostty Scripting API (#2353)
6
7- [ ] **AI shell integration** — requires scrollback access from external script.
8 Wezterm: `pane:get_lines_as_text()` → curl to z.ai API → `pane:send_text()`.
9 Ghostty has no equivalent on Linux. macOS has AppleScript (preview).
11- [ ] **Zoxide workspace switcher** — requires PromptInputLine equivalent + mux API.
12 Wezterm: `PromptInputLine` → fuzzy picker combining zoxide + workspaces → `SwitchToWorkspace`.
13 Workaround: use a nushell keybinding that calls zoxide directly via fzf/builtin picker.
15- [ ] **Dynamic status bar** — requires per-window state + formatting API.
16 Wezterm: `update-status` event → time, battery, AI status, leader indicator, workspace name.
17 Ghostty: title only. No custom formatted status bar.
19- [ ] **Rotating panes** — no `rotate_panes` equivalent.
20 Wezterm: `RotatePanes 'CounterClockwise'` / `RotatePanes 'Clockwise'`.
21 Ghostty has `equalize_splits` but no rotation.
23## Blocked: Needs Ghostty Config API
25- [ ] **Presentation mode** — requires saving/restoring per-surface font size.
26 Wezterm: toggles fullscreen + doubles font + sets DemiBold weight, then restores.
27 Ghostty has `chain=` + `set_font_size` + `toggle_fullscreen` but no state restore.
28 Possible workaround: write a script that swaps config files and reloads.
30- [ ] **Per-host config** — currently using `config-file = ?host-desktop`.
31 Wezterm: `wez.hostname()` → dynamic require.
32 Ghostty: static `config-file` directive. Needs manual per-host file or symlinks.
34## Blocked: Ghostty Philosophy
36- [ ] **Process icons in tab titles** — ghostty doesn't map process→nerdfont icons.
37 Wezterm: `icons.lua` maps 100+ process names to nerdfont glyphs.
38 Ghostty sets tab title from terminal title only.
40- [ ] **Mouse 4-click semantic zone selection** — no ghostty equivalent.
41 Wezterm: `SelectTextAtMouseCursor 'SemanticZone'` on 4 clicks.
43## Not Ported: Low Priority
45- [ ] **Battery display in status** — ghostty has no battery API. Use external widget.
46- [ ] **Quick select** — ghostty has `quick_select` action but no customization of alphabets/matches yet.
47- [ ] **Char select** — ghostty has no `CharSelect` equivalent. Use `toggle_command_palette` instead.
48- [ ] **Debug overlay** — ghostty has `inspector:toggle` (close equivalent).
49- [ ] **Workspace "dotfiles" auto-open** — wezterm `gui-startup` spawns dotfiles workspace on launch.
50 Ghostty has `window-save-state = always` which partially replaces this.
52## New Capabilities (not in wezterm)
54- [x] `global:` quick terminal — system-wide terminal toggle
55- [x] Custom GLSL shaders — visual effects (bloom, cursor smear, etc.)
56- [x] `performable:` keybinds — context-aware bindings that don't shadow nvim
57- [x] `chain=` actions — multiple actions per keypress
58- [x] Key table stacking — nested modal modes
59- [x] Click-to-move cursor in nushell prompts (native, no config needed)

ghostty/config

Modified

+8 / −52 text lines

1# ── Theme ──────────────────────────────────────────────────────────────────────
2# Uses nugu themes generated by nugu/ghostty.nu
3# Auto-switches with system light/dark mode
41theme = light:nugu-light,dark:nugu-dark
5
6# ── Shell ─────────────────────────────────────────────────────────────────────
72command = nu --login
3font-size = 13
9# ── Font ──────────────────────────────────────────────────────────────────────
10font-family = "IBM Plex Mono"
11font-size = 16
13# Bold italic: Monaspace Xenon Var (for comments in editors)
14font-family-bold-italic = "Monaspace Xenon Var"
15font-style-bold-italic = "Bold Italic"
17# Italic: VictorMono (for string values, gives a special touch)
18font-family-italic = "VictorMono"
19font-style-italic = "Italic"
21# ── Window ────────────────────────────────────────────────────────────────────
22window-padding-x = 0
23window-padding-y = 0
245window-decoration = false
25window-inherit-font-size = false
6window-padding-x = 4
7window-padding-y = 0
8window-padding-balance = true
9window-step-resize = true
27# ── Tab bar ───────────────────────────────────────────────────────────────────
28window-show-tab-bar = always
29gtk-tabs-location = bottom
30window-save-state = always
32# ── Scrollback ────────────────────────────────────────────────────────────────
33scrollback-limit = 16777216
35# ── Bell ──────────────────────────────────────────────────────────────────────
36bell-features = no-system,no-audio,no-attention,no-title,no-border
38# ── Clipboard ─────────────────────────────────────────────────────────────────
39clipboard-paste-protection = false
41# ── Close behavior ────────────────────────────────────────────────────────────
42confirm-close-surface = false
44# ── Split behavior ────────────────────────────────────────────────────────────
45split-preserve-zoom = navigation
47# ── Mouse ─────────────────────────────────────────────────────────────────────
48mouse-hide-while-typing = true
50# ── Shell integration ─────────────────────────────────────────────────────────
51shell-integration = detect
52shell-integration-features = cursor,sudo
54# ── Modular configs ───────────────────────────────────────────────────────────
55config-file = keybinds
56config-file = launch-menu
57config-file = ?host-desktop
11copy-on-select = clipboard
12mouse-scroll-multiplier = 1
13bell-features = attention

ghostty/host-desktop

Deleted
deleted file mode 100644

+0 / −5 text lines

1# ── Host: desktop ─────────────────────────────────────────────────────────────
2# Wayland + high refresh rate
3# Note: enable-wayland and max-fps are not ghostty config options.
4# Wayland is auto-detected. FPS follows compositor vsync.
5# See TODO.md for tracking.

ghostty/keybinds

Deleted
deleted file mode 100644

+0 / −72 text lines

1# ── Keybinds for ghostty ──────────────────────────────────────────────────────
2# Ports wezterm bugabinga/key_binds.lua using ghostty 1.3 key tables.
3#
4# Leader: ctrl+a (VoidSymbol in wezterm, ctrl+a here)
5# All modes use catch_all=ignore to prevent key leaks.
6
7# Wipe all defaults (equivalent to wezterm's disable_default_key_bindings)
8keybind = clear
9
10# ── Clipboard ─────────────────────────────────────────────────────────────────
11keybind = ctrl+shift+c=copy_to_clipboard
12keybind = ctrl+shift+v=paste_from_clipboard
14# ── Font mode ─────────────────────────────────────────────────────────────────
15# Port of wezterm font_mode: -=scale down, ==scale up, 0=reset
16keybind = ctrl+a>0=activate_key_table:font
17keybind = font/-=decrease_font_size:1
18keybind = font/==increase_font_size:1
19keybind = font/0=reset_font_size
20keybind = font/escape=deactivate_key_table
21keybind = font/catch_all=ignore
23# ── Pane mode ─────────────────────────────────────────────────────────────────
24# Port of wezterm pane_mode: hjkl navigate, vs split, a select, q close
25keybind = ctrl+a>w=activate_key_table:pane
26keybind = pane/h=goto_split:left
27keybind = pane/j=goto_split:down
28keybind = pane/k=goto_split:up
29keybind = pane/l=goto_split:right
30keybind = pane/v=new_split:right
31keybind = pane/s=new_split:down
32keybind = pane/==activate_key_table:resize
33keybind = pane/q=close_surface
34keybind = pane/escape=deactivate_key_table
35keybind = pane/catch_all=ignore
37# ── Resize sub-mode ──────────────────────────────────────────────────────────
38# Port of wezterm resize_pane_mode: hjkl resize by 10px
39keybind = resize/h=resize_split:left,10
40keybind = resize/j=resize_split:down,10
41keybind = resize/k=resize_split:up,10
42keybind = resize/l=resize_split:right,10
43keybind = resize/escape=deactivate_key_table
44keybind = resize/catch_all=ignore
46# ── Direct leader sequences ───────────────────────────────────────────────────
47# Single-shot actions that don't need a mode
48keybind = ctrl+a>f=toggle_split_zoom
49keybind = ctrl+a>F5=reload_config
50keybind = ctrl+a>F11=toggle_fullscreen
51keybind = ctrl+a>t=new_tab
52keybind = ctrl+a>/=start_search
53keybind = ctrl+a>q=close_surface
55# ── Tab navigation (leader + number) ─────────────────────────────────────────
56keybind = ctrl+a>1=goto_tab:1
57keybind = ctrl+a>2=goto_tab:2
58keybind = ctrl+a>3=goto_tab:3
59keybind = ctrl+a>4=goto_tab:4
60keybind = ctrl+a>5=goto_tab:5
61keybind = ctrl+a>6=goto_tab:6
62keybind = ctrl+a>7=goto_tab:7
63keybind = ctrl+a>8=goto_tab:8
65# ── Scrolling ─────────────────────────────────────────────────────────────────
66keybind = page_up=scroll_page_up
67keybind = page_down=scroll_page_down
68keybind = shift+page_up=scroll_page_fractional:-0.42
69keybind = shift+page_down=scroll_page_fractional:0.42
71# ── Command palette (replaces wezterm launcher) ───────────────────────────────
72keybind = ctrl+a>p=toggle_command_palette

ghostty/launch-menu

Deleted
deleted file mode 100644

+0 / −20 text lines

1# ── Launch Menu ───────────────────────────────────────────────────────────────
2# Replaces wezterm bugabinga/launch.lua via command-palette-entry.
3# Open with ctrl+a>p then search/filter → enter to execute.
4#
5# Each entry uses text: action to type the command + newline into the terminal.
6
7command-palette-entry = title:Anime (new),action:text:ani-cli\n
8command-palette-entry = title:Anime (continue),action:text:ani-cli --continue\n
9command-palette-entry = title:Upgrade,action:text:topgrade --keep\n
10command-palette-entry = title:IRC Chat,action:text:weechat\n
11command-palette-entry = title:Browser,action:text:cha -V\n
12command-palette-entry = title:E-Mail,action:text:aerc\n
13command-palette-entry = title:Music,action:text:cmus\n
14command-palette-entry = title:System Monitor,action:text:btm\n
15command-palette-entry = title:Clock,action:text:tclock\n
16command-palette-entry = title:Calculator,action:text:eva\n
17command-palette-entry = title:Weather,action:text:nu -c "loop {clear; wthrr --forecast today; sleep 15sec}"\n
18command-palette-entry = title:Host Info,action:text:nu -c "loop {clear; macchina --current-shell --interface wlp3s0; sleep 5sec}"\n
19command-palette-entry = title:Units,action:text:fend\n
20command-palette-entry = title:Files,action:text:yazi\n

ghostty/themes/nugu-dark

Modified

+9 / −6 text lines

1010palette=3=#f0ee69
1111palette=4=#b59ae4
1212palette=5=#d151d1
13palette=6=#5d5d5d
13palette=6=#3ec5e3
1414palette=7=#ededed
1515palette=8=#8b8b8b
16palette=9=#3ec5e3
17palette=10=#6f6f6f
18palette=11=#242424
16palette=9=#ec6376
17palette=10=#9aabae
18palette=11=#f0ee69
1919palette=12=#dfd3f3
2020palette=13=#d86dd8
2121palette=14=#c9b6eb
2222palette=15=#f3effb
2323palette=16=#ed5eed
2424palette=17=#dbdbdb
25palette=18=#9d9d9d
26palette=19=#9aabaeNo final newline
25palette=18=#242424
26palette=19=#9d9d9d
27palette=20=#9aabae
28palette=21=#6f6f6f
29palette=22=#5d5d5dNo final newline

ghostty/themes/nugu-light

Modified

+9 / −6 text lines

1010palette=3=#6e6c10
1111palette=4=#715696
1212palette=5=#ae2eae
13palette=6=#6f6f6f
13palette=6=#116477
1414palette=7=#121212
1515palette=8=#3b3b3b
16palette=9=#116477
17palette=10=#5d5d5d
18palette=11=#dbdbdb
16palette=9=#bd172e
17palette=10=#15333b
18palette=11=#6e6c10
1919palette=12=#4f3c69
2020palette=13=#922792
2121palette=14=#604980
2222palette=15=#3e2f53
2323palette=16=#a112a1
2424palette=17=#242424
25palette=18=#292929
26palette=19=#15333bNo final newline
25palette=18=#dbdbdb
26palette=19=#292929
27palette=20=#15333b
28palette=21=#5d5d5d
29palette=22=#6f6f6fNo final newline

git/allowed_signers

Added
new file mode 100644

+4 / −0 text lines

1# Trust store for SSH commit signatures. Public keys only; no secret material.
2# Principal is matched against the committer email.
3oliver@bugabinga.net ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAICyZgTxIo9LIsvZLl/iKxlh6vf2WSiz6tyHEQI9lYnC6 oli@velma
4o.krylow@isp-insoft.de ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIIvGTFdXbhJF4VCi1l5Rm3/ypY0rN16XEJOcIzyLq8AA code.isp-insoft.de

git/gitattributes

Modified

+66 / −46 text lines

1*.java merge=mergiraf
2*.properties merge=mergiraf
3*.kt merge=mergiraf
4*.rs merge=mergiraf
5*.go merge=mergiraf
6*.js merge=mergiraf
7*.jsx merge=mergiraf
8*.mjs merge=mergiraf
9*.json merge=mergiraf
10*.yml merge=mergiraf
11*.yaml merge=mergiraf
12*.toml merge=mergiraf
13*.html merge=mergiraf
14*.htm merge=mergiraf
15*.xhtml merge=mergiraf
16*.xml merge=mergiraf
17*.c merge=mergiraf
18*.h merge=mergiraf
19*.cc merge=mergiraf
20*.hh merge=mergiraf
21*.cpp merge=mergiraf
22*.hpp merge=mergiraf
23*.cxx merge=mergiraf
24*.hxx merge=mergiraf
25*.c++ merge=mergiraf
26*.h++ merge=mergiraf
27*.mpp merge=mergiraf
28*.cppm merge=mergiraf
29*.ixx merge=mergiraf
30*.tcc merge=mergiraf
31*.cs merge=mergiraf
32*.dart merge=mergiraf
33*.dts merge=mergiraf
34*.scala merge=mergiraf
35*.sbt merge=mergiraf
36*.ts merge=mergiraf
37*.tsx merge=mergiraf
38*.py merge=mergiraf
39*.php merge=mergiraf
40*.phtml merge=mergiraf
41*.sol merge=mergiraf
42*.lua merge=mergiraf
43*.rb merge=mergiraf
44*.nix merge=mergiraf
45*.sv merge=mergiraf
46*.svh merge=mergiraf
1* merge=mergiraf
3# Diff drivers select hunk headers, word-diff boundaries, and `grep -W` context.
4# Every driver below ships with git except `zig`, which is defined in gitconfig.
5# One pattern per line: gitattributes reads the first field as the pattern.
6*.adb diff=ada
7*.ads diff=ada
8*.bash diff=bash
9*.bib diff=bibtex
10*.c diff=cpp
11*.cc diff=cpp
12*.cpp diff=cpp
13*.cxx diff=cpp
14*.h diff=cpp
15*.hh diff=cpp
16*.hpp diff=cpp
17*.hxx diff=cpp
18*.cs diff=csharp
19*.css diff=css
20*.dts diff=dts
21*.dtsi diff=dts
22*.ex diff=elixir
23*.exs diff=elixir
24*.f diff=fortran
25*.f90 diff=fortran
26*.f95 diff=fortran
27*.go diff=golang
28*.htm diff=html
29*.html diff=html
30*.xhtml diff=html
31*.java diff=java
32*.kt diff=kotlin
33*.kts diff=kotlin
34*.lua diff=lua
35*.markdown diff=markdown
36*.md diff=markdown
37*.mm diff=objc
38*.pas diff=pascal
39*.pp diff=pascal
40*.php diff=php
41*.phtml diff=php
42*.pl diff=perl
43*.pm diff=perl
44*.py diff=python
45*.R diff=r
46*.rb diff=ruby
47*.rs diff=rust
48*.scm diff=scheme
49*.ss diff=scheme
50*.cls diff=tex
51*.sty diff=tex
52*.tex diff=tex
53*.zig diff=zig
54*.zon diff=zig
56# textconv: make opaque formats reviewable.
57*.class diff=javap
58*.jar diff=zip
59*.war diff=zip
60*.apk diff=zip
61*.docx diff=pandoc
62*.odt diff=pandoc
64# Config languages git ships no driver for.
65*.toml diff=toml
66*.yaml diff=yaml
67*.yml diff=yaml

git/gitconfig

Modified

+98 / −58 text lines

44 ci = commit --all
55 co = checkout
66 bare = clone --bare
7 l = log --all --graph --pretty=format:'%C(magenta)%h %C(white) %an %ar%C(auto) %D%n%s%n'
7 d = diff
8 dc = diff --cached
9 dd = -c diff.external=difft diff
10 di = difftool --tool=idea --dir-diff --no-symlinks
11 dib = "!f() { base='@{upstream}'; git di \"${1:-$base}...${2:-HEAD}\"; }; f"
12 dz = difftool --tool zed
13 l = log
14 lg = log --graph --oneline --decorate
15 s = show
816 m = mergetool
17 rb = rebase @{upstream}
918 ra = rebase --abort
1019 rc = rebase --continue
20 ri = rebase --interactive
21 rs = rebase --interactive --autosquash
1122 st = status --short
12 w = worktree
13 unstage = reset HEAD --
23 unstage = restore --staged
24 upstream = rev-parse --abbrev-ref --symbolic-full-name @{upstream}
1425 last = log -1 HEAD
15 ui = !gitu
16 down = "!sh -c 'git pull --recurse-submodules \"$@\" && git submodule sync --recursive && git submodule update --init --recursive' -"
26 amend = commit --amend
27 fixup = commit --fixup
28 pf = push --force-with-lease
1830[core]
19 attributesfile = .gitattributes
31 attributesfile = ~/.config/git/gitattributes
2032 autocrlf = false
21 compression = 9
33 safecrlf = false
2234 editor = nvim
2335 fscache = true
2436 fsmonitor = true
25 preloadindex = true
2637 quotepath = false
27 safecrlf = false
2838 symlinks = true
2939 untrackedcache = true
30 pager = delta
31 compression = 9
32 whitespace = error
40 pager = delta
3442[log]
3543 abbrevCommit = true
4856 upstream = green
4957 plain = blue
59[apply]
60 # `error` is an action, not a core.whitespace token: refuse to apply patches
61 # that introduce whitespace damage instead of merely warning.
62 whitespace = error
5164[advice]
5265 addEmptyPathSpec = false
5366 pushNonFastForward = false
8396 ui = auto
8598[rebase]
86 autoStash = true
99 autoStash = false
87100 updateRefs = true
88101 missingCommitsCheck = warn
91104 enabled = true
92105 autoupdate = true
94[diff]
95 context = 3
96 renames = copies
97 interHunkContext = 10
98 colorMoved = default
99 tool = zed
101107[difftool]
102108 prompt = false
104[difftool "zed"]
105 cmd = "zeditor --wait --diff \"$LOCAL\" \"$REMOTE\""
110[difftool "idea"]
111 cmd = "\"$(command -v idea || command -v idea.cmd)\" diff --wait \"$LOCAL\" \"$REMOTE\""
107[difftool "difftastic"]
108 cmd = "difft \"$LOCAL\" \"$REMOTE\""
113[difftool "zed"]
114 # Binary is named 'zeditor' on some distros, 'zed' elsewhere.
115 cmd = "\"$(command -v zeditor || command -v zed)\" --wait --diff \"$LOCAL\" \"$REMOTE\""
117[diff "javap"]
118 textconv = javap -p -c
119 cachetextconv = true
121[diff "zip"]
122 textconv = unzip -l
123 cachetextconv = true
125[diff "pandoc"]
126 textconv = pandoc --to=markdown --wrap=none
127 cachetextconv = true
129[diff "toml"]
130 xfuncname = "^\\[.*\\]$"
132[diff "yaml"]
133 xfuncname = "^[^ \t#-].*:.*$"
135[diff "zig"]
136 # Hunk headers name the enclosing declaration in Zig and ZON sources.
137 # Capture groups would truncate the header, so the alternation is group-free.
138 xfuncname = "^pub .*$|^fn .*$|^const .*$|^var .*$|^test .*$|^export .*$|^inline .*$|^comptime .*$"
140[diff]
141 algorithm = histogram
142 colorMoved = zebra
143 colorMovedWS = allow-indentation-change
144 interHunkContext = 10
145 mnemonicPrefix = true
146 submodule = log
110148[merge]
111 tool = vim
112 autostash = true
113 conflictstyle = zdiff3
149 # Result-only Neovim view; diff3 markers retain the base revision.
150 tool = nvimdiff3
151 renormalize = true
152 autostash = false
153 conflictstyle = diff3
115155[mergetool]
116156 keepBackup = false
119159[merge "mergiraf"]
120160 name = mergiraf
121 driver = mergiraf merge --git %O %A %B -s %S -x %X -y %Y -p %P -l %L
123[mergetool "vim"]
124 cmd = "nvim -d \"$LOCAL\" \"$MERGED\" \"$REMOTE\" "
161 # A driver that exits non-zero means "conflict", so a missing mergiraf would
162 # leave the file untouched with no markers. Fall back to git's own merge.
163 driver = "sh -c 'if command -v mergiraf >/dev/null 2>&1; then exec mergiraf merge --git \"$1\" \"$2\" \"$3\" -s \"$4\" -x \"$5\" -y \"$6\" -p \"$7\" -l \"$8\"; else exec git merge-file --marker-size=\"$8\" -L \"$5\" -L \"$4\" -L \"$6\" \"$2\" \"$1\" \"$3\"; fi' -- %O %A %B %S %X %Y %P %L"
126165[branch]
127 sort = committerdate
166 sort = -committerdate
128167 autoSetupMerge = inherit
169[gpg]
170 format = ssh
172[gpg "ssh"]
173 allowedSignersFile = ~/.config/git/allowed_signers
130175[tag]
131176 sort = version:refname
177 gpgSign = true
179[transfer]
180 fsckObjects = true
182[receive]
183 fsckObjects = true
133185[fetch]
186 fsckObjects = true
187 parallel = 0
134188 prune = true
135 pruneTags = true
136189 all = true
137 recurseSubmodules = on-demand
190 recurseSubmodules = false
139192[push]
140193 autoSetupRemote = true
141194 default = current
142195 followTags = true
196 recurseSubmodules = check
144198[pull]
145 default = current
146199 rebase = true
147 recurseSubmodules = on-demand
200 recurseSubmodules = false
149202[interactive]
150203 diffFilter = delta --color-only
162215[commit]
163216 verbose = true
217 gpgSign = true
165219[submodule]
166 recurse = true
220 recurse = false
221 fetchJobs = 0
168[difftool "difftastic"]
169 # See `man git-difftool` for a description of MERGED, LOCAL and REMOTE.
170 cmd = difft "$MERGED" "$LOCAL" "abcdef1" "100644" "$REMOTE" "abcdef2" "100644"
223[checkout]
224 workers = 0
172[difftool]
173 # Run the difftool immediately, don't ask 'are you sure' each time.
174 prompt = false
226[column]
227 ui = auto
176[pager]
177 # Use a pager if the difftool output is larger than one screenful,
178 # consistent with the behaviour of `git diff`.
179 difftool = true
181[diff]
182 # Set difftastic as the default difftool, so we don't need to specify
183 # `-t difftastic` every time.
184 tool = difftastic
185 algorithm = histogram
186 colorMoved = plain
187 mnemonicPrefix = true
188 renames = true
189 submodule = log
229[safe]
230 bareRepository = explicit
191232[worktree]
192233 guessRemote = true
193 useRelativePaths = true
195235# In order to have host-specific configuration, I include additional settings here.
196236# On each host a different file might be symlinked into '.gitconfig.include'.

git/gitconfig.bugabinga

Modified

+1 / −0 text lines

11[user]
22 name = Oliver Jan Krylow
33 email = oliver@bugabinga.net
4 signingKey = ~/.ssh/github.key
56[sendemail]
67 smtpserver = box.bugabinga.net

git/gitconfig.isp

Modified

+15 / −38 text lines

1[user]
2 name = Oliver Krylow
3 email = o.krylow@isp-insoft.de
4
5[gui]
6 fontui = -family \"PT Mono\" -size 12 -weight normal -slant roman -underline 0 -overstrike 0
7 fontdiff = -family Cousine -size 12 -weight normal -slant roman -underline 0 -overstrike 0
8
9[sendemail]
10 smtpserver = sslout.df.eu
11 smtpuser = o.krylow@isp-insoft.de
12 smtpencryption = ssl
13 smtpserverport = 465
14 annotate = yes
15
16[core]
17# Windows Linebreaks behalten, wir nutzen gitattributes für explizite Kontrolle
18 autocrlf = false
19[branch]
20# Immer den neusten Branch auf anhieb finden, da diese wahrscheinlich relevanter sind
21 sort = committerdate
22[pull]
23# führt git pull mit --rebase aus, um unnötige Merge-Commits zu vermeiden
24 rebase = true
25[rebase]
26# Stashed und Entstashed lokale Änderungen um Konflikte beim Rebase zu vermeiden
27 autostash = true
28# Falls gestackte PRs verwendet werden (absichtlich oder ausversehen), wird hier der Workflow vereinfacht
29 updateRefs = true
30[merge]
31# Stashed und Entstashed lokale Änderungen um Konflikte beim Merge zu vermeiden
32 autostash = true
33[push]
34# Spart einem bei neuen Branches immer wieder den Remote-Server und Branch spezifizieren zu müssern
35 autoSetupRemote = true
36[submodule]
37# Erspart einem ein manuelles git submodule update bei jedem git checkout (branch switch)
38 recurse = true
1[user]
2 name = Oliver Krylow
3 email = o.krylow@isp-insoft.de
4 signingKey = ~/.ssh/code.isp-insoft.de
5
6[gui]
7 fontui = -family \"PT Mono\" -size 12 -weight normal -slant roman -underline 0 -overstrike 0
8 fontdiff = -family Cousine -size 12 -weight normal -slant roman -underline 0 -overstrike 0
9
10[sendemail]
11 smtpserver = sslout.df.eu
12 smtpuser = o.krylow@isp-insoft.de
13 smtpencryption = ssl
14 smtpserverport = 465
15 annotate = yes

git/ignore

Modified

+2 / −0 text lines

11.superpowers/
2.super/
3.pi/tune/

helix/config.toml

Deleted
deleted file mode 100644

+0 / −103 text lines

1theme = "nugu-dark"
2
3[editor]
4shell = ["nu", "--commands"]
5true-color = true
6mouse = true
7
8line-number = "relative"
9rulers = [81, 121, 141]
11auto-completion = true
12completion-trigger-len = 3
13auto-info = true
14auto-pairs = false
15auto-format = true
16auto-save = true
18idle-timeout = 200
20scrolloff = 5
21scroll-lines = 1
23color-modes = true
24bufferline = "multiple"
26[editor.statusline]
27left = [
28 "mode",
29 "spacer",
30 "selections",
31 "position",
32 "separator",
33 "position-percentage",
34]
35center = [
36 "version-control",
37 "separator",
38 "file-name",
39 "spacer",
40 "file-modification-indicator",
41 "separator",
42 "file-encoding",
43 "file-line-ending",
44 "file-type",
45]
46right = ["diagnostics", "spacer", "spinner"]
47separator = "·"
48mode.normal = ""
49mode.insert = ""
50mode.select = ""
52[editor.lsp]
53display-messages = true
54display-inlay-hints = true
57[editor.cursor-shape]
58normal = "block"
59insert = "bar"
60select = "underline"
62[editor.file-picker]
63hidden = false
65[editor.whitespace.render]
66space = "all"
67tab = "all"
68newline = "none"
70[editor.whitespace.characters]
71space = "·"
72nbsp = "⍽"
73newline = "⏎"
75[editor.indent-guides]
76render = false
77character = "▏"
78skip-levels = 2
80[editor.soft-wrap]
81enable = true
83[keys.normal]
84# move current line up
85A-k = [
86 "extend_to_line_bounds",
87 "delete_selection",
88 "move_line_up",
89 "paste_before",
90]
91# move current line down
92A-j = ["extend_to_line_bounds", "delete_selection", "paste_after"]
93"A-=" = ":format"
95[keys.insert]
96up = "no_op"
97down = "no_op"
98left = "no_op"
99right = "no_op"
100pageup = "no_op"
101pagedown = "no_op"
102home = "no_op"
103end = "no_op"

helix/languages.toml

Deleted
deleted file mode 100644

+0 / −20 text lines

1[[language]]
2name = "nasm"
3auto-format = true
4language-servers = [{ name = "asm-lsp" }]
5
6[[language]]
7name = "xml"
8auto-format = false
9language-servers = [{ name = "lemminx" }]
11[[language]]
12name = "java"
13auto-format = false
14language-servers = [{ name = "jdtls" }]
16[language-server.asm-lsp]
17command = "asm-lsp"
19[language-server.lemminx]
20command = "lemminx"

helix/themes/nugu-dark.toml

Deleted
deleted file mode 100644

+0 / −142 text lines

1# SYNTAX THEME
2# modifiers:
3# # - bold
4# - dim
5# - italic
6# - slow_blink
7# - rapid_blink
8# - reversed
9# - hidden
10# - crossed_out
12# underline:
13# - style
14# - line
15# - curl
16# - dashed
17# - dotted
18# - double_line
19# - color
21"comment" = { fg = "important_global", modifiers = ["bold"] }
22"string" = { fg = "important_local", modifiers = ["italic"] }
23"comment.block.documentation" = { fg = "minor", modifiers = ["dim"] }
24"punctuation" = { fg = "minor" }
25"keyword" = { fg = "minor" }
26"tag" = { fg = "minor" }
27"keyword.control.return" = { modifiers = ["bold"], underline.style = "line" }
28"keyword.control.exception" = { modifiers = ["bold"], underline.style = "line" }
29"operator" = { fg = "minor" }
30"variable.parameter" = { fg = "focus", modifiers = ["bold"] }
32"markup.heading" = { fg = "important_global", modifiers = [
33 "bold",
34], underline.style = "double_line" }
35"markup.heading.marker" = { fg = "minor" }
36"markup.list" = "minor"
37"markup.bold" = { modifiers = ["bold"] }
38"markup.italic" = { modifiers = ["italic"] }
39"markup.strikethrough" = { modifiers = ["crossed_out"] }
40"markup.link.url" = "accent"
41"markup.link.text" = "important_local"
42"markup.link.label" = "important_global"
43"markup.quote" = { fg = "important_local", modifiers = ["italic"] }
44"markup.raw.inline" = { fg = "important_local" }
45"markup.raw.block" = { fg = "important_global" }
47"diff.plus" = { fg = "important_local", modifiers = ["bold"] }
48"diff.delta" = { fg = "unfocus" }
49"diff.minus" = { fg = "focus", modifiers = ["crossed_out"] }
51"ui.background" = { fg = "normal", bg = "backdrop" }
52"ui.background.separator" = { fg = "ui_minor" }
54"ui.cursor" = { fg = "normal", bg = "accent" }
55"ui.cursor.primary" = { fg = "normal", bg = "accent" }
56"ui.cursor.match" = { fg = "normal", bg = "unfocus", modifiers = [
57 "slow_blink",
58] }
60"ui.cursorline.primary" = { bg = "debug" }
62"ui.selection" = { fg = "normal", bg = "ui_important_local" }
63"ui.selection.primary" = { fg = "normal", bg = "ui_important_global" }
65"ui.linenr" = { fg = "ui_unfocus" }
66"ui.linenr.selected" = { fg = "ui_accent" }
68"ui.statusline" = { fg = "ui_minor", bg = "ui_backdrop" }
69"ui.statusline.separator" = { fg = "ui_unfocus", bg = "ui_backdrop" }
70"ui.statusline.insert" = { fg = "ui_important_global", modifiers = ["bold"] }
71"ui.statusline.select" = { fg = "ui_focus", modifiers = ["bold"] }
72"ui.statusline.inactive" = { fg = "ui_unfocus", bg = "ui_backdrop" }
74"ui.bufferline" = { fg = "ui_minor", bg = "ui_backdrop" }
75"ui.bufferline.active" = { fg = "ui_important_global", bg = "ui_unfocus", modifiers = [
76 "bold",
77], underline = { style = "double_line", color = "ui_backdrop" } }
79"ui.gutter" = { bg = "ui_backdrop" }
81"ui.debug.breakpoint" = { fg = "ui_important_global" }
82"ui.debug.active" = { fg = "ui_important_global" }
84"ui.window" = { fg = "ui_unfocus", bg = "ui_backdrop" }
86"ui.help" = { fg = "ui_important_global", bg = "ui_backdrop" }
88"ui.text" = { fg = "normal", bg = "backdrop" }
89"ui.text.focus" = { fg = "ui_focus" }
90"ui.text.info" = { fg = "ui_normal", bg = "ui_backdrop" }
91"ui.text.inactive" = { fg = "ui_minor" }
93"ui.menu" = { fg = "ui_normal", bg = "ui_backdrop" }
94"ui.menu.selected" = { fg = "ui_focus", bg = "ui_backdrop", modifiers = [
95 "bold",
96] }
97"ui.menu.scroll" = { fg = "ui_accent", bg = "ui_backdrop" }
99"ui.popup" = { fg = "normal", bg = "backdrop" }
100"ui.popup.info" = { fg = "ui_minor", bg = "ui_backdrop" }
102"ui.highlight" = { bg = "ui_focus" }
103"ui.highlight.frameline" = { bg = "ui_important_global" }
105"ui.virtual.ruler" = { bg = "ui_unfocus" }
106"ui.virtual.whitespace" = { fg = "ui_unfocus" }
107"ui.virtual.inlay-hint" = { fg = "ui_minor" }
109"error" = { bg = "error" }
110"warning" = { bg = "warning" }
111"info" = { bg = "info" }
112"hint" = { fg = "info", modifiers = ["dim"] }
113"diagnostic.error" = { underline = { style = "double_line", color = "error" } }
114"diagnostic.warning" = { underline = { style = "double_line", color = "warning" } }
115"diagnostic.info" = { underline = { style = "double_line", color = "info" } }
116"diagnostic.hint" = { underline = { style = "double_line", color = "info" }, modifiers = [
117 "dim",
118] }
119"special" = { fg = "debug" }
121[palette]
123normal = "#ededed"
124backdrop = "#121212"
125accent = "#d151d1"
126important_local = "#b59ae4"
127important_global = "#dfd3f3"
128minor = "#8b8b8b"
129focus = "#7ba1aa"
130unfocus = "#5d5d5d"
131ui_normal = "#dbdbdb"
132ui_backdrop = "#242424"
133ui_accent = "#d86dd8"
134ui_important_global = "#f3effb"
135ui_important_local = "#c9b6eb"
136ui_minor = "#9d9d9d"
137ui_focus = "#9aabae"
138ui_unfocus = "#6f6f6f"
139error = "#ec6376"
140warning = "#f0ee69"
141info = "#3ec5e3"
142debug = "#ed5eed"

helix/themes/nugu-light.toml

Deleted
deleted file mode 100644

+0 / −142 text lines

1# SYNTAX THEME
2# modifiers:
3# # - bold
4# - dim
5# - italic
6# - slow_blink
7# - rapid_blink
8# - reversed
9# - hidden
10# - crossed_out
12# underline:
13# - style
14# - line
15# - curl
16# - dashed
17# - dotted
18# - double_line
19# - color
21"comment" = { fg = "important_global", modifiers = ["bold"] }
22"string" = { fg = "important_local", modifiers = ["italic"] }
23"comment.block.documentation" = { fg = "minor", modifiers = ["dim"] }
24"punctuation" = { fg = "minor" }
25"keyword" = { fg = "minor" }
26"tag" = { fg = "minor" }
27"keyword.control.return" = { modifiers = ["bold"], underline.style = "line" }
28"keyword.control.exception" = { modifiers = ["bold"], underline.style = "line" }
29"operator" = { fg = "minor" }
30"variable.parameter" = { fg = "focus", modifiers = ["bold"] }
32"markup.heading" = { fg = "important_global", modifiers = [
33 "bold",
34], underline.style = "double_line" }
35"markup.heading.marker" = { fg = "minor" }
36"markup.list" = "minor"
37"markup.bold" = { modifiers = ["bold"] }
38"markup.italic" = { modifiers = ["italic"] }
39"markup.strikethrough" = { modifiers = ["crossed_out"] }
40"markup.link.url" = "accent"
41"markup.link.text" = "important_local"
42"markup.link.label" = "important_global"
43"markup.quote" = { fg = "important_local", modifiers = ["italic"] }
44"markup.raw.inline" = { fg = "important_local" }
45"markup.raw.block" = { fg = "important_global" }
47"diff.plus" = { fg = "important_local", modifiers = ["bold"] }
48"diff.delta" = { fg = "unfocus" }
49"diff.minus" = { fg = "focus", modifiers = ["crossed_out"] }
51"ui.background" = { fg = "normal", bg = "backdrop" }
52"ui.background.separator" = { fg = "ui_minor" }
54"ui.cursor" = { fg = "normal", bg = "accent" }
55"ui.cursor.primary" = { fg = "normal", bg = "accent" }
56"ui.cursor.match" = { fg = "normal", bg = "unfocus", modifiers = [
57 "slow_blink",
58] }
60"ui.cursorline.primary" = { bg = "debug" }
62"ui.selection" = { fg = "normal", bg = "ui_important_local" }
63"ui.selection.primary" = { fg = "normal", bg = "ui_important_global" }
65"ui.linenr" = { fg = "ui_unfocus" }
66"ui.linenr.selected" = { fg = "ui_accent" }
68"ui.statusline" = { fg = "ui_minor", bg = "ui_backdrop" }
69"ui.statusline.separator" = { fg = "ui_unfocus", bg = "ui_backdrop" }
70"ui.statusline.insert" = { fg = "ui_important_global", modifiers = ["bold"] }
71"ui.statusline.select" = { fg = "ui_focus", modifiers = ["bold"] }
72"ui.statusline.inactive" = { fg = "ui_unfocus", bg = "ui_backdrop" }
74"ui.bufferline" = { fg = "ui_minor", bg = "ui_backdrop" }
75"ui.bufferline.active" = { fg = "ui_important_global", bg = "ui_unfocus", modifiers = [
76 "bold",
77], underline = { style = "double_line", color = "ui_backdrop" } }
79"ui.gutter" = { bg = "ui_backdrop" }
81"ui.debug.breakpoint" = { fg = "ui_important_global" }
82"ui.debug.active" = { fg = "ui_important_global" }
84"ui.window" = { fg = "ui_unfocus", bg = "ui_backdrop" }
86"ui.help" = { fg = "ui_important_global", bg = "ui_backdrop" }
88"ui.text" = { fg = "normal", bg = "backdrop" }
89"ui.text.focus" = { fg = "ui_focus" }
90"ui.text.info" = { fg = "ui_normal", bg = "ui_backdrop" }
91"ui.text.inactive" = { fg = "ui_minor" }
93"ui.menu" = { fg = "ui_normal", bg = "ui_backdrop" }
94"ui.menu.selected" = { fg = "ui_focus", bg = "ui_backdrop", modifiers = [
95 "bold",
96] }
97"ui.menu.scroll" = { fg = "ui_accent", bg = "ui_backdrop" }
99"ui.popup" = { fg = "normal", bg = "backdrop" }
100"ui.popup.info" = { fg = "ui_minor", bg = "ui_backdrop" }
102"ui.highlight" = { bg = "ui_focus" }
103"ui.highlight.frameline" = { bg = "ui_important_global" }
105"ui.virtual.ruler" = { bg = "ui_unfocus" }
106"ui.virtual.whitespace" = { fg = "ui_unfocus" }
107"ui.virtual.inlay-hint" = { fg = "ui_minor" }
109"error" = { bg = "error" }
110"warning" = { bg = "warning" }
111"info" = { bg = "info" }
112"hint" = { fg = "info", modifiers = ["dim"] }
113"diagnostic.error" = { underline = { style = "double_line", color = "error" } }
114"diagnostic.warning" = { underline = { style = "double_line", color = "warning" } }
115"diagnostic.info" = { underline = { style = "double_line", color = "info" } }
116"diagnostic.hint" = { underline = { style = "double_line", color = "info" }, modifiers = [
117 "dim",
118] }
119"special" = { fg = "debug" }
121[palette]
123normal = "#121212"
124backdrop = "#ededed"
125accent = "#ae2eae"
126important_local = "#715696"
127important_global = "#4f3c69"
128minor = "#3b3b3b"
129focus = "#184e5b"
130unfocus = "#6f6f6f"
131ui_normal = "#242424"
132ui_backdrop = "#dbdbdb"
133ui_accent = "#922792"
134ui_important_global = "#3e2f53"
135ui_important_local = "#604980"
136ui_minor = "#292929"
137ui_focus = "#15333b"
138ui_unfocus = "#5d5d5d"
139error = "#bd172e"
140warning = "#6e6c10"
141info = "#116477"
142debug = "#a112a1"

hypr/AGENTS.md

Deleted
deleted file mode 100644

+0 / −42 text lines

1# AGENTS — Nugu theming
2
3Scope: `hypr/` desktop theming.
4
5Rules:
6- Nugu generators output palette/color fragments only when app supports import/include.
7- Keep app behavior/layout/fonts/spacing in app config dir.
8- Do not duplicate whole app configs in `nugu/`.
9- Use generated fragments:
10 - Ironbar: `ironbar/nugu.css` via `@import url("nugu.css")`
11 - Mako: `mako/nugu.conf` via `include=~/.config/mako/nugu.conf`
12 - Hypr Lua: `hypr/generated/nugu.lua`
13 - Runtime JSON: `hypr/generated/nugu.json`
14- Runtime switcher `hypr/scripts/theme.lua` writes active color fragments under `$XDG_CONFIG_HOME`.
16Hyprtoolkit:
17- Never rewrite `hyprtoolkit.conf` while Hyprtoolkit apps run.
18- Bug: https://github.com/hyprwm/hyprtoolkit/issues/92
19- Static session config only until fixed.
21Nugu semantics:
22- `content.*` = app/content/terminal text surfaces.
23- `ui.*` = chrome/widgets/borders/status bars.
24- `error|warning|info|debug` = semantic signal colors.
25- Active UI: bg `ui.focus`, fg `content.backdrop`.
26- Hover/accent UI: bg `ui.accent`, fg `content.backdrop`.
27- Muted UI text: `ui.minor` over `ui.backdrop`.
28- Borders/accent lines: `ui.accent`.
30Accessibility:
31- Check critical fg/bg pairs with `pastel format luminance` or `pastel textcolor`.
32- Target ≥4.5 contrast; prefer ≥7 for small bar text.
33- Verify screenshots; CSS cascade/child labels may override intended colors.
35Fonts:
36- Use IBM Plex family exclusively in Hypr desktop configs.
37- UI sans: `IBM Plex Sans`; mono/status: `IBM Plex Mono`.
39Testing:
40- After theme edits: `NUGU_NO_NOTIFY=1 hypr/scripts/theme.lua dark|light`.
41- Check `systemctl --user is-active mako.service ironbar.service hyprpaper.service`.
42- Screenshot dark/light with `grim`; inspect actual rendered colors, not just CSS.

hypr/generated/nugu.json

Deleted
deleted file mode 100644

+0 / −54 text lines

1{
2 "dark": {
3 "debug": "#ed5eed",
4 "error": "#ec6376",
5 "warning": "#f0ee69",
6 "info": "#3ec5e3",
7 "content": {
8 "normal": "#ededed",
9 "backdrop": "#121212",
10 "accent": "#d151d1",
11 "minor": "#8b8b8b",
12 "focus": "#7ba1aa",
13 "unfocus": "#5d5d5d",
14 "important_local": "#b59ae4",
15 "important_global": "#dfd3f3"
16 },
17 "ui": {
18 "normal": "#dbdbdb",
19 "backdrop": "#242424",
20 "accent": "#d86dd8",
21 "minor": "#9d9d9d",
22 "focus": "#9aabae",
23 "unfocus": "#6f6f6f",
24 "important_local": "#c9b6eb",
25 "important_global": "#f3effb"
26 }
27 },
28 "light": {
29 "debug": "#a112a1",
30 "error": "#bd172e",
31 "warning": "#6e6c10",
32 "info": "#116477",
33 "content": {
34 "normal": "#121212",
35 "backdrop": "#ededed",
36 "accent": "#ae2eae",
37 "minor": "#3b3b3b",
38 "focus": "#184e5b",
39 "unfocus": "#6f6f6f",
40 "important_local": "#715696",
41 "important_global": "#4f3c69"
42 },
43 "ui": {
44 "normal": "#242424",
45 "backdrop": "#dbdbdb",
46 "accent": "#922792",
47 "minor": "#292929",
48 "focus": "#15333b",
49 "unfocus": "#5d5d5d",
50 "important_local": "#604980",
51 "important_global": "#3e2f53"
52 }
53 }
54}No final newline

hypr/generated/nugu.lua

Deleted
deleted file mode 100644

+0 / −88 text lines

1local palette = {
2 dark = {
3 debug = "#ed5eed",
4 error = "#ec6376",
5 warning = "#f0ee69",
6 info = "#3ec5e3",
7 content = {
8 normal = "#ededed",
9 backdrop = "#121212",
10 accent = "#d151d1",
11 minor = "#8b8b8b",
12 focus = "#7ba1aa",
13 unfocus = "#5d5d5d",
14 important_local = "#b59ae4",
15 important_global = "#dfd3f3",
16 },
17 ui = {
18 normal = "#dbdbdb",
19 backdrop = "#242424",
20 accent = "#d86dd8",
21 minor = "#9d9d9d",
22 focus = "#9aabae",
23 unfocus = "#6f6f6f",
24 important_local = "#c9b6eb",
25 important_global = "#f3effb",
26 },
27 },
28 light = {
29 debug = "#a112a1",
30 error = "#bd172e",
31 warning = "#6e6c10",
32 info = "#116477",
33 content = {
34 normal = "#121212",
35 backdrop = "#ededed",
36 accent = "#ae2eae",
37 minor = "#3b3b3b",
38 focus = "#184e5b",
39 unfocus = "#6f6f6f",
40 important_local = "#715696",
41 important_global = "#4f3c69",
42 },
43 ui = {
44 normal = "#242424",
45 backdrop = "#dbdbdb",
46 accent = "#922792",
47 minor = "#292929",
48 focus = "#15333b",
49 unfocus = "#5d5d5d",
50 important_local = "#604980",
51 important_global = "#3e2f53",
52 },
53 },
54}
56local M = {}
58function M.mode()
59 local path = os.getenv("HOME") .. "/.cache/nugu/mode"
60 local file = io.open(path, "r")
61 if not file then return "dark" end
62 local mode = file:read("*l") or "dark"
63 file:close()
64 if mode == "light" then return "light" end
65 return "dark"
66end
68function M.current()
69 return palette[M.mode()]
70end
72function M.get(mode)
73 return palette[mode]
74end
76function M.hex(color)
77 return color:gsub("#", "")
78end
80function M.rgba(color, alpha)
81 return "rgba(" .. M.hex(color) .. (alpha or "ff") .. ")"
82end
84function M.rgb(color)
85 return "rgb(" .. M.hex(color) .. ")"
86end
88return M

hypr/hypridle.conf

Deleted
deleted file mode 100644

+0 / −21 text lines

1general {
2 lock_cmd = pidof hyprlock || hyprlock
3 before_sleep_cmd = loginctl lock-session
4 after_sleep_cmd = hyprctl dispatch dpms on
5}
6
7listener {
8 timeout = 600
9 on-timeout = loginctl lock-session
10}
12listener {
13 timeout = 690
14 on-timeout = hyprctl dispatch dpms off
15 on-resume = hyprctl dispatch dpms on
16}
18listener {
19 timeout = 4200
20 on-timeout = systemctl suspend
21}

hypr/hyprland.lua

Deleted
deleted file mode 100644

+0 / −12 text lines

1-- bugabinga x230 Hyprland
2-- Lua-only compositor config. Generated app configs live beside this tree.
3
4require("modules.env")
5require("modules.permissions")
6require("modules.monitors")
7require("modules.input")
8require("modules.appearance")
9require("modules.animations")
10require("modules.workspaces")
11require("modules.rules")
12require("modules.binds")

hypr/hyprlock.conf

Deleted
deleted file mode 100644

+0 / −36 text lines

1general {
2 hide_cursor = true
3 ignore_empty_input = true
4 fail_timeout = 1500
5}
6
7background {
8 monitor =
9 path = screenshot
10 color = rgba(121212ff)
11 blur_passes = 3
12 blur_size = 4
13}
15input-field {
16 monitor =
17 size = 520, 72
18 position = 0, -24
19 halign = center
20 valign = center
22 outer_color = rgba(d151d1ee)
23 inner_color = rgba(242424ee)
24 font_color = rgba(edededff)
25 check_color = rgba(7ba1aaff)
26 fail_color = rgba(e46479ff)
27 outline_thickness = 2
29 font_family = IBM Plex Mono
30 placeholder_text = 󰌾 unlock
31 fail_text = nope
33 rounding = 7
34 shadow_passes = 0
35 fade_on_empty = false
36}

hypr/hyprpaper.conf

Deleted
deleted file mode 100644

+0 / −7 text lines

1wallpaper {
2 monitor =
3 path = ~/.config/hypr/wallpapers/nugu-dark.png
4}
5
6splash = false
7ipc = true

hypr/hyprsunset.conf

Deleted
deleted file mode 100644

+0 / −12 text lines

1# Time-based blue-light filter, independent from Nugu light/dark mode.
2# hyprsunset applies the latest profile at startup, then switches at each time.
3
4profile {
5 time = 07:00
6 identity = true
7}
8
9profile {
10 time = 19:00
11 temperature = 4500
12}

hypr/hyprtoolkit.conf

Deleted
deleted file mode 100644

+0 / −25 text lines

1# Nugu Hyprtoolkit palette.
2# Static for now: live rewrites busy-loop Hyprtoolkit apps.
3# https://github.com/hyprwm/hyprtoolkit/issues/92
4
5background = 0xFF121212
6base = 0xFF242424
7alternate_base = 0xFF2E2E2E
8text = 0xFFEDEDED
9bright_text = 0xFFF3EFFB
10link_text = 0xFF3EC5DD
11accent = 0xFFD86DD8
12accent_secondary = 0xFFB59AE4
14rounding_large = 12
15rounding_small = 7
17h1_size = 21
18h2_size = 16
19h3_size = 13
20font_size = 11
21small_font_size = 10
23font_family = IBM Plex Sans
24font_family_monospace = IBM Plex Mono
25icon_theme = Adwaita

hypr/lib/apps.lua

Deleted
deleted file mode 100644

+0 / −23 text lines

1local tui = require("scripts.tui_tab")
2
3return {
4 terminal = "wezterm connect unix",
5 terminal_class = "wezterm start --always-new-process --class",
6 browser = "firefox",
7 editor = "nvim",
8 launcher = "hyprlauncher",
9 file_manager = function() tui.spawn("yazi") end,
10 bluetooth = function() tui.spawn("bluetui") end,
11 wifi = function() tui.spawn("impala") end,
12 lock = "hyprlock",
13 logout = "hyprshutdown --dry-run",
14 theme_toggle = "lua ~/.config/hypr/scripts/theme.lua toggle",
15 theme_auto = "lua ~/.config/hypr/scripts/theme.lua auto",
16 clipboard = "bash -lc 'cliphist list | hyprlauncher --dmenu | cliphist decode | wl-copy'",
17 screenshot_region = "hyprshot -m region -z",
18 screenshot_window = "hyprshot -m window -z",
19 screenshot_output = "hyprshot -m output -z",
20 screenshot_annotate = "hyprshot -m region -z -- satty --filename",
21 binds_help = "lua ~/.config/hypr/scripts/show_binds.lua",
22 clients_help = "lua ~/.config/hypr/scripts/show_clients.lua",
23}

hypr/modules/animations.lua

Deleted
deleted file mode 100644

+0 / −14 text lines

1hl.config({ animations = { enabled = true } })
2
3hl.curve("nuguEase", { type = "bezier", points = { {0.16, 1.0}, {0.3, 1.0} } })
4hl.curve("nuguSnap", { type = "bezier", points = { {0.2, 0.0}, {0.0, 1.0} } })
5hl.curve("nuguSpring", { type = "spring", mass = 1, stiffness = 80, dampening = 16 })
6
7hl.animation({ leaf = "global", enabled = true, speed = 1, bezier = "default" })
8hl.animation({ leaf = "border", enabled = true, speed = 4.0, bezier = "nuguEase" })
9hl.animation({ leaf = "windows", enabled = true, speed = 3.6, spring = "nuguSpring" })
10hl.animation({ leaf = "windowsIn", enabled = true, speed = 3.2, spring = "nuguSpring", style = "popin 88%" })
11hl.animation({ leaf = "windowsOut", enabled = true, speed = 2.0, bezier = "nuguSnap", style = "popin 92%" })
12hl.animation({ leaf = "fade", enabled = true, speed = 2.4, bezier = "nuguEase" })
13hl.animation({ leaf = "layers", enabled = true, speed = 3.0, bezier = "nuguEase" })
14hl.animation({ leaf = "workspaces", enabled = true, speed = 2.2, bezier = "nuguEase", style = "slidefade 20%" })

hypr/modules/appearance.lua

Deleted
deleted file mode 100644

+0 / −70 text lines

1local nugu = require("generated.nugu")
2local t = nugu.current()
3local rgba = nugu.rgba
4
5hl.config({
6 general = {
7 gaps_in = 4,
8 gaps_out = 8,
9 border_size = 2,
10 col = {
11 active_border = { colors = { rgba(t.content.accent, "ee"), rgba(t.content.important_local, "ee") }, angle = 42 },
12 inactive_border = rgba(t.ui.unfocus, "88"),
13 },
14 resize_on_border = true,
15 allow_tearing = false,
16 layout = "dwindle",
17 },
19 decoration = {
20 rounding = 7,
21 rounding_power = 2,
22 active_opacity = 1.0,
23 inactive_opacity = 0.96,
24 shadow = {
25 enabled = true,
26 range = 8,
27 render_power = 2,
28 color = rgba(t.content.backdrop, "cc"),
29 },
30 blur = {
31 enabled = true,
32 size = 4,
33 passes = 2,
34 vibrancy = 0.12,
35 noise = 0.02,
36 },
37 },
39 dwindle = {
40 preserve_split = true,
41 smart_split = true,
42 },
44 master = {
45 new_status = "master",
46 },
48 group = {
49 col = {
50 border_active = rgba(t.content.accent, "ee"),
51 border_inactive = rgba(t.ui.unfocus, "88"),
52 },
53 },
55 misc = {
56 force_default_wallpaper = 0,
57 disable_hyprland_logo = true,
58 disable_splash_rendering = true,
59 vrr = 0,
60 },
62 ecosystem = {
63 no_update_news = true,
64 no_donation_nag = true,
65 },
67 xwayland = {
68 enabled = false,
69 },
70})

hypr/modules/binds.lua

Deleted
deleted file mode 100644

+0 / −78 text lines

1local apps = require("lib.apps")
2local workspaces = require("modules.workspaces")
3local mod = "SUPER"
4
5local function bind(key, cmd, description)
6 local dispatcher = type(cmd) == "function" and cmd or hl.dsp.exec_cmd(cmd)
7 hl.bind(key, dispatcher, { description = description })
8end
9
10bind(mod .. " + Return", apps.terminal, "terminal: wezterm")
11bind(mod .. " + Space", apps.launcher, "launcher: hyprlauncher")
12bind(mod .. " + B", apps.browser, "browser: firefox")
13-- TUI app binds open in an existing WezTerm default mux workspace window as new tabs.
14bind(mod .. " + E", apps.file_manager, "files: yazi")
15bind(mod .. " + N", apps.wifi, "wifi: impala")
16bind(mod .. " + U", apps.bluetooth, "bluetooth: bluetui")
17hl.bind(mod .. " + Q", hl.dsp.window.close(), { description = "close window" })
18hl.bind(mod .. " + C", hl.dsp.window.close(), { description = "close window" })
19bind(mod .. " + V", apps.clipboard, "clipboard history")
20bind(mod .. " + ALT + L", apps.lock, "lock")
21bind(mod .. " + ALT + S", "loginctl lock-session && systemctl suspend", "lock + suspend")
22bind(mod .. " + SHIFT + R", "hyprctl reload", "reload hypr")
23bind(mod .. " + SHIFT + T", apps.theme_toggle, "toggle nugu light/dark")
24bind(mod .. " + CTRL + T", apps.theme_auto, "nugu auto mode now")
25bind(mod .. " + Slash", apps.binds_help, "show binds")
26bind(mod .. " + Tab", apps.clients_help, "show clients")
27bind(mod .. " + Escape", "makoctl dismiss --all", "dismiss notifications")
28bind("CTRL + ALT + Delete", apps.logout, "graceful hyprland logout")
30hl.bind(mod .. " + H", hl.dsp.focus({ direction = "left" }), { description = "focus left" })
31hl.bind(mod .. " + L", hl.dsp.focus({ direction = "right" }), { description = "focus right" })
32hl.bind(mod .. " + K", hl.dsp.focus({ direction = "up" }), { description = "focus up" })
33hl.bind(mod .. " + J", hl.dsp.focus({ direction = "down" }), { description = "focus down" })
35hl.bind(mod .. " + SHIFT + H", hl.dsp.window.move({ direction = "left" }), { description = "move left" })
36hl.bind(mod .. " + SHIFT + L", hl.dsp.window.move({ direction = "right" }), { description = "move right" })
37hl.bind(mod .. " + SHIFT + K", hl.dsp.window.move({ direction = "up" }), { description = "move up" })
38hl.bind(mod .. " + SHIFT + J", hl.dsp.window.move({ direction = "down" }), { description = "move down" })
40hl.bind(mod .. " + CTRL + H", hl.dsp.window.resize({ x = -24, y = 0, relative = true }), { description = "resize left" })
41hl.bind(mod .. " + CTRL + L", hl.dsp.window.resize({ x = 24, y = 0, relative = true }), { description = "resize right" })
42hl.bind(mod .. " + CTRL + K", hl.dsp.window.resize({ x = 0, y = -24, relative = true }), { description = "resize up" })
43hl.bind(mod .. " + CTRL + J", hl.dsp.window.resize({ x = 0, y = 24, relative = true }), { description = "resize down" })
45hl.bind(mod .. " + F", hl.dsp.window.fullscreen({ mode = "fullscreen", action = "toggle" }), { description = "fullscreen" })
46hl.bind(mod .. " + T", hl.dsp.window.float({ action = "toggle" }), { description = "toggle floating" })
47hl.bind(mod .. " + P", hl.dsp.window.pseudo({ action = "toggle" }), { description = "pseudo tile" })
48hl.bind(mod .. " + G", hl.dsp.group.toggle(), { description = "toggle group" })
49hl.bind(mod .. " + SHIFT + G", hl.dsp.group.next(), { description = "next group tab" })
51for _, ws in ipairs(workspaces.list) do
52 hl.bind(mod .. " + " .. ws.key, hl.dsp.focus({ workspace = ws.id }), { description = "workspace " .. ws.name })
53 hl.bind(mod .. " + SHIFT + " .. ws.key, hl.dsp.window.move({ workspace = ws.id }), { description = "move to " .. ws.name })
54end
56hl.bind(mod .. " + S", hl.dsp.workspace.toggle_special("scratch"), { description = "toggle scratch" })
57hl.bind(mod .. " + SHIFT + V", hl.dsp.window.move({ workspace = "special:scratch" }), { description = "send to scratch" })
58hl.bind(mod .. " + mouse_down", hl.dsp.focus({ workspace = "e+1" }))
59hl.bind(mod .. " + mouse_up", hl.dsp.focus({ workspace = "e-1" }))
60hl.bind(mod .. " + mouse:272", hl.dsp.window.drag(), { mouse = true, description = "drag window" })
61hl.bind(mod .. " + mouse:273", hl.dsp.window.resize(), { mouse = true, description = "resize window" })
63hl.bind("XF86AudioRaiseVolume", hl.dsp.exec_cmd("wpctl set-volume -l 1 @DEFAULT_AUDIO_SINK@ 2%+"), { locked = true, repeating = true })
64hl.bind("XF86AudioLowerVolume", hl.dsp.exec_cmd("wpctl set-volume @DEFAULT_AUDIO_SINK@ 2%-"), { locked = true, repeating = true })
65hl.bind("XF86AudioMute", hl.dsp.exec_cmd("wpctl set-mute @DEFAULT_AUDIO_SINK@ toggle"), { locked = true })
66hl.bind("XF86AudioMicMute", hl.dsp.exec_cmd("wpctl set-mute @DEFAULT_AUDIO_SOURCE@ toggle"), { locked = true })
67hl.bind("XF86MonBrightnessUp", hl.dsp.exec_cmd("brightnessctl -e4 -n2 set 5%+"), { locked = true, repeating = true })
68hl.bind("XF86MonBrightnessDown", hl.dsp.exec_cmd("brightnessctl -e4 -n2 set 5%-"), { locked = true, repeating = true })
69hl.bind("XF86AudioNext", hl.dsp.exec_cmd("playerctl next"), { locked = true })
70hl.bind("XF86AudioPause", hl.dsp.exec_cmd("playerctl play-pause"), { locked = true })
71hl.bind("XF86AudioPlay", hl.dsp.exec_cmd("playerctl play-pause"), { locked = true })
72hl.bind("XF86AudioPrev", hl.dsp.exec_cmd("playerctl previous"), { locked = true })
74bind("Print", apps.screenshot_region, "screenshot region")
75bind("SHIFT + Print", apps.screenshot_window, "screenshot window")
76bind("CTRL + Print", apps.screenshot_output, "screenshot output")
77bind(mod .. " + Print", apps.screenshot_annotate, "screenshot annotate")
78bind(mod .. " + SHIFT + Print", "hyprpicker -a", "pick color")

hypr/modules/env.lua

Deleted
deleted file mode 100644

+0 / −15 text lines

1hl.env("XDG_CURRENT_DESKTOP", "Hyprland")
2hl.env("XDG_SESSION_DESKTOP", "Hyprland")
3hl.env("XDG_SESSION_TYPE", "wayland")
4hl.env("GDK_BACKEND", "wayland,x11")
5hl.env("QT_QPA_PLATFORM", "wayland;xcb")
6hl.env("QT_QPA_PLATFORMTHEME", "xdgdesktopportal")
7hl.env("QT_WAYLAND_DISABLE_WINDOWDECORATION", "1")
8hl.env("SDL_VIDEODRIVER", "wayland")
9hl.env("CLUTTER_BACKEND", "wayland")
10hl.env("MOZ_ENABLE_WAYLAND", "1")
11hl.env("ELECTRON_OZONE_PLATFORM_HINT", "wayland")
12hl.env("OZONE_PLATFORM", "wayland")
13hl.env("_JAVA_AWT_WM_NONREPARENTING", "1")
14hl.env("XCURSOR_SIZE", "24")
15hl.env("HYPRCURSOR_SIZE", "24")

hypr/modules/input.lua

Deleted
deleted file mode 100644

+0 / −21 text lines

1hl.config({
2 input = {
3 kb_layout = "us",
4 kb_variant = "altgr-intl",
5 kb_model = "",
6 kb_options = "caps:none",
7 kb_rules = "",
8 repeat_rate = 40,
9 repeat_delay = 600,
10 follow_mouse = 1,
11 sensitivity = 0,
12 accel_profile = "adaptive",
13 natural_scroll = true,
14 touchpad = {
15 natural_scroll = true,
16 disable_while_typing = true,
17 },
18 },
19})
21hl.gesture({ fingers = 3, direction = "horizontal", action = "workspace" })

hypr/modules/monitors.lua

Deleted
deleted file mode 100644

+0 / −10 text lines

1-- ThinkPad X230 internal display. Fallback keeps docks/external outputs sane.
2-- ICC path stays under ~/.config so other WMs can reuse the same profile.
3hl.monitor({
4 output = "LVDS-1",
5 mode = "1366x768@60.01900",
6 position = "0x0",
7 scale = 1,
8 icc = "/home/oli/.config/icc/thinkpad_x230.icc",
9})
10hl.monitor({ output = "", mode = "preferred", position = "auto", scale = 1 })

hypr/modules/permissions.lua

Deleted
deleted file mode 100644

+0 / −5 text lines

1-- Explicitly allow the small trusted local tools this rice binds.
2-- Permission changes may require a fresh Hyprland session.
3hl.permission("/usr/(bin|local/bin)/grim", "screencopy", "allow")
4hl.permission("/usr/(bin|local/bin)/hyprshot", "screencopy", "allow")
5hl.permission("/usr/(lib|libexec|lib64)/xdg-desktop-portal-hyprland", "screencopy", "allow")

hypr/modules/rules.lua

Deleted
deleted file mode 100644

+0 / −26 text lines

1local nugu = require("generated.nugu")
2local t = nugu.current()
3
4hl.window_rule({
5 name = "suppress-maximize-events",
6 match = { class = ".*" },
7 suppress_event = "maximize",
8})
9
10hl.window_rule({ match = { class = "^(firefox|org.mozilla.firefox)$" }, workspace = "1" })
11hl.window_rule({ match = { class = "^(firefox|org.mozilla.firefox)$" }, opacity = "0.98 0.96" })
13hl.window_rule({ match = { class = "^(wezterm|org.wezfurlong.wezterm)$" }, workspace = "3" })
14hl.window_rule({ match = { class = "^yazi$" }, workspace = "3" })
16hl.window_rule({ match = { class = "^(mpv|com.github.celluloid_player.Celluloid)$" }, workspace = "5" })
17hl.window_rule({ match = { class = "^(mpv|com.github.celluloid_player.Celluloid)$" }, immediate = true })
19hl.window_rule({ match = { class = "^(pavucontrol|blueman-manager|nm-connection-editor)$" }, float = true, center = true })
20hl.window_rule({ match = { class = "^(org.gnome.Nautilus|thunar)$", title = "^(Open|Save).*" }, float = true, center = true })
21hl.window_rule({ match = { class = "(pinentry-)(.*)" }, stay_focused = true })
23hl.window_rule({ match = { float = true }, border_color = nugu.rgba(t.ui.accent, "dd") })
24hl.window_rule({ match = { fullscreen = true }, border_size = 0, rounding = 0 })
25hl.window_rule({ match = { float = false, workspace = "w[tv1]s[false]" }, border_size = 0, rounding = 0 })
26hl.window_rule({ match = { float = false, workspace = "f[1]s[false]" }, border_size = 0, rounding = 0 })

hypr/modules/workspaces.lua

Deleted
deleted file mode 100644

+0 / −21 text lines

1local M = {}
2
3M.list = {
4 { key = "1", id = "1", name = "web" },
5 { key = "2", id = "2", name = "code" },
6 { key = "3", id = "3", name = "term" },
7 { key = "4", id = "4", name = "chat" },
8 { key = "5", id = "5", name = "media" },
9 { key = "9", id = "9", name = "misc" },
10}
12for _, ws in ipairs(M.list) do
13 hl.workspace_rule({ workspace = ws.id, monitor = "LVDS-1" })
14end
16hl.workspace_rule({ workspace = "1", default = true })
17hl.workspace_rule({ workspace = "special:scratch", on_created_empty = "wezterm start --always-new-process" })
18hl.workspace_rule({ workspace = "w[tv1]s[false]", gaps_out = 0, gaps_in = 0 })
19hl.workspace_rule({ workspace = "f[1]s[false]", gaps_out = 0, gaps_in = 0 })
21return M

hypr/scripts/common.lua

Deleted
deleted file mode 100644

+0 / −37 text lines

1local M = {}
2
3function M.trim(value)
4 return (value or ""):gsub("^%s+", ""):gsub("%s+$", "")
5end
6
7function M.shell_quote(value)
8 value = tostring(value)
9 return "'" .. value:gsub("'", "'\\''") .. "'"
10end
12function M.read_command(command)
13 local pipe = io.popen(command .. " 2>/dev/null")
14 if not pipe then return "" end
15 local output = pipe:read("*a") or ""
16 pipe:close()
17 return output
18end
20function M.choose(lines)
21 if #lines == 0 then return nil end
23 local path = os.tmpname()
24 local file = assert(io.open(path, "w"))
25 for _, line in ipairs(lines) do
26 file:write(line, "\n")
27 end
28 file:close()
30 local selected = M.trim(M.read_command("hyprlauncher --dmenu < " .. M.shell_quote(path)))
31 os.remove(path)
33 if selected == "" then return nil end
34 return selected
35end
37return M

hypr/scripts/cycle_clients.lua

Deleted
deleted file mode 100644

+0 / −73 text lines

1#!/usr/bin/env lua
2
3local source = debug.getinfo(1, "S").source:gsub("^@", "")
4local script_dir = source:match("(.+)/[^/]+$") or "."
5local hypr_dir = script_dir:match("(.+)/[^/]+$") or "."
6package.path = hypr_dir .. "/?.lua;" .. hypr_dir .. "/?/init.lua;" .. package.path
7
8local common = require("scripts.common")
9
10local function focus(address)
11 if not address:match("^0x") then address = "0x" .. address end
12 local expr = "hl.dispatch(hl.dsp.focus({ window = " .. string.format("%q", "address:" .. address) .. " }))"
13 os.execute("hyprctl -q eval " .. common.shell_quote(expr))
14end
16local function parse_active()
17 return common.read_command("hyprctl activewindow"):match("^Window%s+(%S+)%s+%-%>")
18end
20local function parse_clients()
21 local clients = {}
22 local current
24 for line in common.read_command("hyprctl clients"):gmatch("[^\n]+") do
25 local address, title = line:match("^Window%s+(%S+)%s+%-%>%s+(.+):$")
26 if address then
27 current = { address = address, title = title, class = "", workspace = 0, mapped = true, hidden = false }
28 clients[#clients + 1] = current
29 elseif current then
30 local key, value = line:match("^%s*([%w_]+):%s*(.*)$")
31 if key == "class" then
32 current.class = value
33 elseif key == "workspace" then
34 current.workspace = tonumber(value:match("^(%-?%d+)")) or 0
35 elseif key == "mapped" then
36 current.mapped = value == "1"
37 elseif key == "hidden" then
38 current.hidden = value == "1"
39 end
40 end
41 end
43 local filtered = {}
44 for _, client in ipairs(clients) do
45 if client.mapped and not client.hidden then filtered[#filtered + 1] = client end
46 end
48 table.sort(filtered, function(a, b)
49 if a.workspace ~= b.workspace then return a.workspace < b.workspace end
50 if a.class ~= b.class then return a.class < b.class end
51 if a.title ~= b.title then return a.title < b.title end
52 return a.address < b.address
53 end)
55 return filtered
56end
58local direction = arg[1] == "prev" and -1 or 1
59local clients = parse_clients()
60if #clients < 2 then os.exit(0) end
62local active = parse_active()
63local index = 1
65for i, client in ipairs(clients) do
66 if client.address == active then
67 index = i
68 break
69 end
70end
72local next_index = ((index - 1 + direction) % #clients) + 1
73focus(clients[next_index].address)

hypr/scripts/show_binds.lua

Deleted
deleted file mode 100644

+0 / −77 text lines

1#!/usr/bin/env lua
2
3local source = debug.getinfo(1, "S").source:gsub("^@", "")
4local script_dir = source:match("(.+)/[^/]+$") or "."
5local hypr_dir = script_dir:match("(.+)/[^/]+$") or "."
6package.path = hypr_dir .. "/?.lua;" .. hypr_dir .. "/?/init.lua;" .. package.path
7
8local common = require("scripts.common")
9
10local modifier_bits = {
11 { bit = 64, name = "SUPER" },
12 { bit = 1, name = "SHIFT" },
13 { bit = 4, name = "CTRL" },
14 { bit = 8, name = "ALT" },
15}
17local function has_bit(value, bit)
18 return value % (bit * 2) >= bit
19end
21local function mods(mask)
22 local out = {}
23 for _, mod in ipairs(modifier_bits) do
24 if has_bit(mask, mod.bit) then out[#out + 1] = mod.name end
25 end
26 if #out == 0 then return "None" end
27 return table.concat(out, "+")
28end
30local function format_key(key)
31 if key:match("^mouse:") then return key:gsub("^mouse:", "MOUSE_") end
32 return key:upper()
33end
35local binds = {}
36local current
38for line in common.read_command("hyprctl binds"):gmatch("[^\n]+") do
39 if line:match("^bind") then
40 current = { modmask = 0, key = "?", dispatcher = "", arg = "", description = "" }
41 table.insert(binds, current)
42 elseif current then
43 local key, value = line:match("^%s*([%w_]+):%s*(.*)$")
44 if key == "modmask" then
45 current.modmask = tonumber(value) or 0
46 elseif key == "key" then
47 current.key = value
48 elseif key == "dispatcher" then
49 current.dispatcher = value
50 elseif key == "arg" then
51 current.arg = value
52 elseif key == "description" then
53 current.description = value
54 end
55 end
56end
58local labels = {}
59local by_label = {}
61for _, bind in ipairs(binds) do
62 local label = string.format("%s + %s -> %s", mods(bind.modmask), format_key(bind.key), bind.description ~= "" and bind.description or bind.dispatcher)
63 labels[#labels + 1] = label
64 by_label[label] = bind
65end
67local selected = common.choose(labels)
68if not selected then os.exit(0) end
70local bind = by_label[selected]
71if not bind then os.exit(1) end
73if bind.dispatcher == "exec" and bind.arg ~= "" then
74 os.execute(bind.arg .. " &")
75elseif bind.dispatcher ~= "" and bind.dispatcher ~= "__lua" then
76 os.execute("hyprctl dispatch " .. common.shell_quote(bind.dispatcher) .. " " .. common.shell_quote(bind.arg))
77end

hypr/scripts/show_clients.lua

Deleted
deleted file mode 100644

+0 / −48 text lines

1#!/usr/bin/env lua
2
3local source = debug.getinfo(1, "S").source:gsub("^@", "")
4local script_dir = source:match("(.+)/[^/]+$") or "."
5local hypr_dir = script_dir:match("(.+)/[^/]+$") or "."
6package.path = hypr_dir .. "/?.lua;" .. hypr_dir .. "/?/init.lua;" .. package.path
7
8local common = require("scripts.common")
9
10local clients = {}
11local current
13for line in common.read_command("hyprctl clients"):gmatch("[^\n]+") do
14 local address, title = line:match("^Window%s+(%S+)%s+%-%>%s+(.+):$")
15 if address then
16 current = { address = address, title = title, class = "?", workspace = "?" }
17 table.insert(clients, current)
18 elseif current then
19 local key, value = line:match("^%s*([%w_]+):%s*(.*)$")
20 if key == "class" then
21 current.class = value
22 elseif key == "workspace" then
23 current.workspace = value:match("%((.-)%)") or value:match("^(%S+)") or "?"
24 end
25 end
26end
28local labels = {}
29local by_label = {}
31for _, client in ipairs(clients) do
32 local label = string.format("%s: %s (%s)", client.class, client.title, client.workspace)
33 labels[#labels + 1] = label
34 by_label[label] = client
35end
37local selected = common.choose(labels)
38if not selected then os.exit(0) end
40local client = by_label[selected]
41if not client then os.exit(1) end
43local address = client.address
44if not address:match("^0x") then address = "0x" .. address end
46local target = "address:" .. address
47local expr = "hl.dispatch(hl.dsp.focus({ window = " .. string.format("%q", target) .. " }))"
48os.execute("hyprctl -q eval " .. common.shell_quote(expr))

hypr/scripts/theme.lua

Deleted
deleted file mode 100644

+0 / −212 text lines

1#!/usr/bin/env lua
2
3local source = debug.getinfo(1, "S").source:gsub("^@", "")
4local script_dir = source:match("(.+)/[^/]+$") or "."
5local hypr_dir = script_dir:match("(.+)/[^/]+$") or "."
6package.path = hypr_dir .. "/?.lua;" .. hypr_dir .. "/?/init.lua;" .. package.path
7
8local nugu = require("generated.nugu")
9
10local function trim(value)
11 return (value or ""):gsub("^%s+", ""):gsub("%s+$", "")
12end
14local function shell_quote(value)
15 value = tostring(value)
16 return "'" .. value:gsub("'", "'\\''") .. "'"
17end
19local function run(command)
20 os.execute(command .. " >/dev/null 2>&1")
21end
23local function mkdir(path)
24 run("mkdir -p " .. shell_quote(path))
25end
27local function read_file(path)
28 local file = io.open(path, "r")
29 if not file then return nil end
30 local data = file:read("*a")
31 file:close()
32 return data
33end
35local function write_file(path, content)
36 local file = assert(io.open(path, "w"))
37 file:write(content)
38 file:close()
39end
41local home = assert(os.getenv("HOME"), "HOME unset")
42local config_home = os.getenv("XDG_CONFIG_HOME") or home .. "/.config"
43local cache_dir = home .. "/.cache/nugu"
44local mode_file = cache_dir .. "/mode"
45local auto_file = cache_dir .. "/auto"
47local function active_mode()
48 local mode = trim(read_file(mode_file))
49 if mode == "light" then return "light" end
50 return "dark"
51end
53local function auto_mode()
54 local hour = tonumber(os.date("%H")) or 0
55 if hour >= 7 and hour < 19 then return "light" end
56 return "dark"
57end
59local function auto_enabled()
60 local value = read_file(auto_file)
61 return value == nil or trim(value) ~= "0"
62end
64local function set_auto(enabled)
65 mkdir(cache_dir)
66 write_file(auto_file, enabled and "1" or "0")
67end
69local function write_desktop_color_scheme(mode)
70 local scheme = mode == "dark" and "prefer-dark" or "prefer-light"
71 run("gsettings set org.gnome.desktop.interface color-scheme " .. shell_quote(scheme))
72end
74local function write_mako(p)
75 local dir = config_home .. "/mako"
76 mkdir(dir)
77 write_file(dir .. "/nugu.conf", string.format([[# Generated by hypr/scripts/theme.lua from Nugu palette.
78background-color=%see
79text-color=%sff
80border-color=%sff
81progress-color=over %sff
83[urgency=low]
84background-color=%se6
85text-color=%sff
86border-color=%sff
87progress-color=over %sff
89[urgency=normal]
90border-color=%sff
91progress-color=over %sff
93[urgency=critical]
94background-color=%sff
95text-color=%sff
96border-color=%sff
97progress-color=over %sff
99[summary~="[Ee]rror|[Ff]ailed|[Ff]ailure|[Cc]rash"]
100border-color=%sff
101progress-color=over %sff
103[summary~="[Ww]arn|[Ww]arning"]
104border-color=%sff
105progress-color=over %sff
107[summary~="[Ii]nfo|[Nn]otice"]
108border-color=%sff
109progress-color=over %sff
110]],
111 p.ui.backdrop, p.ui.normal, p.ui.accent, p.ui.focus,
112 p.content.backdrop, p.content.minor, p.ui.unfocus, p.content.minor,
113 p.ui.accent, p.ui.focus,
114 p.ui.backdrop, p.ui.important_global, p.error, p.error,
115 p.error, p.error,
116 p.warning, p.warning,
117 p.info, p.info))
118end
120local function write_ironbar(p)
121 local dir = config_home .. "/ironbar"
122 mkdir(dir)
123 write_file(dir .. "/nugu.css", string.format([[/* Generated by hypr/scripts/theme.lua from Nugu palette. */
124:root {
125 --bg: %s;
126 --bg-transparent: %see;
127 --surface: %s;
128 --fg: %s;
129 --accent: %s;
130 --focus: %s;
131 --on-focus: %s;
132 --muted: %s;
133 --unfocus: %s;
134 --error: %s;
135 --warning: %s;
136 --info: %s;
137 --debug: %s;
138 --border: %s;
139}
140]],
141 p.ui.backdrop,
142 p.ui.backdrop,
143 p.ui.minor,
144 p.ui.normal,
145 p.ui.accent,
146 p.ui.focus,
147 p.content.backdrop,
148 p.ui.minor,
149 p.ui.unfocus,
150 p.error,
151 p.warning,
152 p.info,
153 p.debug,
154 p.ui.accent))
155end
157local function apply_mode(mode)
158 mkdir(cache_dir)
159 write_file(mode_file, mode)
161 local p = assert(nugu.get(mode), "unknown mode: " .. tostring(mode))
162 write_desktop_color_scheme(mode)
163 write_mako(p)
164 write_ironbar(p)
166 run("hyprctl hyprpaper wallpaper " .. shell_quote(",~/.config/hypr/wallpapers/nugu-" .. mode .. ".png"))
167 run("hyprctl reload")
168 if os.getenv("NUGU_NO_RESTART_MAKO") ~= "1" then
169 run("systemctl --user restart mako.service")
170 end
171 run("systemctl --user restart ironbar.service")
172 if os.getenv("NUGU_NO_NOTIFY") ~= "1" then
173 run("notify-send --expire-time 1500 nugu " .. shell_quote(mode .. " mode"))
174 end
175end
177local function next_mode()
178 return active_mode() == "dark" and "light" or "dark"
179end
181local function watch()
182 while true do
183 if auto_enabled() then
184 local target = auto_mode()
185 if target ~= active_mode() then apply_mode(target) end
186 end
187 os.execute("sleep 300")
188 end
189end
191local mode = arg[1] or "toggle"
193if mode == "dark" or mode == "light" or mode == "toggle" then
194 set_auto(false)
195elseif mode == "auto" then
196 set_auto(true)
197end
199if mode == "dark" or mode == "light" then
200 apply_mode(mode)
201elseif mode == "toggle" then
202 apply_mode(next_mode())
203elseif mode == "auto" then
204 apply_mode(auto_mode())
205elseif mode == "current" then
206 apply_mode(active_mode())
207elseif mode == "watch" then
208 watch()
209else
210 io.stderr:write("mode must be dark|light|toggle|auto|current|watch\n")
211 os.exit(1)
212end

hypr/scripts/theme.nu

Deleted
deleted file mode 100755

+0 / −179 text lines

1#!/usr/bin/env nu
2
3# Nugu desktop theme switcher. Writes active runtime configs, then reloads clients.
4
5const modes = [dark light]
6
7def config-home [] { $env.XDG_CONFIG_HOME? | default ($env.HOME | path join ".config") }
8def cache-dir [] { $env.HOME | path join ".cache" "nugu" }
9def mode-file [] { cache-dir | path join "mode" }
10def auto-file [] { cache-dir | path join "auto" }
11def palette-file [] { config-home | path join "hypr" "generated" "nugu.json" }
13def active-mode [] {
14 let path = (mode-file)
15 if ($path | path exists) {
16 let mode = (open --raw $path | str trim)
17 if $mode in $modes { return $mode }
18 }
19 "dark"
20}
22def auto-mode [] {
23 let hour = (date now | format date "%H" | into int)
24 if $hour >= 7 and $hour < 19 { "light" } else { "dark" }
25}
27def hex-no-hash [color: string] { $color | str replace --all "#" "" }
28def argb [color: string] { $"0xFF(hex-no-hash $color)" }
30def palette [mode: string] {
31 open (palette-file) | get $mode
32}
34def auto-enabled [] {
35 let path = (auto-file)
36 if not ($path | path exists) { return true }
37 (open --raw $path | str trim) != "0"
38}
40def set-auto [enabled: bool] {
41 (if $enabled { "1" } else { "0" }) | save --raw --force (auto-file)
42}
44def write-desktop-color-scheme [mode: string] {
45 let scheme = if $mode == "dark" { "prefer-dark" } else { "prefer-light" }
46 try { gsettings set org.gnome.desktop.interface color-scheme $scheme | ignore }
47}
49def write-hyprtoolkit [mode: string, p: record] {
50 let out = (config-home | path join "hypr" "hyprtoolkit.conf")
51 $"background = (argb $p.content.backdrop)
52base = (argb $p.ui.backdrop)
53alternate_base = (argb $p.ui.unfocus)
54text = (argb $p.content.normal)
55bright_text = (argb $p.ui.important_global)
56accent = (argb $p.ui.accent)
57accent_secondary = (argb $p.content.important_local)
58h1_size = 20
59h2_size = 16
60h3_size = 13
61font_size = 11
62small_font_size = 10
63font_family = IBM Plex Sans
64font_family_monospace = IBM Plex Mono
65icon_theme = Adwaita
66" | save --raw --force $out
67}
69def write-mako [mode: string, p: record] {
70 mkdir (config-home | path join "mako")
71 let out = (config-home | path join "mako" "nugu.conf")
72 $"# Generated by hypr/scripts/theme.nu from Nugu palette.
73background-color=($p.ui.backdrop)ee
74text-color=($p.ui.normal)ff
75border-color=($p.ui.accent)ff
76progress-color=over ($p.ui.focus)ff
78[urgency=low]
79background-color=($p.content.backdrop)e6
80text-color=($p.content.minor)ff
81border-color=($p.ui.unfocus)ff
82progress-color=over ($p.content.minor)ff
84[urgency=normal]
85border-color=($p.ui.accent)ff
86progress-color=over ($p.ui.focus)ff
88[urgency=critical]
89background-color=($p.ui.backdrop)ff
90text-color=($p.ui.important_global)ff
91border-color=($p.error)ff
92progress-color=over ($p.error)ff
94[summary~=\"[Ee]rror|[Ff]ailed|[Ff]ailure|[Cc]rash\"]
95border-color=($p.error)ff
96progress-color=over ($p.error)ff
98[summary~=\"[Ww]arn|[Ww]arning\"]
99border-color=($p.warning)ff
100progress-color=over ($p.warning)ff
102[summary~=\"[Ii]nfo|[Nn]otice\"]
103border-color=($p.info)ff
104progress-color=over ($p.info)ff
105" | save --raw --force $out
106}
108def write-ironbar [mode: string, p: record] {
109 mkdir (config-home | path join "ironbar")
110 let out = (config-home | path join "ironbar" "nugu.css")
111 let surface = $p.ui.minor
112 let on_focus = $p.content.backdrop
113 $"/* Generated by hypr/scripts/theme.nu from Nugu palette. */
114:root {
115 --bg: ($p.ui.backdrop);
116 --bg-transparent: ($p.ui.backdrop)ee;
117 --surface: ($surface);
118 --fg: ($p.ui.normal);
119 --accent: ($p.ui.accent);
120 --focus: ($p.ui.focus);
121 --on-focus: ($on_focus);
122 --muted: ($p.ui.minor);
123 --unfocus: ($p.ui.unfocus);
124 --error: ($p.error);
125 --border: ($p.ui.accent);
126}
127" | save --raw --force $out
128}
130def apply-mode [mode: string] {
131 mkdir (cache-dir)
132 let p = (palette $mode)
133 $mode | save --raw --force (mode-file)
134 write-desktop-color-scheme $mode
135 # Disabled until Hyprtoolkit handles live config rewrites without busy-looping:
136 # https://github.com/hyprwm/hyprtoolkit/issues/92
137 # write-hyprtoolkit $mode $p
138 write-mako $mode $p
139 write-ironbar $mode $p
141 try { hyprctl hyprpaper wallpaper $",~/.config/hypr/wallpapers/nugu-($mode).png" | ignore }
142 try { hyprctl reload | ignore }
143 if (($env.NUGU_NO_RESTART_MAKO? | default "") != "1") {
144 try { systemctl --user restart mako.service | ignore }
145 }
146 try { systemctl --user restart ironbar.service | ignore }
147 if (($env.NUGU_NO_NOTIFY? | default "") != "1") {
148 try { notify-send --expire-time 1500 "nugu" $"($mode) mode" | ignore }
149 }
150}
152def next-mode [] { if (active-mode) == "dark" { "light" } else { "dark" } }
154def main [mode: string = "toggle"] {
155 let manual = $mode in [dark light toggle]
156 if $manual { set-auto false }
157 if $mode == "auto" { set-auto true }
159 let target = match $mode {
160 "dark" => "dark",
161 "light" => "light",
162 "toggle" => (next-mode),
163 "auto" => (auto-mode),
164 "current" => (active-mode),
165 "watch" => { watch; return },
166 _ => { error make { msg: "mode must be dark|light|toggle|auto|current|watch" } },
167 }
168 apply-mode $target
169}
171def watch [] {
172 loop {
173 if (auto-enabled) {
174 let target = (auto-mode)
175 if $target != (active-mode) { apply-mode $target }
176 }
177 sleep 5min
178 }
179}

hypr/scripts/tui_tab.lua

Deleted
deleted file mode 100644

+0 / −36 text lines

1local M = {}
2
3local function shell_quote(value)
4 value = tostring(value)
5 return "'" .. value:gsub("'", "'\\''") .. "'"
6end
7
8local function trim(value)
9 return (value or ""):gsub("^%s+", ""):gsub("%s+$", "")
10end
12local function run(command)
13 local pipe = io.popen(command .. " 2>/dev/null")
14 if not pipe then return nil end
16 local output = pipe:read("*a")
17 pipe:close()
19 return trim(output)
20end
22function M.spawn(...)
23 local args = { ... }
24 if #args == 0 then return end
26 for i, arg in ipairs(args) do
27 args[i] = shell_quote(arg)
28 end
30 local pane_id = run("wezterm cli --prefer-mux spawn -- " .. table.concat(args, " "))
31 if pane_id and pane_id:match("^%d+$") then
32 hl.exec_cmd("wezterm cli --prefer-mux activate-pane --pane-id " .. shell_quote(pane_id))
33 end
34end
36return M

hypr/systemd/cliphist.service

Deleted
deleted file mode 100644

+0 / −12 text lines

1[Unit]
2Description=Clipboard history daemon
3PartOf=graphical-session.target
4After=graphical-session.target
5
6[Service]
7ExecStart=/usr/bin/wl-paste --type text --watch cliphist store
8Restart=on-failure
9RestartSec=2
11[Install]
12WantedBy=graphical-session.target

hypr/systemd/ironbar-workspaces.service

Deleted
deleted file mode 100644

+0 / −13 text lines

1[Unit]
2Description=Instant Ironbar workspace state
3After=graphical-session.target ironbar.service
4PartOf=graphical-session.target ironbar.service
5
6[Service]
7ExecStart=%h/.config/ironbar/scripts/workspaces-watch.py
8Restart=on-failure
9RestartSec=1
10Slice=session.slice
12[Install]
13WantedBy=graphical-session.target

hypr/systemd/ironbar.service

Deleted
deleted file mode 100644

+0 / −14 text lines

1[Unit]
2Description=Ironbar Wayland status bar
3PartOf=graphical-session.target
4After=graphical-session.target nugu-theme.service
5Wants=nugu-theme.service
6
7[Service]
8Environment=GSK_RENDERER=cairo
9ExecStart=/usr/bin/ironbar
10Restart=on-failure
11RestartSec=2
13[Install]
14WantedBy=graphical-session.target

hypr/systemd/mako.service

Deleted
deleted file mode 100644

+0 / −15 text lines

1[Unit]
2Description=Mako notification daemon
3PartOf=graphical-session.target
4After=graphical-session.target
5
6[Service]
7Environment=NUGU_NO_RESTART_MAKO=1
8Environment=NUGU_NO_NOTIFY=1
9ExecStartPre=/usr/bin/lua %h/.config/hypr/scripts/theme.lua current
10ExecStart=/usr/bin/mako --config %h/.config/mako/config
11Restart=on-failure
12RestartSec=2
14[Install]
15WantedBy=graphical-session.target

hypr/systemd/nugu-theme.service

Deleted
deleted file mode 100644

+0 / −13 text lines

1[Unit]
2Description=Nugu automatic light/dark desktop mode
3PartOf=graphical-session.target
4After=graphical-session.target hyprpaper.service
5Wants=hyprpaper.service
6
7[Service]
8ExecStart=/usr/bin/lua %h/.config/hypr/scripts/theme.lua watch
9Restart=on-failure
10RestartSec=10
12[Install]
13WantedBy=graphical-session.target

hypr/systemd/wl-clip-persist.service

Deleted
deleted file mode 100644

+0 / −12 text lines

1[Unit]
2Description=Persist Wayland clipboard after source exits
3PartOf=graphical-session.target
4After=graphical-session.target
5
6[Service]
7ExecStart=/usr/bin/wl-clip-persist --clipboard regular
8Restart=on-failure
9RestartSec=2
11[Install]
12WantedBy=graphical-session.target

hypr/wallpapers/nugu-dark.png

Deleted
deleted file mode 100644

Binary size (old → new): 9858 → 0 bytes.

hypr/wallpapers/nugu-light.png

Deleted
deleted file mode 100644

Binary size (old → new): 131656 → 0 bytes.

ironbar/PLAN.md

Deleted
deleted file mode 100644

+0 / −715 text lines

1# Ironbar rework plan
2
3Goal: rebuild the bar incrementally, one widget/behavior at a time, with Nugu colors, consistent clicks, and verification after each step.
4
5Workflow rule:
6
71. Propose exact minimal change.
82. Experiment safely when behavior is unknown.
93. Apply focused changes.
104. Verify live with config validation, service state, logs, screenshots, and interaction tests.
115. Remove superfluous widgets/CSS/scripts.
13Originally: stop after each step for discussion.
14Current standing goal: continue autonomously to completion while preserving brutal verification.
16Order rule: start with Bluetooth as requested, then proceed roughly easiest → hardest.
18## Current status
20Done/live:
22- Bluetooth stack installed/running: `bluez`, `bluez-utils`, `bluetooth.service` active.
23- `bluetui` installed and preferred as Bluetooth manager.
24- Ironbar Bluetooth widget is status-only; builtin popup disabled because GTK switch popup looked bad.
25- Bluetooth left/middle click opens `bluetui` through shared Hypr Lua TUI launcher.
26- Ironbar icon theme switched to installed `Adwaita`.
27- Ironbar `popup_autohide = true` globally.
28- WezTerm mux service added under `wezterm/systemd/wezterm-mux-server.service`, enabled and active.
29- WezTerm config attaches GUI to Unix mux (`connect unix`) and status shows `MUX` for mux domain.
30- Hypr `SUPER+Enter` opens `wezterm connect unix`.
31- Hypr TUI app binds:
32 - `SUPER+E` → `yazi`
33 - `SUPER+N` → `impala`
34 - `SUPER+U` → `bluetui`
35- TUI launcher activates the newly spawned WezTerm pane/tab.
36- XWayland disabled; obsolete XWayland drag workaround removed.
37- Mouse accel switched to adaptive; natural scroll enabled.
39Known unresolved:
41- No hard blocker.
42- Physical wheel/trackpad scroll over the volume module remains unverified because `wdotool scroll` does not trigger Ironbar layer-shell scroll events here.
43- Existing visible WezTerm local-domain sessions may need manual migration/closure; no seamless transfer to mux known.
45## Current live audit
47- Repo clean, ahead of origin; Ironbar commits are local.
48- Running services verified active: `ironbar.service`, `ironbar-workspaces.service`, `mako.service`, `hyprpaper.service`, `pipewire-pulse.socket`, system `upower.service`, system `bluetooth.service`.
49- Resource usage after settling: `ironbar` about 1.3% CPU / 77M RSS; `workspaces-watch.py` 0.0% CPU / 15M RSS.
50- Regions use Ironbar `start` / `center` / `end` boxes:
51 - start: custom workspace switcher, clipboard, bindmode
52 - center: music, clock
53 - end: Mako status, WiFi, Bluetooth, tray, CPU, volume, brightness, battery, inhibit, power
54- Polling/wakeups:
55 - Mako status script: 5000ms, shell + `makoctl list | grep`
56 - WiFi status script: 30000ms, shell + `iwctl station wlan0 show`
57 - sys_info CPU: interval 2
58 - workspace state: Hypr socket2 event watcher, 10s idle refresh, no label polling
59- Scroll handlers:
60 - volume: `wpctl set-volume -l 1 @DEFAULT_AUDIO_SINK@ 2%+` / `wpctl set-volume @DEFAULT_AUDIO_SINK@ 2%-`, `smooth_scroll_speed = 1.0`
61 - brightness: builtin systemd backlight backend, `smooth_scroll_speed = 0.5`
62- Hardcoded color grep reports only generated `ironbar/nugu.css`; `style.css` uses semantic Nugu vars.
63- Known broken/unproven widget behavior: physical volume scroll only. Slider drag and the configured scroll commands are verified.
65## Checked facts
67- Installed Ironbar: `0.19.0`.
68- `ironbar --print-schema` exposes needed modules:
69 - `battery`, `bindmode`, `bluetooth`, `brightness`, `clipboard`, `clock`, `custom`, `focused`, `inhibit`, `launcher`, `music`, `notifications`, `script`, `sys_info`, `tray`, `volume`, `workspaces`.
70- WiFi stack: `iwd` + systemd-networkd.
71 - `iwd.service`: active.
72 - `NetworkManager`: not installed.
73 - Ironbar `network_manager` module is wrong unless we intentionally switch network stacks.
74- Notifications: Mako currently.
75 - Ironbar `notifications` module requires SwayNC.
76 - SwayNC would replace/compete with Mako, so defer.
77- `hyprshutdown` installed; keybind uses `--dry-run`.
78- Music config must use `player_type = "mpris"`, not `playerctl`.
79- Builtin Ironbar workspaces dispatch legacy Hypr syntax; custom switcher is used for Lua-dispatcher compatibility.
80- Workspace highlighting is event-driven via Hypr socket2 + Ironbar vars; no polling labels.
82## Upstream feature note
84From Ironbar compiling wiki/features:
86- Default build enables all features.
87- Custom builds can disable defaults and enable selected features.
88- Must enable at least one config feature.
89- If custom-building for this setup:
91```text
92cli,config+json,workspaces+hyprland,focused,launcher,music+mpris,sys_info,script,custom,tray,volume,battery,bluetooth,brightness,bindmode,inhibit,clipboard,clock,notifications
93```
95Notes:
97- `cli` implies `ipc`.
98- `network_manager` omitted while using `iwd`.
99- `notifications` only useful if switching to SwayNC.
101## Preferences / launch policy
103- Work one thing at a time: propose → experiment → change → verify.
104- Prefer awesome fast TUIs when they exist (`bluetui`, `impala`, `btm`, `wiremix`, `yazi`, etc.).
105- Prefer mux-backed WezTerm tabs for TUI apps over standalone terminal windows.
106- Prefer implementation logic in Lua over shell snippets; shell command strings are acceptable only at process boundary.
107- Prefer `require(...)` modules over `dofile(...)` in normal config and shared helpers.
108- Shared TUI launch logic lives in Hypr Lua: `hypr/scripts/tui_tab.lua`.
109- Hypr binds call it via `require("scripts.tui_tab")`; Ironbar actions bridge through `hyprctl eval 'require("scripts.tui_tab").spawn(...)'` so both use the same implementation.
110- TUI launcher should spawn into WezTerm mux and activate the new pane/tab.
111- Keep app-specific service/config files in app dirs when possible, e.g. WezTerm systemd unit under `wezterm/systemd/`.
112- Avoid fighting ugly GTK popups when a better TUI exists; use Ironbar as status/launcher if builtin popup is poor.
114## Package/dependency report
116Already installed:
118- `ironbar`
119- `hyprshutdown`
120- `playerctl`
121- `iwd`
122- `brightnessctl`
123- `bluez`
124- `bluez-utils`
125- `bluetui`
126- `impala`
127- `wezterm-nightly-bin`
128- `upower`
129- `pipewire-pulse`
131No longer planned:
133```sh
134sudo pacman -S pavucontrol swaync networkmanager
135```
137Reasons:
139- `wiremix` replaces `pavucontrol` for audio.
140- Mako stays; SwayNC would replace/compete with it.
141- WiFi stack stays `iwd` + systemd-networkd; no NetworkManager.
143Optional only if requested later:
145```sh
146sudo pacman -S resources
147```
149Avoid unless intentionally switching network stack:
151```sh
152sudo pacman -S networkmanager
153```
155## Verification loop for every step
1571. Edit only one widget/behavior.
1582. Validate:
160 ```sh
161 ironbar --validate-config -c ~/.config/ironbar/config.json -t ~/.config/ironbar/style.css
162 ```
1643. Restart:
166 ```sh
167 systemctl --user restart ironbar.service
168 ```
1704. Inspect:
172 ```sh
173 systemctl --user status ironbar.service --no-pager
174 journalctl --user -u ironbar.service -n 80 --no-pager
175 ```
1775. Screenshot / visual check.
1786. Discuss before next step.
180## Click convention
182- Left: popup or primary action.
183- Right: toggle/mute/secondary action.
184- Middle: open full external tool/TUI.
185- Scroll: adjust continuous value.
186- Tooltip: document behavior.
188## WezTerm mux policy
190- WezTerm GUI should attach to Unix mux by default:
191 - `cfg.unix_domains = { { name = "unix", no_serve_automatically = true } }`
192 - `cfg.default_gui_startup_args = { "connect", "unix" }`
193- Mux server is systemd-managed:
194 - `wezterm/systemd/wezterm-mux-server.service`
195- WezTerm status should make mux visible:
196 - domain `unix` renders as `MUX`.
197- Hypr terminal bind should explicitly use mux:
198 - `wezterm connect unix`
199- TUI app launcher should:
200 1. spawn into mux with `wezterm cli --prefer-mux spawn -- ...`
201 2. capture pane id in Lua
202 3. activate pane with `wezterm cli --prefer-mux activate-pane --pane-id ...`
203- Existing non-mux GUI sessions cannot be seamlessly transferred into mux; recreate/close manually.
205## Nugu styling rules
207- Generated colors stay in `ironbar/nugu.css`.
208- Layout/behavior stay in `ironbar/config.json` + `ironbar/style.css`.
209- Use vars:
210 - normal fg: `--fg`
211 - muted/empty: `--muted` / `--unfocus`
212 - active bg: `--focus`, fg `--on-focus`
213 - hover/accent bg: `--accent`, fg `--on-focus`
214 - error: `--error`
216## Ordered implementation steps
218### Step 1 — Bluetooth — done
220Why first: explicit request.
222Implemented:
224- `bluez` + `bluez-utils` installed by user; `bluetooth.service` active.
225- `bluetui` installed and preferred.
226- Ironbar builtin `bluetooth` module used only for bar status.
227- Builtin Bluetooth popup disabled; GTK switch popup looked bad even after CSS work.
228- Left/middle click opens `bluetui` through shared Hypr Lua TUI launcher:
229 - `hyprctl eval 'require("scripts.tui_tab").spawn("bluetui")'`
230- Bar label uses fixed semantic Bluetooth battery icon, not dynamic percentage icon:
231 - `󰥈 {device_battery_percent}%`
232- `icon_theme` switched from missing `Papirus` to installed `Adwaita`; broken device image fixed.
234Verified:
236- Ironbar config validates.
237- Ironbar restarts and stays active.
238- Popup autohide works globally.
239- Bluetooth status visible; clicks open `bluetui`.
241Follow-up if wanted:
243- Tune bar label length/format.
244- Add notification if Bluetooth disconnected/low battery.
246### Step 2 — baseline validation + obvious fixes
248Difficulty: very easy.
250Scope:
252- Fix music `player_type`: `playerctl` → `mpris`.
253- Add `name`/`class` only where needed for CSS targeting.
254- No layout rework.
256Verify:
258- Config validates.
259- Ironbar starts cleanly.
261### Step 3 — tray
263Difficulty: very easy.
265Goal:
267- Keep tray widget.
268- Improve popover padding/colors if needed.
270Verify:
272- Existing tray icons render.
273- Menus/popovers readable.
275### Step 4 — clock/calendar colors
277Difficulty: easy.
279Goal:
281- Fix hard-to-read calendar popup.
283Scope:
285- CSS only.
286- Explicit GTK calendar selectors:
287 - `.popup-clock calendar`
288 - `.popup-clock calendar header`
289 - `.popup-clock calendar grid label.day-name`
290 - `.popup-clock calendar grid label.day-number`
291 - `.popup-clock calendar grid label.other-month`
292 - `.popup-clock calendar grid label.today`
293 - `.popup-clock calendar grid label:selected`
295Verify:
297- Popup readable in dark + light.
298- Today/current/other-month/day-name colors use Nugu vars.
300### Step 5 — clipboard
302Difficulty: easy.
304Goal:
306- Keep clipboard widget and make behavior explicit.
308Proposed behavior:
310- Left: popup/list.
311- Middle: optional external launcher later.
312- Right: do **not** clear history unless confirmed.
314Verify:
316- Popup readable.
317- Selection/paste still works.
319### Step 6 — volume — done
321Goal:
323- Make volume behavior consistent.
325Implemented:
327- Builtin `volume` module.
328- Scroll adjusts PipeWire output volume.
329- Right click mutes output.
330- Middle click opens `wiremix` through shared Hypr Lua TUI launcher.
331- Sources hidden on bar to reduce clutter.
333Verified:
335- `pipewire-pulse.socket` active.
336- Ironbar logs show volume client connected, no `PAErr(-1)`.
337- `wiremix` spawned into WezTerm mux tab and activated.
338- Popup/device picker colors fixed for dark+light Nugu.
339- Slider drag verified with `wdotool`: volume changed from 55% to 7%, then restored to 55% and unmuted.
340- Scroll actions are configured as oneshot scripts and `smooth_scroll_speed = 1.0` is explicit for wheel/trackpad input.
341- The exact scroll commands were executed manually: 55% → 57% → 55%.
342- `wdotool scroll` does not trigger Ironbar layer-shell scroll events in this live setup, so physical scroll remains the remaining manual check.
344### Step 7 — battery — done
346Difficulty: easy.
348Goal:
350- Add/keep robust battery widget.
352Implementation:
354- Builtin `battery` module.
355- Show icon + percent.
356- Style low/critical/charging states using Nugu semantic colors.
358Verified:
360- Hidden on machines without `BAT*` via `show_if`.
361- Shows X230 battery percentage.
362- `upower` active.
363- Warning/critical states styled with Nugu semantic colors.
365### Step 8 — brightness — done
367Difficulty: easy-medium.
369Goal:
371- Add brightness widget.
373Implementation:
375- Builtin `brightness` module.
376- Use `systemd`/`backlight` backend.
378Implemented:
380- Builtin brightness module with `systemd`/`intel_backlight` backend.
381- Scroll adjusts brightness through Ironbar backend.
382- Rejected custom `brightnessctl` script experiment because direct set failed without permission.
384Verified:
386- Detects `intel_backlight`.
387- Brightness visible/readable in screenshots.
388- No config/service errors.
390Known issue (scroll does not change brightness):
392- `ironbar.service` runs under the user manager, so the process is in a sessionless scope. Ironbar's `systemd` brightness backend calls `org.freedesktop.login1` `SetBrightness`, which is rejected with `org.freedesktop.login1.NotYourDevice: Session is not in foreground, refusing.`
393- Root cause is session ownership, not config. The Ironbar config is already correct (`mode.type = systemd`, `smooth_scroll_speed = 0.5`); changing it cannot fix this. The fix is host-side, requires root, and the agent cannot apply it.
395Note on `udev` `uaccess`:
397- Rejected for this host: the seat's `ActiveSession` is the greeter (Type=wayland, Class=greeter) and the user session is `Idle=yes`. udev `uaccess` hands the device to the session that owns the seat, not the user session ironbar runs in. Live test: after installing `ACTION=="add", SUBSYSTEM=="backlight", TAG+="uaccess"`, `SetBrightness` still returned `NotYourDevice`. Rule was removed. Skip on this seat layout, or also reconfigure seat ownership.
399Note on polkit `login1.set-brightness`:
401- `NotYourDevice` is raised by `logind` **before** polkit is consulted, so the polkit rule cannot fix it on this seat layout. Staged at `polkit/10-brightness.rules` for completeness; install only after the seat is reconfigured so a real user session owns the foreground.
403Arch wiki ([Backlight](https://wiki.archlinux.org/title/Backlight)) recommended fix: udev `RUN+=` to chgrp/chmod the sysfs file, plus the `video` group. sysfs `brightness` is a `DEVICE_ATTR_RW` whose mode is hardcoded `0644`; udev `GROUP=` / `MODE=` keys do **not** apply to sysfs. The rule must include `KERNEL==` to avoid a `RUN+=` flood on every brightness change.
405 ```sh
406 # udev/backlight.rules
407 ACTION=="add", SUBSYSTEM=="backlight", KERNEL=="intel_backlight", RUN+="/usr/bin/chgrp video /sys/class/backlight/intel_backlight/brightness"
408 ACTION=="add", SUBSYSTEM=="backlight", KERNEL=="intel_backlight", RUN+="/usr/bin/chmod g+w /sys/class/backlight/intel_backlight/brightness"
409 ```
411 ```sh
412 doas install -m 0644 /home/oli/Workspace/dotfiles/udev/backlight.rules /etc/udev/rules.d/backlight.rules
413 doas udevadm control --reload
414 doas udevadm trigger --subsystem-match=backlight --action=add
415 doas usermod -aG video oli # log out / log in (or `newgrp video` for current shell)
416 ```
418 After that, logind `SetBrightness` from the user session still works through the builtin `systemd` backend; sysfs is also directly writable by members of `video` for any helper that bypasses logind (e.g. `brightnessctl` from inside the user session).
420### Step 9 — bindmode
422Difficulty: easy-medium.
424Goal:
426- Show Hyprland submap/bindmode only when active.
428Implementation:
430- Builtin `bindmode` module.
432Verify:
434- Hidden during normal use.
435- Appears/disappears correctly if a Hypr submap is active.
437### Step 10 — inhibit — done
439Difficulty: medium.
441Goal:
443- Add sleep/lock inhibition toggle.
445Implementation:
447- Builtin `inhibit` module.
449Proposed behavior:
451- Left: toggle selected duration.
452- Right: cycle duration.
453- Format off/on clearly.
455Verified:
457- Toggle visible/readable.
458- Duration visible in screenshot.
459- No Ironbar errors.
461### Step 11 — cute cat widget — skipped/removed
463Reason:
465- Cute but superfluous under the current goal.
466- Removed after screenshot showed the right/center area was already dense.
468Verified:
470- Bar validates/restarts without it.
471- Center media has more room.
473### Step 12 — media/player controls — done
475Difficulty: medium.
477Goal:
479- Make media useful and compact.
481Implementation:
483- Builtin `music` module with MPRIS.
484- Format: status icon + truncated title/artist.
485- Popup: album art + controls.
487Implemented:
489- Builtin `music` module with MPRIS.
490- Compact title/artist format with truncation.
491- No extra scroll action; avoid accidental media changes.
493Verified:
495- Firefox/MPRIS player detected.
496- Title visible and compact at 1366px.
497- Popup styled by Nugu CSS.
499### Step 13 — system monitors
501Difficulty: medium.
503Goal:
505- Add compact system monitor row.
507Implementation:
509- Builtin `sys_info` module.
511Candidate labels:
513- CPU percent.
514- RAM percent.
515- Temperature.
516- Disk root percent.
517- Network up/down.
519Implemented:
521- Compact CPU label via builtin `sys_info`.
522- Left/middle opens `btm` through shared Hypr Lua TUI launcher.
524Useful install:
526```sh
527sudo pacman -S bottom
528```
530Optional GUI:
532```sh
533sudo pacman -S resources
534```
536Verify:
538- Values update at sane intervals.
539- Compact enough for 1366px.
540- No excessive CPU wakeups.
542### Step 14 — power menu
544Difficulty: medium-hard.
546Goal:
548- Polish power menu using installed `hyprshutdown`.
550Implementation:
552- `custom` module popup.
554Candidate buttons:
556- poweroff: `hyprshutdown --post-cmd "systemctl poweroff"`
557- reboot: `hyprshutdown --post-cmd "systemctl reboot"`
558- logout: `hyprshutdown`
559- suspend: `loginctl lock-session && systemctl suspend`
560- lock: `hyprlock`
561- Popup order puts destructive actions far left and safe lock nearest the right-side opener, avoiding accidental shutdown/reboot from a second click at the trigger position.
563Verify:
565- Popup opens.
566- Lock/suspend/logout work.
567- Do not test reboot/poweroff without explicit confirmation.
569### Step 15 — notifications — done
571Decision:
573- Keep Mako.
574- Do not install SwayNC; it would replace/compete with Mako.
575- Ironbar builtin `notifications` module remains unused.
577Implemented:
579- Custom Mako indicator script:
580 - empty: `󰂚`
581 - active notifications: `󰂞 N`
582- Left click: `makoctl restore`.
583- Right click: `makoctl dismiss --all`.
585Verified:
587- Mako service active.
588- Count visible/readable in screenshots.
589- Dismissing all notifications via Mako works.
590- No SwayNC dependency.
592### Step 16 — WiFi / network — done
594Decision:
596- Keep `iwd` + systemd-networkd.
597- Do not install/use NetworkManager.
599Implemented:
601- Custom script module reads `iwctl station wlan0 show`.
602- Connected state is icon-only to reduce clutter.
603- Disconnected state shows `󰖪 off`.
604- Left/middle click opens `impala` through shared Hypr Lua TUI launcher.
606Verified:
608- `iwd.service` active.
609- `networkctl status wlan0` routable/online.
610- WiFi icon visible/readable.
611- No NetworkManager dependency.
613### Step 17 — workspaces — done
615Goal:
617- Show fixed workspace favorites.
618- Logical order:
619 - `1 web`
620 - `2 code`
621 - `3 term`
622 - `4 chat`
623 - `5 media`
624 - `9 misc`
625- Empty favorites remain visible.
626- Active/occupied/empty states readable.
627- Click focuses correct workspace.
629Problem found:
631- Builtin Ironbar `workspaces` sends legacy `hyprctl dispatch workspace N`.
632- Hyprland Lua dispatcher rejects that syntax:
633 - `error: [string "return hl.dispatch(workspace 1)"]:1: ')' expected near '1'`
635Implemented:
637- Migrated Hypr workspace rules/binds/window rules to numeric IDs.
638- Replaced builtin Ironbar workspaces with a custom workspace switcher.
639- Each button uses Lua dispatcher syntax:
640 - `hyprctl eval 'hl.dispatch(hl.dsp.focus({ workspace = "N" }))'`
641- Replaced old polling `ironbar/scripts/workspace-label.lua` with `ironbar/scripts/workspaces-watch.py`.
642- Watcher listens to Hypr socket2 and writes Ironbar vars (`#ws1`, `#ws2`, ...), making highlight update immediately on switch.
643- Watcher uses direct Hypr Unix socket IPC for state reads and only writes changed Ironbar vars.
644- Watcher caches the Hypr socket directory and Nugu CSS vars, avoiding repeated `hyprctl instances` subprocesses and repeated CSS file reads on every workspace event.
645- Added `hypr/systemd/ironbar-workspaces.service`, symlink manifest entry, and service enable recipe.
646- `ironbar-workspaces.service` is `PartOf=ironbar.service` so bar restarts immediately refresh workspace vars.
647- Removed unused builtin `.workspaces` CSS.
648- Removed launcher underline styling after screenshot showed it clashed with the active workspace/focused launcher pills.
649- Increased system-module spacing slightly; verified clock/power still fit on 1366px.
650- Removed unused `.notifications` CSS and normalized `.sysinfo` spacing.
651- Removed normal `scratch` workspace from the bar; special scratch remains on `SUPER+S`.
653Verified:
655- Hypr reload ok; no config errors.
656- Existing named `web`/`term` windows moved to numeric `1`/`3`.
657- All six icons visible; no tofu/question mark glyphs.
658- Empty workspace active-state update verified 0.2s after click.
659- Service active and low overhead: `ironbar` ~1.8% CPU shortly after restart, watcher ~0.2% CPU / 6.6M RSS on X230.
660- Clicks verified via `wdotool`:
661 - workspace `1` focuses `id=1`
662 - empty workspace `2` focuses `id=2`
663 - workspace `3` focuses `id=3`
664- Ironbar logs contain no workspace dispatch errors after custom switcher.
666## Suggested final bar layout
668Start:
6701. workspaces
6712. clipboard
6723. bindmode
674Removed:
676- focused window module; active app/title was redundant and made the left side noisy.
677- launcher module; colorful app/window icons broke the semantic Nugu bar aesthetic.
679Center:
6811. media/player
6822. clock
684End:
6861. Mako indicator
6872. WiFi icon
6884. Bluetooth battery/status
6895. tray
6906. sys_info CPU
6917. volume
6928. brightness
6939. battery
69410. inhibit
69511. power menu
697Interaction polish:
699- All hover states use the same semantic accent background + on-focus foreground, including music and clipboard.
700- Generic `:checked` styling was removed; persistent state is explicit per widget.
701- Power and volume checked/focus states are explicitly neutral so clicking elsewhere clears visible highlight.
702- Clock popup time/month/year/arrows/days were screenshot-verified readable after GTK calendar selector fixes.
703- Clipboard grouped with left utilities; notifications grouped with right status.
704- Bar edge padding increased so power does not sit flush against the display edge.
705- Region/group spacing added between workspace/utility and right-side connectivity/metrics/inhibit groups.
706- Active workspace pill widened to make instant highlight easier to see.
707- WiFi polling relaxed to 30s because connected state is icon-only and detail action opens `impala`.
708- Ironbar systemd unit sets `GSK_RENDERER=cairo`; this removes GTK/Mesa Vulkan startup noise on X230 while staying around 1.5% CPU / 77M RSS after settling.
709- Destructive power actions were not clicked during validation.
710- Power popup visual test confirmed destructive off/reboot buttons sit away from the opener cursor side.
712## Open decisions
714- Media scroll: next/prev, volume, or none? Current: no scroll action.
715- Optional later: richer Mako popup/history UI. Current: compact count + restore/dismiss actions.

ironbar/config.json

Deleted
deleted file mode 100644

+0 / −255 text lines

1{
2 "icon_theme": "Adwaita",
3 "position": "top",
4 "height": 30,
5 "popup_autohide": true,
6 "popup_gap": 4,
7 "start": [
8 {
9 "type": "custom",
10 "name": "workspace-switcher",
11 "class": "nugu-workspaces",
12 "bar": [
13 {
14 "type": "box",
15 "widgets": [
16 {
17 "type": "button",
18 "class": "workspace-item",
19 "label": "#ws1",
20 "on_click": "!hyprctl eval 'hl.dispatch(hl.dsp.focus({ workspace = \"1\" }))'"
21 },
22 {
23 "type": "button",
24 "class": "workspace-item",
25 "label": "#ws2",
26 "on_click": "!hyprctl eval 'hl.dispatch(hl.dsp.focus({ workspace = \"2\" }))'"
27 },
28 {
29 "type": "button",
30 "class": "workspace-item",
31 "label": "#ws3",
32 "on_click": "!hyprctl eval 'hl.dispatch(hl.dsp.focus({ workspace = \"3\" }))'"
33 },
34 {
35 "type": "button",
36 "class": "workspace-item",
37 "label": "#ws4",
38 "on_click": "!hyprctl eval 'hl.dispatch(hl.dsp.focus({ workspace = \"4\" }))'"
39 },
40 {
41 "type": "button",
42 "class": "workspace-item",
43 "label": "#ws5",
44 "on_click": "!hyprctl eval 'hl.dispatch(hl.dsp.focus({ workspace = \"5\" }))'"
45 },
46 {
47 "type": "button",
48 "class": "workspace-item",
49 "label": "#ws9",
50 "on_click": "!hyprctl eval 'hl.dispatch(hl.dsp.focus({ workspace = \"9\" }))'"
51 }
52 ]
53 }
54 ],
55 "tooltip": "Workspaces: web code term chat media misc"
56 },
57 {
58 "type": "clipboard",
59 "max_items": 5,
60 "truncate": {
61 "mode": "end",
62 "length": 30
63 }
64 },
65 {
66 "type": "bindmode",
67 "truncate": {
68 "mode": "end",
69 "max_length": 20
70 }
71 }
72 ],
73 "center": [
74 {
75 "type": "music",
76 "player_type": "mpris",
77 "format": "{title} / {artist}",
78 "truncate": {
79 "mode": "end",
80 "max_length": 42
81 }
82 },
83 {
84 "type": "clock",
85 "format": "%H:%M"
86 }
87 ],
88 "end": [
89 {
90 "type": "script",
91 "class": "mako-status",
92 "cmd": "~/.config/ironbar/scripts/mako-status.sh",
93 "mode": "poll",
94 "interval": 5000,
95 "on_click_left": "makoctl restore",
96 "on_click_right": "makoctl dismiss --all",
97 "tooltip": "Notifications: left restores last, right dismisses all"
98 },
99 {
100 "type": "script",
101 "class": "wifi",
102 "cmd": "~/.config/ironbar/scripts/wifi-status.sh",
103 "mode": "poll",
104 "interval": 30000,
105 "on_click_left": "hyprctl eval 'require(\"scripts.tui_tab\").spawn(\"impala\")'",
106 "on_click_middle": "hyprctl eval 'require(\"scripts.tui_tab\").spawn(\"impala\")'",
107 "tooltip": "WiFi: left/middle opens impala"
108 },
109 {
110 "type": "bluetooth",
111 "format": {
112 "not_found": "",
113 "disabled": "󰂲",
114 "enabled": "󰂯",
115 "connected": "󰂱",
116 "connected_battery": "󰂱 {device_battery_percent}%"
117 },
118 "disable_popup": true,
119 "on_click_left": "hyprctl eval 'require(\"scripts.tui_tab\").spawn(\"bluetui\")'",
120 "on_click_middle": "hyprctl eval 'require(\"scripts.tui_tab\").spawn(\"bluetui\")'",
121 "tooltip": "Bluetooth: left/middle opens bluetui"
122 },
123 {
124 "type": "tray",
125 "icon_size": 14
126 },
127 {
128 "type": "sys_info",
129 "format": [" {cpu_percent:1}%"],
130 "interval": {
131 "cpu": 2
132 },
133 "on_click_left": "hyprctl eval 'require(\"scripts.tui_tab\").spawn(\"btm\")'",
134 "on_click_middle": "hyprctl eval 'require(\"scripts.tui_tab\").spawn(\"btm\")'",
135 "tooltip": "System monitor: left/middle opens btm"
136 },
137 {
138 "type": "volume",
139 "on_scroll_up": "wpctl set-volume -l 1 @DEFAULT_AUDIO_SINK@ 2%+",
140 "on_scroll_down": "wpctl set-volume @DEFAULT_AUDIO_SINK@ 2%-",
141 "on_click_right": "wpctl set-mute @DEFAULT_AUDIO_SINK@ toggle",
142 "on_click_middle": "hyprctl eval 'require(\"scripts.tui_tab\").spawn(\"wiremix\")'",
143 "smooth_scroll_speed": 1.0,
144 "show_sources": false,
145 "tooltip": "Volume: scroll adjusts, right mutes, middle opens wiremix"
146 },
147 {
148 "type": "brightness",
149 "format": "{percentage}%",
150 "icon_label": "display-brightness-symbolic",
151 "mode": {
152 "type": "systemd",
153 "subsystem": "backlight",
154 "name": "intel_backlight"
155 },
156 "smooth_scroll_speed": 0.5,
157 "tooltip": "Brightness: scroll adjusts display"
158 },
159 {
160 "type": "battery",
161 "format": "{percentage}%",
162 "icon_size": 10,
163 "show_if": "ls /sys/class/power_supply/ | grep -q '^BAT'",
164 "profiles": {
165 "warning": {
166 "percent": 20
167 },
168 "critical": {
169 "when": {
170 "percent": 5,
171 "charging": false
172 },
173 "format": "󰂎 {percentage}%"
174 }
175 },
176 "tooltip": "Battery: left opens details"
177 },
178 {
179 "type": "inhibit",
180 "durations": ["00:30:00", "01:00:00", "02:00:00", "inf"],
181 "default_duration": "00:30:00",
182 "format_on": "󰅶 {duration}",
183 "format_off": "󰛊 {duration}",
184 "tooltip": "Inhibit: left toggles, right cycles duration"
185 },
186 {
187 "type": "custom",
188 "name": "power-menu",
189 "class": "power-menu",
190 "bar": [
191 {
192 "type": "button",
193 "name": "power-btn",
194 "label": "󰐥",
195 "on_click": "popup:toggle"
196 }
197 ],
198 "popup": [
199 {
200 "type": "box",
201 "orientation": "vertical",
202 "widgets": [
203 {
204 "type": "label",
205 "name": "header",
206 "label": "power"
207 },
208 {
209 "type": "box",
210 "name": "buttons",
211 "widgets": [
212 {
213 "type": "button",
214 "class": "power-btn danger",
215 "label": "󰐥 off",
216 "on_click": "!hyprshutdown --post-cmd \"systemctl poweroff\""
217 },
218 {
219 "type": "button",
220 "class": "power-btn",
221 "label": "󰜉 reboot",
222 "on_click": "!hyprshutdown --post-cmd \"systemctl reboot\""
223 },
224 {
225 "type": "button",
226 "class": "power-btn",
227 "label": "󰍃 out",
228 "on_click": "!hyprshutdown"
229 },
230 {
231 "type": "button",
232 "class": "power-btn",
233 "label": "󰤄 sleep",
234 "on_click": "!loginctl lock-session && systemctl suspend"
235 },
236 {
237 "type": "button",
238 "class": "power-btn",
239 "label": "󰌾 lock",
240 "on_click": "!hyprlock"
241 }
242 ]
243 },
244 {
245 "type": "label",
246 "name": "uptime",
247 "label": "up {{30000:uptime -p | cut -d ' ' -f2-}}"
248 }
249 ]
250 }
251 ],
252 "tooltip": "Power menu"
253 }
254 ]
255}

ironbar/nugu.css

Deleted
deleted file mode 100644

+0 / −17 text lines

1/* Generated by hypr/scripts/theme.nu from Nugu palette. */
2:root {
3 --bg: #242424;
4 --bg-transparent: #242424ee;
5 --surface: #9d9d9d;
6 --fg: #dbdbdb;
7 --accent: #d86dd8;
8 --focus: #9aabae;
9 --on-focus: #121212;
10 --muted: #9d9d9d;
11 --unfocus: #6f6f6f;
12 --error: #ec6376;
13 --warning: #f0ee69;
14 --info: #3ec5e3;
15 --debug: #ed5eed;
16 --border: #d86dd8;
17}

ironbar/scripts/mako-status.sh

Deleted
deleted file mode 100755

+0 / −7 text lines

1#!/bin/sh
2
3count=$(makoctl list 2>/dev/null | grep -c '^Notification ')
4case "$count" in
5 0) printf '󰂚\n' ;;
6 *) printf '󰂞 %s\n' "$count" ;;
7esac

ironbar/scripts/wifi-status.sh

Deleted
deleted file mode 100755

+0 / −12 text lines

1#!/bin/sh
2
3station=${1:-wlan0}
4raw=$(iwctl station "$station" show 2>/dev/null | sed 's/\x1b\[[0-9;]*m//g')
5state=$(printf '%s\n' "$raw" | awk '/State/ {print $2; exit}')
6
7if [ "$state" != connected ]; then
8 printf '󰖪 off\n'
9 exit 0
10fi
12printf '󰖩\n'

ironbar/scripts/workspaces-watch.py

Deleted
deleted file mode 100755

+0 / −148 text lines

1#!/usr/bin/env python3
2
3import json
4import os
5import select
6import socket
7import subprocess
8import time
9from pathlib import Path
11WORKSPACES = [
12 ("1", "󰖟"),
13 ("2", "󰅨"),
14 ("3", "󰆍"),
15 ("4", "󰭹"),
16 ("5", "󰎆"),
17 ("9", "󰉋"),
18]
19EVENT_PREFIXES = (
20 "workspace",
21 "focusedmon",
22 "createworkspace",
23 "destroyworkspace",
24 "moveworkspace",
25 "openwindow",
26 "closewindow",
27 "movewindow",
28 "urgent",
29)
30last_vars: dict[str, str] = {}
31color_mtime = 0
32color_vars: dict[str, str] = {}
33hypr_socket_dir = ""
36def css_vars() -> dict[str, str]:
37 global color_mtime, color_vars
38 config_home = Path(os.environ.get("XDG_CONFIG_HOME", Path.home() / ".config"))
39 path = config_home / "ironbar" / "nugu.css"
40 mtime = path.stat().st_mtime_ns
41 if mtime == color_mtime:
42 return color_vars
43 colors: dict[str, str] = {}
44 for line in path.read_text().splitlines():
45 if ":" not in line:
46 continue
47 name, value = line.strip().rstrip(";").split(":", 1)
48 name = name.strip()
49 value = value.strip()
50 if name.startswith("--") and value.startswith("#"):
51 colors[name[2:]] = value
52 color_mtime = mtime
53 color_vars = colors
54 return colors
57def hypr_dir() -> str:
58 global hypr_socket_dir
59 if hypr_socket_dir:
60 return hypr_socket_dir
61 sig = os.environ.get("HYPRLAND_INSTANCE_SIGNATURE")
62 if not sig:
63 result = subprocess.run(("hyprctl", "instances", "-j"), text=True, capture_output=True, check=False)
64 instances = json.loads(result.stdout or "[]")
65 sig = instances[0]["instance"]
66 hypr_socket_dir = f"{os.environ['XDG_RUNTIME_DIR']}/hypr/{sig}"
67 return hypr_socket_dir
70def hypr_cmd(command: str) -> str:
71 with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as sock:
72 sock.settimeout(1)
73 sock.connect(f"{hypr_dir()}/.socket.sock")
74 sock.sendall(command.encode())
75 chunks: list[bytes] = []
76 while True:
77 chunk = sock.recv(65536)
78 if not chunk:
79 break
80 chunks.append(chunk)
81 return b"".join(chunks).decode("utf-8", "replace")
84def event_socket_path() -> str:
85 return f"{hypr_dir()}/.socket2.sock"
88def markup(ws_id: str, icon: str, active: str, occupied: set[str], colors: dict[str, str]) -> str:
89 if ws_id == active:
90 return '<span foreground="{}" background="{}" font_weight="bold"> {} </span>'.format(
91 colors["on-focus"],
92 colors["focus"],
93 icon,
94 )
95 if ws_id in occupied:
96 return '<span foreground="{}">{}</span>'.format(colors["fg"], icon)
97 return '<span foreground="{}">{}</span>'.format(colors["muted"], icon)
100def hypr_state() -> tuple[str, set[str]]:
101 active = json.loads(hypr_cmd("j/activeworkspace") or "{}")
102 workspaces = json.loads(hypr_cmd("j/workspaces") or "[]")
103 return str(active.get("id", "")), {str(ws.get("id")) for ws in workspaces if ws.get("windows", 0) > 0}
106def set_var(name: str, value: str) -> None:
107 if last_vars.get(name) == value:
108 return
109 subprocess.run(("ironbar", "var", "set", name, value), stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, check=False)
110 last_vars[name] = value
113def update() -> None:
114 colors = css_vars()
115 active, occupied = hypr_state()
116 for ws_id, icon in WORKSPACES:
117 set_var(f"ws{ws_id}", markup(ws_id, icon, active, occupied, colors))
120def watch() -> None:
121 global hypr_socket_dir
122 while True:
123 update()
124 try:
125 with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as sock:
126 sock.connect(event_socket_path())
127 pending = b""
128 while True:
129 ready, _, _ = select.select([sock], [], [], 10)
130 if not ready:
131 update()
132 continue
133 chunk = sock.recv(4096)
134 if not chunk:
135 break
136 pending += chunk
137 while b"\n" in pending:
138 raw, pending = pending.split(b"\n", 1)
139 line = raw.decode("utf-8", "replace")
140 if line.startswith(EVENT_PREFIXES):
141 update()
142 except Exception:
143 hypr_socket_dir = ""
144 time.sleep(1)
147if __name__ == "__main__":
148 watch()

ironbar/style.css

Deleted
deleted file mode 100644

+0 / −617 text lines

1@import url("nugu.css");
2
3:root {
4 --radius: 7px;
5 --font-size: 12px;
6}
7
8* {
9 font-family: 'IBM Plex Mono';
10 font-size: var(--font-size);
11 border: none;
12 box-shadow: none;
13 background-image: none;
14 text-shadow: none;
15 -gtk-icon-shadow: none;
16 border-radius: 0;
17}
19window, popover, popover contents {
20 background-color: var(--bg-transparent);
21 color: var(--fg);
22 border-radius: var(--radius);
23}
25#bar {
26 background-color: var(--bg);
27 padding: 0 20px;
28 border-bottom: 2px solid var(--accent);
29}
31box, button, label {
32 background: transparent;
33 background-image: none;
34 color: var(--fg);
35}
37button {
38 min-height: 0;
39 padding: 1px 7px;
40 border-radius: var(--radius);
41 background: transparent;
42}
44button:hover, button:active {
45 background: var(--accent);
46 color: var(--on-focus);
47}
49button:hover label,
50button:active label,
51button:hover image,
52button:active image {
53 color: var(--on-focus);
54}
56.nugu-workspaces {
57 margin-left: 4px;
58 margin-right: 10px;
59}
61.nugu-workspaces .workspace-item {
62 min-height: 0;
63 margin: 0 2px;
64 padding: 1px 5px;
65 color: var(--muted);
66}
68.nugu-workspaces .workspace-item:hover {
69 background: var(--accent);
70 color: var(--on-focus);
71}
73.bindmode {
74 margin-left: 8px;
75 padding: 1px 7px;
76 border-radius: var(--radius);
77 background: var(--warning);
78 color: var(--bg);
79 font-weight: bold;
80}
82.popup-music {
83 padding: 12px;
84}
86.popup-music .album-art {
87 border-radius: var(--radius);
88 margin-right: 12px;
89}
91.volume {
92 margin: 0 7px;
93}
95.popup-volume {
96 padding: 12px;
97 background-color: var(--bg-transparent);
98 color: var(--fg);
99}
101.popup-volume .device-box,
102.popup-volume .apps-box {
103 background-color: transparent;
104 color: var(--fg);
105}
107.popup-volume .device-selector,
108.popup-volume .device-selector button,
109.popup-volume dropdown,
110.popup-volume dropdown button {
111 background: var(--accent);
112 color: var(--on-focus);
113 border-radius: var(--radius);
114}
116.popup-volume .device-selector label,
117.popup-volume .device-selector arrow,
118.popup-volume .device-selector *,
119.popup-volume dropdown button,
120.popup-volume dropdown button * {
121 background: transparent;
122 color: var(--on-focus);
123}
125.popup-volume .btn-mute {
126 color: var(--fg);
127}
129.popup-volume .btn-mute:hover,
130.popup-volume .btn-mute:checked {
131 background: var(--accent);
132 color: var(--on-focus);
133}
135popover listview,
136popover list,
137popover row,
138popover modelbutton {
139 background-color: var(--bg);
140 color: var(--fg);
141}
143popover listview row,
144popover list row {
145 padding: 6px 10px;
146}
148popover listview row label,
149popover list row label,
150popover row label,
151popover modelbutton label {
152 color: var(--fg);
153}
155popover listview row:hover,
156popover list row:hover,
157popover row:hover,
158popover modelbutton:hover {
159 background-color: var(--accent);
160 color: var(--on-focus);
161}
163popover listview row:hover label,
164popover list row:hover label,
165popover row:hover label,
166popover modelbutton:hover label {
167 color: var(--on-focus);
168}
170popover listview row:selected,
171popover list row:selected,
172popover row:selected,
173popover modelbutton:checked {
174 background-color: var(--focus);
175 color: var(--on-focus);
176}
178popover listview row:selected label,
179popover list row:selected label,
180popover row:selected label,
181popover modelbutton:checked label {
182 color: var(--on-focus);
183}
185/* GTK dropdown popovers are separate popovers, not children of .popup-volume. */
186popover contents listview,
187popover contents list,
188popover contents row,
189popover contents modelbutton,
190popover contents button {
191 background: var(--bg);
192 color: var(--fg);
193}
195popover contents row *,
196popover contents modelbutton *,
197popover contents button * {
198 color: var(--fg);
199}
201popover contents row:hover,
202popover contents modelbutton:hover,
203popover contents button:hover {
204 background: var(--accent);
205 color: var(--on-focus);
206}
208popover contents row:hover *,
209popover contents modelbutton:hover *,
210popover contents button:hover * {
211 color: var(--on-focus);
212}
214popover contents row:selected,
215popover contents modelbutton:checked,
216popover contents button:checked {
217 background: var(--focus);
218 color: var(--on-focus);
219}
221popover contents row:selected *,
222popover contents modelbutton:checked *,
223popover contents button:checked * {
224 color: var(--on-focus);
225}
227.popup-volume dropdown popover,
228.popup-volume dropdown popover contents,
229.popup-volume dropdown popover listview,
230.popup-volume dropdown popover row {
231 background: var(--bg);
232 color: var(--fg);
233}
235.popup-volume dropdown popover label,
236.popup-volume dropdown popover row *,
237.popup-volume dropdown popover listview * {
238 color: var(--fg);
239}
241.popup-volume dropdown popover row:hover {
242 background: var(--accent);
243}
245.popup-volume dropdown popover row:selected {
246 background: var(--accent);
247}
249.popup-volume dropdown popover row:selected * {
250 color: var(--on-focus);
251}
253scale trough {
254 min-height: 6px;
255 min-width: 6px;
256 background-color: var(--unfocus);
257 border-radius: var(--radius);
258}
260scale highlight {
261 min-height: 6px;
262 min-width: 6px;
263 background-color: var(--accent);
264 border-radius: var(--radius);
265}
267.brightness {
268 margin: 0 7px;
269 color: var(--fg);
270}
272.battery {
273 margin: 0 7px;
274 color: var(--fg);
275}
277.battery.warning {
278 color: var(--warning);
279}
281.battery.critical {
282 color: var(--error);
283 font-weight: bold;
284}
286.popup-battery {
287 padding: 10px 12px;
288 background-color: var(--bg-transparent);
289 color: var(--fg);
290}
292.popup-battery .details {
293 color: var(--muted);
294}
296.inhibit {
297 margin: 0 7px 0 12px;
298 color: var(--muted);
299}
301.inhibit button:checked,
302.inhibit button:active {
303 background: var(--accent);
304 color: var(--on-focus);
305}
307.clock {
308 font-weight: bold;
309 margin: 0 7px;
310 color: var(--accent);
311}
313.popup-clock {
314 padding: 12px;
315 background-color: var(--bg-transparent);
316 color: var(--fg);
317}
319.popup-clock *,
320.popup-clock calendar.view header,
321.popup-clock calendar.view header *,
322.popup-clock calendar.view header stack.month,
323.popup-clock calendar.view header label.year {
324 color: var(--fg);
325}
327.popup-clock .calendar-clock {
328 background: var(--accent);
329 color: var(--on-focus);
330 border-radius: var(--radius);
331 padding: 2px 8px;
332 margin-bottom: 8px;
333}
335.popup-clock .calendar-clock,
336.popup-clock .calendar-clock * {
337 color: var(--on-focus);
338 font-weight: bold;
339}
341.popup-clock calendar {
342 background: transparent;
343 color: var(--fg);
344 border-radius: var(--radius);
345}
347.popup-clock calendar header {
348 border-bottom: 1px solid var(--unfocus);
349 padding-bottom: 6px;
350 margin-bottom: 6px;
351}
353.popup-clock calendar button:hover,
354.popup-clock calendar.view header button:hover,
355.popup-clock calendar.view header button:hover * {
356 background: var(--accent);
357 color: var(--on-focus);
358}
360.popup-clock calendar grid label.day-name,
361.popup-clock calendar grid label.week-number {
362 color: var(--muted);
363}
365.popup-clock calendar grid label.day-number {
366 color: var(--fg);
367 border-radius: var(--radius);
368}
370.popup-clock calendar grid label.other-month {
371 color: var(--unfocus);
372}
374.popup-clock calendar grid label.today {
375 color: var(--accent);
376 font-weight: bold;
377}
379.popup-clock calendar grid label:selected {
380 background: var(--focus);
381 color: var(--on-focus);
382}
384.music {
385 margin: 0 7px;
386 color: var(--fg);
387}
389.clipboard {
390 margin: 0 10px 0 12px;
391}
393.popup-clipboard {
394 padding: 8px;
395}
397.popup-clipboard .item {
398 padding: 4px 8px;
399 border-radius: var(--radius);
400 color: var(--fg);
401}
403.popup-clipboard .item label {
404 color: var(--fg);
405}
407.popup-clipboard .item:hover {
408 background-color: var(--accent);
409 color: var(--on-focus);
410}
412.popup-clipboard .item:hover label {
413 color: var(--on-focus);
414}
416.mako-status {
417 margin: 0 7px 0 12px;
418 color: var(--fg);
419}
421.wifi {
422 margin: 0 7px;
423 color: var(--fg);
424}
426.bluetooth {
427 margin: 0 7px;
428}
430.bluetooth.disabled,
431.bluetooth.not-found {
432 color: var(--muted);
433}
435.bluetooth.enabled {
436 color: var(--fg);
437}
439.bluetooth.connected {
440 color: var(--fg);
441}
443.tray {
444 margin: 0 7px 0 12px;
445}
447.tray popover contents {
448 padding: 8px;
449}
451.power-menu {
452 margin-left: 12px;
453}
455.power-menu button,
456.power-menu #power-btn {
457 color: var(--muted);
458}
460.power-menu button:hover,
461.power-menu #power-btn:hover {
462 background: var(--accent);
463 color: var(--on-focus);
464}
466.power-menu button:checked,
467.power-menu button:focus,
468.power-menu #power-btn:checked,
469.power-menu #power-btn:focus {
470 background: transparent;
471 color: var(--muted);
472}
474.popup-power-menu {
475 padding: 12px;
476 background-color: var(--bg-transparent);
477 color: var(--fg);
478}
480.popup-power-menu #header {
481 font-size: 14px;
482 font-weight: bold;
483 margin-bottom: 8px;
484 padding-bottom: 8px;
485 color: var(--accent);
486 border-bottom: 1px solid var(--unfocus);
487}
489.popup-power-menu #buttons {
490 margin-bottom: 8px;
491}
493.popup-power-menu .power-btn {
494 background-color: transparent;
495 border: 1px solid var(--unfocus);
496 border-radius: var(--radius);
497 padding: 6px 10px;
498 margin: 0 3px;
499 color: var(--fg);
500}
502.popup-power-menu .power-btn:hover {
503 background-color: var(--accent);
504 border-color: var(--accent);
505 color: var(--on-focus);
506}
508.popup-power-menu .power-btn.danger {
509 border-color: var(--error);
510}
512.popup-power-menu .power-btn.danger:hover {
513 background-color: var(--accent);
514 border-color: var(--accent);
515 color: var(--on-focus);
516}
518.popup-power-menu #uptime {
519 color: var(--muted);
520}
522.sysinfo {
523 margin: 0 7px 0 16px;
524}
526.sysinfo > .item + .item {
527 margin-left: 8px;
528}
530.music:hover,
531.clipboard:hover,
532.mako-status:hover,
533.wifi:hover,
534.bluetooth:hover,
535.tray:hover,
536.sysinfo:hover,
537.volume:hover,
538.brightness:hover,
539.battery:hover,
540.inhibit:hover,
541.clock:hover {
542 background: var(--accent);
543 color: var(--on-focus);
544 border-radius: var(--radius);
545}
547.music:hover label,
548.clipboard:hover label,
549.mako-status:hover label,
550.wifi:hover label,
551.bluetooth:hover label,
552.tray:hover label,
553.sysinfo:hover label,
554.volume:hover label,
555.brightness:hover label,
556.battery:hover label,
557.inhibit:hover label,
558.clock:hover label {
559 color: var(--on-focus);
560}
562.music:checked,
563.music:focus,
564.clipboard:checked,
565.clipboard:focus,
566.mako-status:checked,
567.mako-status:focus,
568.wifi:checked,
569.wifi:focus,
570.bluetooth:checked,
571.bluetooth:focus,
572.tray:checked,
573.tray:focus,
574.sysinfo:checked,
575.sysinfo:focus,
576.volume:checked,
577.volume:focus,
578.volume button:checked,
579.volume button:focus,
580.brightness:checked,
581.brightness:focus,
582.battery:checked,
583.battery:focus,
584.clock:checked,
585.clock:focus {
586 background: transparent;
587 color: var(--fg);
588}
590.music:checked label,
591.music:focus label,
592.clipboard:checked label,
593.clipboard:focus label,
594.mako-status:checked label,
595.mako-status:focus label,
596.wifi:checked label,
597.wifi:focus label,
598.bluetooth:checked label,
599.bluetooth:focus label,
600.tray:checked label,
601.tray:focus label,
602.sysinfo:checked label,
603.sysinfo:focus label,
604.volume:checked label,
605.volume:focus label,
606.brightness:checked label,
607.brightness:focus label,
608.battery:checked label,
609.battery:focus label,
610.clock:checked label,
611.clock:focus label {
612 color: var(--fg);
613}
615.popup {
616 padding: 8px;
617}

justfile

Deleted
deleted file mode 100644

+0 / −223 text lines

1set shell := ["nu", "--commands"]
2
3default:
4 @just --list
5
6# initialize crypto, install hooks, verify, link dorkfiles into HOME
7link: nugu-linux-console nugu-hypr
8 java bootstripper.java bootstrap
9
10# build generated files needed by linked shell config
11nugu-linux-console:
12 just --justfile nugu/justfile --working-directory nugu linux-console
13
14nugu-hypr:
15 just --justfile nugu/justfile --working-directory nugu hypr
16
17# verify crypto filters, hooks, and staged secrets
18check:
19 java bootstripper.java check
20
21clean:
22 java bootstripper.java clean
23
24# run the same checks as the Git pre-commit hook
25pre-commit:
26 java bootstripper.java pre-commit
27
28# integration test in ephemeral rootless Podman Linux; fresh system deps: git + java
29# tests every *.symlinks manifest; primary hostname printed first for quick failure context
30test hostname="desktop":
31 #!/usr/bin/env bash
32 set -euo pipefail
33
34 root="$(git rev-parse --show-toplevel)"
35 key="$root/.git/dotfiles-aes.key"
36 image="registry.fedoraproject.org/fedora:latest"
37 container="dotfiles-integration-$(date +%Y%m%d%H%M%S)-$$"
38
39 if [ ! -r "$key" ]; then
40 echo "missing $key"
41 exit 1
42 fi
43
44 trap 'podman rm -f "$container" >/dev/null 2>&1 || true' EXIT
45
46 echo "container=$container"
47 podman run --name "$container" --rm -i --hostname "{{hostname}}" \
48 -e PRIMARY_HOSTNAME="{{hostname}}" \
49 -v "$root:/src:ro" \
50 -v "$key:/dotfiles-aes.key:ro" \
51 "$image" bash -s <<'CONTAINER'
52 set -euo pipefail
53
54 ok() { echo "ok:$1"; }
55 fail() { echo "FAIL:$1"; exit 1; }
56
57 target_path() {
58 local home="$1"
59 local target="$2"
60 if [[ "$target" == ~* ]]; then
61 printf '%s%s\n' "$home" "${target:1}"
62 else
63 printf '%s\n' "$target"
64 fi
65 }
66
67 targets_for() {
68 awk '
69 { sub(/\r$/, "") }
70 NF == 0 { next }
71 source == "" { source = $0; next }
72 { print $0; source = "" }
73 END { if (source != "") exit 2 }
74 ' "$1"
75 }
76
77 run_manifest() {
78 local host="$1"
79 local manifest="$host.symlinks"
80 local home="/tmp/home-$host"
81 local bootstrap_log="/tmp/bootstrap-$host.log"
82 local check_log="/tmp/check-$host.log"
83 local clean_log="/tmp/clean-$host.log"
84
85 echo "manifest=$manifest"
86 rm -rf "$home"
87 mkdir -p "$home"
88
89 HOSTNAME="$host" java -Duser.home="$home" bootstripper.java bootstrap >"$bootstrap_log" 2>&1 || {
90 echo "FAIL:bootstrap:$host"
91 tail -120 "$bootstrap_log"
92 exit 1
93 }
94 ok "bootstrap:$host"
95
96 HOSTNAME="$host" java -Duser.home="$home" bootstripper.java check >"$check_log" 2>&1 || {
97 echo "FAIL:check:$host"
98 cat "$check_log"
99 exit 1
100 }
101 ok "check:$host"
102
103 while IFS= read -r target; do
104 local path
105 path="$(target_path "$home" "$target")"
106 test -L "$path" || fail "link:$host:$target"
107 done < <(targets_for "$manifest")
108 ok "links:$host"
109
110 HOSTNAME="$host" java -Duser.home="$home" bootstripper.java clean >"$clean_log" 2>&1 || {
111 echo "FAIL:clean:$host"
112 cat "$clean_log"
113 exit 1
114 }
115 ok "clean:$host"
116 }
117
118 fresh_crypto_smoke() {
119 local repo=/tmp/fresh-crypto
120 rm -rf "$repo" /tmp/fresh-crypto-home
121 mkdir -p "$repo/tools" /tmp/fresh-crypto-home
122 cp bootstripper.java "$repo/"
123 cp tools/aes.java "$repo/tools/"
124 cd "$repo"
125 git init --quiet
126 printf 'secret.txt\n' > .secrets
127 printf 'dummy.txt\n~/dummy.txt\n' > mini.symlinks
128 printf 'not a real secret\n' > secret.txt
129 printf 'dummy\n' > dummy.txt
130
131 DOTFILES_AES_PASSPHRASE=test java bootstripper.java init-crypto >/tmp/fresh-init.log 2>&1 || { cat /tmp/fresh-init.log; fail fresh-init; }
132 DOTFILES_AES_PASSPHRASE=test java bootstripper.java check >/tmp/fresh-check-1.log 2>&1 || { cat /tmp/fresh-check-1.log; fail fresh-check-1; }
133 git add .dotfiles-aes-salt .secrets bootstripper.java tools/aes.java mini.symlinks dummy.txt secret.txt
134 DOTFILES_AES_PASSPHRASE=test java bootstripper.java check >/tmp/fresh-check-2.log 2>&1 || { cat /tmp/fresh-check-2.log; fail fresh-check-2; }
135 git show :secret.txt | head -c 6 | grep -qx DFAES1 || fail fresh-staged-encrypted
136 HOSTNAME=mini DOTFILES_AES_PASSPHRASE=test java -Duser.home=/tmp/fresh-crypto-home bootstripper.java bootstrap >/tmp/fresh-bootstrap.log 2>&1 || { cat /tmp/fresh-bootstrap.log; fail fresh-bootstrap; }
137 test -L /tmp/fresh-crypto-home/dummy.txt || fail fresh-link
138 HOSTNAME=mini DOTFILES_AES_PASSPHRASE=test java -Duser.home=/tmp/fresh-crypto-home bootstripper.java clean >/tmp/fresh-clean.log 2>&1 || { cat /tmp/fresh-clean.log; fail fresh-clean; }
139 ok fresh-crypto
140 }
141
142 printf 'rootless='
143 awk 'NR == 1 { print ($1 == 0 && $2 != 0) ? "yes" : "unknown" }' /proc/self/uid_map
144
145 if ! dnf -qy --setopt=install_weak_deps=False install git-core java-latest-openjdk-headless >/tmp/dnf.log 2>&1; then
146 cat /tmp/dnf.log
147 fail deps
148 fi
149 ok deps
150 git --version
151 java -version 2>&1 | sed -n '1p'
152
153 mkdir -p /root/work
154 git config --global --add safe.directory /src
155 git clone --quiet --no-local /src /root/work/dotfiles || fail clone
156 install -m 600 /dotfiles-aes.key /root/work/dotfiles/.git/dotfiles-aes.key
157 cd /root/work/dotfiles
158
159 java bootstripper.java install-hooks >/tmp/install-hooks.log 2>&1 || { cat /tmp/install-hooks.log; fail install-hooks; }
160 test -x .git/hooks/pre-commit || fail hook-executable
161 grep -qx 'exec java bootstripper.java pre-commit' .git/hooks/pre-commit || fail hook-content
162 ok install-hooks
163
164 git show HEAD:nushell/secrets.nu | head -c 6 | grep -qx DFAES1 || fail committed-encrypted
165 ok committed-encrypted
166
167 mapfile -t hosts < <(find . -maxdepth 1 -name '*.symlinks' -printf '%f\n' | sed 's/\.symlinks$//' | sort)
168 printf 'primary-manifest=%s.symlinks\n' "$PRIMARY_HOSTNAME"
169 printf 'manifests=%s\n' "${hosts[*]}"
170
171 for host in "${hosts[@]}"; do
172 run_manifest "$host"
173 done
174 ok "symlink-manifests:${#hosts[@]}"
175
176 if head -c 6 nushell/secrets.nu | grep -qx DFAES1; then
177 fail worktree-still-encrypted
178 fi
179 ok worktree-decrypted
180
181 java bootstripper.java pre-commit >/tmp/precommit.log 2>&1 || { echo FAIL:pre-commit; cat /tmp/precommit.log; exit 1; }
182 grep -q 'Skipping gitleaks: command not found' /tmp/precommit.log || fail gitleaks-optional
183 ok pre-commit
184
185 fresh_crypto_smoke
186
187 echo RESULT:ok
188 CONTAINER
189
190# create initial crypto salt
191init-crypto:
192 java bootstripper.java init-crypto
193
194# install Git hooks
195hooks:
196 java bootstripper.java install-hooks
197
198# enable some user systemd services
199services:
200 nu enable_user_services.nu
201
202# remove links to dorkfiles from HOME
203unlink:
204 java bootstripper.java clean
205
206# typically the initial git remote for the dotfiles repo is https
207# this command changes the remote to ssh
208ssh-remote:
209 git remote rm origin
210 git remote add origin git@github.com:bugabinga/dotfiles.git
211 git fetch
212 git branch --set-upstream-to=origin/trunk trunk
213
214# initial setup: link dotfiles, enable services, fix permissions
215setup: link services fix_permissions
216
217# install previously exported winget apps. see topgrade config for exports.
218import_winget:
219 winget import C:/Users/okr/Tools/winget_installed_apps.json
220
221# fix some file permissions
222fix_permissions:
223 let firefox_profile = ('~/.mozilla/firefox/qrza8u52.default-release' | path expand); if ($firefox_profile | path exists) { chmod 700 $firefox_profile }

mako/config

Deleted
deleted file mode 100644

+0 / −43 text lines

1include=~/.config/mako/nugu.conf
2
3font=IBM Plex Sans 10
4border-size=2
5border-radius=12
6padding=12,14
7margin=8
8outer-margin=14
9anchor=top-right
10layer=overlay
11width=360
12height=160
13max-visible=4
14max-history=80
15sort=-priority
16icons=1
17max-icon-size=48
18icon-border-radius=7
19markup=1
20actions=1
21history=1
22ignore-timeout=1
23default-timeout=6500
24format=%a\n<b>%s</b>\n%b
25on-button-left=invoke-default-action
26on-button-middle=dismiss-group
27on-button-right=dismiss
29[urgency=low]
30default-timeout=2500
32[urgency=normal]
33default-timeout=6500
35[urgency=critical]
36border-size=3
37default-timeout=0
39[grouped]
40format=%a · %g\n<b>%s</b>\n%b
42[hidden]
43format=+%h more notifications

mako/nugu.conf

Deleted
deleted file mode 100644

+0 / −33 text lines

1# Generated by hypr/scripts/theme.nu from Nugu palette.
2background-color=#242424ee
3text-color=#dbdbdbff
4border-color=#d86dd8ff
5progress-color=over #9aabaeff
6
7[urgency=low]
8background-color=#121212e6
9text-color=#8b8b8bff
10border-color=#6f6f6fff
11progress-color=over #8b8b8bff
13[urgency=normal]
14border-color=#d86dd8ff
15progress-color=over #9aabaeff
17[urgency=critical]
18background-color=#242424ff
19text-color=#f3effbff
20border-color=#ec6376ff
21progress-color=over #ec6376ff
23[summary~="[Ee]rror|[Ff]ailed|[Ff]ailure|[Cc]rash"]
24border-color=#ec6376ff
25progress-color=over #ec6376ff
27[summary~="[Ww]arn|[Ww]arning"]
28border-color=#f0ee69ff
29progress-color=over #f0ee69ff
31[summary~="[Ii]nfo|[Nn]otice"]
32border-color=#3ec5e3ff
33progress-color=over #3ec5e3ff

mise.android.toml

Added
new file mode 100644

+2 / −0 text lines

1[settings]
2enable_tools = ["http:git-revue"]

mise.lock

Added
new file mode 100644

+20 / −0 text lines

1# @generated - this file is auto-generated by `mise lock` https://mise.jdx.dev/dev-tools/mise-lock.html
2
3[[tools.java]]
4version = "27.0.1+0"
5backend = "core:java"
6
7[tools.java.options]
8shorthand_vendor = "temurin"
9
10[tools.java."platforms.linux-arm64"]
11checksum = "sha256:5ddacf925244a00b60cac828b61ff2f67a68cd32b8dfe5cee1405e333b4589e5"
12url = "https://github.com/adoptium/temurin27-binaries/releases/download/jdk-27.0.1.0.2%2B1/OpenJDK27U-jdk_aarch64_linux_hotspot_27.0.1.0.2_1.tar.gz"
14[tools.java."platforms.linux-x64"]
15checksum = "sha256:30cb129f6cf299c852cec0feca9ea2a596d2ee9f26d8605d3a253951f6c8b20f"
16url = "https://github.com/adoptium/temurin27-binaries/releases/download/jdk-27.0.1.0.2%2B1/OpenJDK27U-jdk_x64_linux_hotspot_27.0.1.0.2_1.tar.gz"
18[tools.java."platforms.windows-x64"]
19checksum = "sha256:5fac419f00d2256941a6b1253a827bb8b904da215a1ec0667035e5592811c1dc"
20url = "https://github.com/adoptium/temurin27-binaries/releases/download/jdk-27.0.1.0.2%2B1/OpenJDK27U-jdk_x64_windows_hotspot_27.0.1.0.2_1.zip"

mise.toml

Added
new file mode 100644

+141 / −0 text lines

1[tools]
2java = "latest"
3
4[task_config]
5shell = "java scripts/mise_shell.java"
6
7[tasks.default]
8description = "List tasks"
9hide = true
10run = 'run("mise", "tasks", "ls");'
12[tasks.check]
13description = "Verify crypto, hooks, secrets, and symlink manifests"
14run = 'run("java", "bootstripper.java", "check");'
16[tasks.ci]
17description = "Run committed-state Podman CI check"
18run = 'run("java", "./scripts/dotfiles_integration_test.java");'
20[tasks.ci-check]
21description = "Run the CI check suite"
22hide = true
23run = 'run("java", "./scripts/dotfiles_integration_test.java", "--inside");'
25[tasks.crypto-test]
26description = "Run the complete crypto acceptance suite"
27hide = true
28run = 'run("java", "./scripts/dotfiles_integration_test.java", "--crypto");'
30[tasks.crypto-git-test]
31description = "Run focused encrypted Git filter and merge tests"
32run = 'run("java", "./scripts/dotfiles_integration_test.java", "--crypto-git");'
34[tasks.crypto-restore-test]
35description = "Run focused encrypted-secret restoration tests"
36run = 'run("java", "./scripts/dotfiles_integration_test.java", "--crypto-restore");'
38[tasks.fresh-checkout-crypto-test]
39description = "Test link-time crypto setup from a fresh encrypted checkout"
40run = 'run("java", "./scripts/dotfiles_integration_test.java", "--fresh-checkout-crypto");'
42[tasks.bootstrap-test]
43description = "Run focused bootstrap and platform-selection tests"
44run = 'run("java", "./scripts/dotfiles_integration_test.java", "--bootstrap");'
46[tasks.hooks-test]
47description = "Run isolated Git hook and link integration tests"
48run = 'run("java", "./scripts/dotfiles_integration_test.java", "--hooks");'
50[tasks.mise-shell-test]
51description = "Run focused Mise Java task-shell tests"
52run = 'run("java", "./scripts/dotfiles_integration_test.java", "--mise-shell");'
54[tasks.mise-route-test]
55description = "Test the production Mise link-task route"
56run = 'run("java", "./scripts/dotfiles_integration_test.java", "--mise-route");'
58[tasks.manifests-test]
59description = "Validate all repository symlink manifest contracts"
60run = 'run("java", "./scripts/dotfiles_integration_test.java", "--manifest-contracts");'
62[tasks.process-harness-test]
63description = "Test integration subprocess timeout and cleanup"
64run = 'run("java", "./scripts/dotfiles_integration_test.java", "--process-cleanup");'
66[tasks.secrets-scan]
67description = "Scan committed Git history for plaintext secrets"
68run = 'run("gitleaks", "git", "--redact=100", "--no-banner", "--log-opts=--all --full-history --diff-merges=first-parent --no-ext-diff --no-textconv");'
70[tasks.link]
71description = "Converge crypto and hooks, validate manifests, and link dorkfiles into HOME"
72run = 'run("java", "bootstripper.java", "link");'
74[tasks.setup-crypto]
75description = "Configure crypto and decrypt unchanged checkout secrets; refuse local changes"
76run = 'run("java", "bootstripper.java", "setup-crypto");'
78[tasks.clean]
79description = "Remove managed dorkfiles links from HOME"
80run = 'run("java", "bootstripper.java", "clean");'
82[tasks.init]
83description = "Create initial crypto salt"
84hide = true
85run = 'run("java", "bootstripper.java", "init-crypto");'
87[tasks.hook]
88description = "Install Git hooks"
89hide = true
90run = 'run("java", "bootstripper.java", "install-hooks");'
92[tasks.fix]
93description = "Fix local file permissions"
94hide = true
95run = 'run("java", "scripts/fix_permissions.java");'
97[tasks.niri-test]
98description = "Test Niri modernization inspector, Nugu generation, and config loading"
99run = '''
100run("node", "--test", "niri/.pi/skills/modernize/scripts/inspect.test.mjs");
101run("node", "--test", "niri/config.test.mjs", "niri/theme.test.mjs");
102run("nu", "--no-config-file", "nugu/mode.test.nu");
103'''
105[tasks.nugu-termux]
106description = "Generate both Nugu Termux palettes without selecting a mode"
107run = '''
108cd("nugu");
109run("just", "--shell", "nu", "--clear-shell-args", "--shell-arg=--no-config-file", "--shell-arg=--commands", "termux");
110'''
112[tasks.termux-test]
113description = "Test Nugu Termux generation and manual theme switching"
114run = '''
115run("nu", "--no-config-file", "-c", "for file in [nugu/termux.nu nushell/modules/termux-theme.nu] { if not (nu-check --as-module $file) { error make {msg: $'Parse failed: ($file)'} } }");
116run("node", "--test", "termux/theme.test.mjs");
117'''
119[tasks.wezterm-test]
120description = "Test WezTerm modernization and instance helpers"
121run = '''
122run("node", "--test", "wezterm/.pi/skills/modernize/scripts/inspect.test.mjs");
123run("nu", "--no-config-file", "wezterm/tests/wezterm_instances_test.nu");
124'''
126[tasks.nushell-markdown-test]
127description = "Test standalone Markdown rendering and To-Do integration"
128run = 'run("nu", "--no-config-file", "nushell/tests/markdown.test.nu");'
130[tasks.nushell-pi-test]
131description = "Test Pi discovery, full-history reader, rendering, and CLI passthrough"
132run = '''
133run("nu", "--no-config-file", "nushell/tests/pi.test.nu");
134run("nu", "--no-config-file", "nushell/tests/pi-reader.test.nu");
135'''
137[tasks.win32-drive-test]
138description = "Test the win32-drive skill script against a fixture window (takes over the Windows desktop)"
139run = '''
140run("powershell.exe", "-NoProfile", "-ExecutionPolicy", "Bypass", "-File", "pi/agent/skillz/win32-drive/scripts/win32-drive.test.ps1");
141'''

mise/.mise/locks/npm-cf/1.0.0-beta.16/aube-lock.yaml

Added
new file mode 100644

+615 / −0 text lines

1lockfileVersion: '9.0'
2
3settings:
4 autoInstallPeers: true
5 excludeLinksFromLockfile: false
6
7importers:
8
9 .:
10 dependencies:
11 cf:
12 specifier: 1.0.0-beta.16
13 version: 1.0.0-beta.16
15packages:
17 '@cloudflare/build-output-utils@0.9.1':
18 resolution: {integrity: sha512-zTzHGwXD7dJ1+vWlVgvTWbg1k0x53+Wu1aR6MDWAflOwJD9KtHjz7Qqq6pnTbVxlR0m5GLlD6sshEuiKnB1KQA==}
20 '@cloudflare/codemods@0.4.2':
21 resolution: {integrity: sha512-oHvDlfhQEIkdf8Mvz4SMgk+6evVlu9rrntRv5KQfRK3H4RkXUmawzYQ7+zdBG0wiWdp/Ku/PqNMWVYAs8T4jrQ==}
22 hasBin: true
24 '@cloudflare/config@0.25.0':
25 resolution: {integrity: sha512-h4tgL9/pmeoIdKfs/irfV/eCotbEpbadO2RGPbHwRij6Ek7q8Gqx4juSoDSb/fk9IclansgAHXF9b8rb3Kw4jg==}
27 '@cloudflare/runtime-types@0.1.10':
28 resolution: {integrity: sha512-OXEpo7VZ/ALsLGzKCX4n0Dknnf1w3W6wCWELiKyW6MUd7JRvd23KSTrUKIHLJaBpXR1hTKCqWBUWUHBn2wZbnQ==}
30 '@cloudflare/workerd-darwin-64@1.20261006.1':
31 resolution: {integrity: sha512-lCX6avJO2It9AyDEYitjmOtJRVp/xmaW0TziyoLAnfxlzozyyRbSFfIIMMCiDx/sTP1++E4VLbV+7BHSD33f0Q==}
32 engines: {node: '>=16'}
33 cpu: [x64]
34 os: [darwin]
36 '@cloudflare/workerd-darwin-arm64@1.20261006.1':
37 resolution: {integrity: sha512-PyFGjOaldtppnLuKsdkoYWXfLVpDjuf8u+uoykX+1Xvxo2EPmCVViq0iDKm+U7c7PRno85ehS3/MPVXyk2HwHw==}
38 engines: {node: '>=16'}
39 cpu: [arm64]
40 os: [darwin]
42 '@cloudflare/workerd-linux-64@1.20261006.1':
43 resolution: {integrity: sha512-Ntf9S8eesmVufdjaT2kzWlz6Ng9XGYTc6cHQVRKAg59lFufwsIabGeMT6U4KkrpEeSIxgHq8aPtuLbZXE19tCA==}
44 engines: {node: '>=16'}
45 cpu: [x64]
46 os: [linux]
48 '@cloudflare/workerd-linux-arm64@1.20261006.1':
49 resolution: {integrity: sha512-JyeDBymVWw5tVRebSsVE8ojDYxd6UlZrAseHU8G+NpIyd5wF61tXlF/axLeCUqu0pOhBFHb8I5QKi0jwrCK41Q==}
50 engines: {node: '>=16'}
51 cpu: [arm64]
52 os: [linux]
54 '@cloudflare/workerd-windows-64@1.20261006.1':
55 resolution: {integrity: sha512-nWP0URNqOBN9fa/gZ7eh/w051DwjOXN8j4lDZDYVXyQPsux6sV3DfyYZT+CjR/rt9nKBSmJT9QE9/bWT18+84w==}
56 engines: {node: '>=16'}
57 cpu: [x64]
58 os: [win32]
60 '@cspotcode/source-map-support@0.8.1':
61 resolution: {integrity: sha512-IchNf6dN4tHoMFIn/7OE8LWZ19Y6q/67Bmf6vnGREv8RSbBVb9LPJxEcnwrcwX6ixSvaiGoomAUvu4YSxXrVgw==}
62 engines: {node: '>=12'}
64 '@emnapi/runtime@1.11.3':
65 resolution: {integrity: sha512-Xz4Tpyki7XyrpbUK1jR1AhdAdaXyhhY4lZ3neLodmhpuWfy2PAQN5B46sAiU4liOXGLkHypn/qU+jvfWSCYYLA==}
67 '@img/colour@1.1.0':
68 resolution: {integrity: sha512-Td76q7j57o/tLVdgS746cYARfSyxk8iEfRxewL9h4OMzYhbW4TAcppl0mT4eyqXddh6L/jwoM75mo7ixa/pCeQ==}
69 engines: {node: '>=18'}
71 '@img/sharp-darwin-arm64@0.35.5':
72 resolution: {integrity: sha512-QRUlFQ0WxvdWyqqG/WtI3iupfD5rBzmCHXSdPsY91sAtVtTo7Q4cb6zOccZ3gqEqkr0f1As1ehLqmEpDsRf+lg==}
73 engines: {node: '>=20.9.0'}
74 cpu: [arm64]
75 os: [darwin]
77 '@img/sharp-darwin-x64@0.35.5':
78 resolution: {integrity: sha512-+BR255RhDlpygUpOc/Jdt1nT6DQ3XG/ERo5wbcdOf5Q320dKtPCKPLR1LJs9VGXRaMa8l1uUa0tkCNOXiAxZUw==}
79 engines: {node: '>=20.9.0'}
80 cpu: [x64]
81 os: [darwin]
83 '@img/sharp-freebsd-wasm32@0.35.5':
84 resolution: {integrity: sha512-Y/z91nEZ4uIBX5X3nfTovjU9lHNKFYbL2lpHCLVNmXQK03VIZvXBBt0KxbPGp2SdGSF+2mQU4e+hQaWOt86iAw==}
85 engines: {node: '>=20.9.0'}
86 os: [freebsd]
88 '@img/sharp-libvips-darwin-arm64@1.3.4':
89 resolution: {integrity: sha512-5R89nBYiRdUlSWJxPhO+GVtaXzXSxKnRu/xqMn3KTA3L9EB9Oy/P+Nn2f2vlhPuUdy/Zusb2DarbyTpGCfEDuw==}
90 cpu: [arm64]
91 os: [darwin]
93 '@img/sharp-libvips-darwin-x64@1.3.4':
94 resolution: {integrity: sha512-iR2OKH80yi0U+dUplyh3/xdpFvps6YkCwsXenIJxqxR1v9o+xtKTGbS9H7cps+2Vxjc8B1j96p75NmTGjIhtpQ==}
95 cpu: [x64]
96 os: [darwin]
98 '@img/sharp-libvips-linux-arm64@1.3.4':
99 resolution: {integrity: sha512-Y3dgX/6lE2QhQb+Gxy0WZxfg9MEm/JBjamZpS2IklP7xIQoKN4hzAm7KcMVGtaVDt3neE9OKBC7vAfonA/Lr1A==}
100 cpu: [arm64]
101 os: [linux]
102 libc: [glibc]
104 '@img/sharp-libvips-linux-arm@1.3.4':
105 resolution: {integrity: sha512-LmRtTsOHuvM2+wlO2Db37dx5MiZhB0FvSunciw48YjdOkZz9KAiRbm8ujeMOA1INqmei5NapFxYEK1D1ZSidmw==}
106 cpu: [arm]
107 os: [linux]
108 libc: [glibc]
110 '@img/sharp-libvips-linux-ppc64@1.3.4':
111 resolution: {integrity: sha512-Le6boB8Tai0Nis+gIxIpKx68UDVVIqdR8Tin5Yf1z2LJJQLDJvCDRqRu+jC2qCoD+eIomonmOwB4smBRxfVpYQ==}
112 cpu: [ppc64]
113 os: [linux]
114 libc: [glibc]
116 '@img/sharp-libvips-linux-riscv64@1.3.4':
117 resolution: {integrity: sha512-aHkkIEHPRdQEegJN20MLmGtxYD9R2wQr3Cwpddnu5+YKMt6Uzax7S9h5gpZTo8wyrGuZSlfQ63OevL5mTyOC7Q==}
118 cpu: [riscv64]
119 os: [linux]
120 libc: [glibc]
122 '@img/sharp-libvips-linux-s390x@1.3.4':
123 resolution: {integrity: sha512-ra/mB6MikESDUO7Yg+Mi95bFBb9GsObURuhnOv3OqknjGe9sZrG8tCe9q0xSIGrtLgvgw0gKnFWcK4blSgQOuQ==}
124 cpu: [s390x]
125 os: [linux]
126 libc: [glibc]
128 '@img/sharp-libvips-linux-x64@1.3.4':
129 resolution: {integrity: sha512-GJ//SSXbnwSDes02umB3nDJLFcQzw8a18V8fyhqr6tV515tOEMdImjjxj1AoafMRz56F3PHgftnj1QEKSU1zkw==}
130 cpu: [x64]
131 os: [linux]
132 libc: [glibc]
134 '@img/sharp-libvips-linuxmusl-arm64@1.3.4':
135 resolution: {integrity: sha512-hvulFwtjUcagsis6BBxHwGFwWoNZjgYmULGVrZcyfNbjA8hKILbRxGg15/7w5HDyXHXUos/j6baAWqnCyQ2DWA==}
136 cpu: [arm64]
137 os: [linux]
138 libc: [musl]
140 '@img/sharp-libvips-linuxmusl-x64@1.3.4':
141 resolution: {integrity: sha512-6zXKeE/p39I1AmA3cJG35eyBGNqNddLnUXjhwBnsGjFPWqf5VKkDBEqaEkPDoTEtkxwi2vv8Tcr2mDyP4So7Fg==}
142 cpu: [x64]
143 os: [linux]
144 libc: [musl]
146 '@img/sharp-linux-arm64@0.35.5':
147 resolution: {integrity: sha512-LYVx5JTsOM2CBzmxreh+nl64/3H6Xb09iSLknqH47z2T2DFFxDeFLP5y4dJwe6H7uGQlHPyEEtIqyo3DYsRwdQ==}
148 engines: {node: '>=20.9.0'}
149 cpu: [arm64]
150 os: [linux]
151 libc: [glibc]
153 '@img/sharp-linux-arm@0.35.5':
154 resolution: {integrity: sha512-LEaXK2WdXVK5ykcw0buWyPMsmLLL2vpHLD6yrNSW+JGEL3BZPA4tpKN6iaMc4AxTTAoaX/sU1rOL51lcIz48ZQ==}
155 engines: {node: '>=20.9.0'}
156 cpu: [arm]
157 os: [linux]
158 libc: [glibc]
160 '@img/sharp-linux-ppc64@0.35.5':
161 resolution: {integrity: sha512-QVxAAq8evVRI9ia2vqgwrmWucn5Dfv+JdWzj75pD8omHLPSP7f8p20O8jxzjCcuCEQEOtYOZUmX1hkiZ0kdevA==}
162 engines: {node: '>=20.9.0'}
163 cpu: [ppc64]
164 os: [linux]
165 libc: [glibc]
167 '@img/sharp-linux-riscv64@0.35.5':
168 resolution: {integrity: sha512-LtdreXguaavKODPIfzJ4kffx7UNt1omwtK0rch4EBbbSTXPnxWmYSayXdLJw0fJzQ97kHt1gL/yh4tvU+nCyRQ==}
169 engines: {node: '>=20.9.0'}
170 cpu: [riscv64]
171 os: [linux]
172 libc: [glibc]
174 '@img/sharp-linux-s390x@0.35.5':
175 resolution: {integrity: sha512-UZasTOFiYzotTsGOCu42BfUzP6Tu6Do/947iRm1RsLKvlllxwGcn4RN27LibGWceix4Y+Pmw3jsnTcCQIgWjqA==}
176 engines: {node: '>=20.9.0'}
177 cpu: [s390x]
178 os: [linux]
179 libc: [glibc]
181 '@img/sharp-linux-x64@0.35.5':
182 resolution: {integrity: sha512-SxFtLTeJInhAA9Q836kux2vZNeOBQEx658qvbboZScr0wIARym3IcGmW7KpVD5sbVg0Ojy+udFQdayYIZyoNog==}
183 engines: {node: '>=20.9.0'}
184 cpu: [x64]
185 os: [linux]
186 libc: [glibc]
188 '@img/sharp-linuxmusl-arm64@0.35.5':
189 resolution: {integrity: sha512-9HbMclmI1zlNkFRs3z9/eBtDjfD0sGlrX1z6b1qwmiFY5ElDLh4BC0LPBdVp7z1DXFiKlIcznf+ZlsuZzLxQqg==}
190 engines: {node: '>=20.9.0'}
191 cpu: [arm64]
192 os: [linux]
193 libc: [musl]
195 '@img/sharp-linuxmusl-x64@0.35.5':
196 resolution: {integrity: sha512-4KOphqB035HrVdqLZfCgMzzERrQkkzOwRhl4OAkRO1YCldbaFjySXMaK534Mo0V+LndnlJk+sbUyLeU0ULyD1A==}
197 engines: {node: '>=20.9.0'}
198 cpu: [x64]
199 os: [linux]
200 libc: [musl]
202 '@img/sharp-wasm32@0.35.5':
203 resolution: {integrity: sha512-Ptsga1su4tQx+LLF1ECS9U6nz5kmrXKo6XVbtR48Ke3ZRxxgaWBu7IDtEe1quo8hiupwm6WFqxVlXaSf7IINGQ==}
204 engines: {node: '>=20.9.0'}
206 '@img/sharp-webcontainers-wasm32@0.35.5':
207 resolution: {integrity: sha512-hfhF/FmoQyTUkA0bIKFOtw536BQSeBMe6BF6QyWlrPxT754+TFLaZ7sKKTfvvM0yJgKgaYTwnFCIZ/GuDw5SUA==}
208 engines: {node: '>=20.9.0'}
209 cpu: [wasm32]
211 '@img/sharp-win32-arm64@0.35.5':
212 resolution: {integrity: sha512-X4t7g+7ZA5DKblCBEXGjUqqemj4vczING/5viFwAL8h4N3qYeyjwdCvRLHi4EdOUI+2Z7UFlp1VM+p/AuEtm6Q==}
213 engines: {node: '>=20.9.0'}
214 cpu: [arm64]
215 os: [win32]
217 '@img/sharp-win32-ia32@0.35.5':
218 resolution: {integrity: sha512-5Zm82LoBc43nhwNybZlG7Y1KO//Zhsn306fQl29ZOuStHLGTo3BWL83q3cznX0poxSAMuYL1On/BHBxkBeKr6A==}
219 engines: {node: ^20.9.0}
220 cpu: [ia32]
221 os: [win32]
223 '@img/sharp-win32-x64@0.35.5':
224 resolution: {integrity: sha512-x76eH0vEiHlcMQu8Y8IenntaACtddpT6W0wmXtWrnKcnKI7ME5DdgqhAD6SEWOEl1v2zDvkZDhFA9KnURwpfqg==}
225 engines: {node: '>=20.9.0'}
226 cpu: [x64]
227 os: [win32]
229 '@jridgewell/resolve-uri@3.1.2':
230 resolution: {integrity: sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==}
231 engines: {node: '>=6.0.0'}
233 '@jridgewell/sourcemap-codec@1.6.0':
234 resolution: {integrity: sha512-T7jf+5zgsZHwNJ4lvQ7/aezbyk0nNX+zJVWpmHA7VYsEx7a7qr5Rg5IbtJFqkgze5Y2sruq1RUY8Q837Od7iFw==}
236 '@jridgewell/trace-mapping@0.3.9':
237 resolution: {integrity: sha512-3Belt6tdc8bPgAtbcmdtNJlirVoTmEb5e2gC94PnkwEW9jI6CAHUeoG85tjWP5WquqfavoMtMwiG4P926ZKKuQ==}
239 '@poppinss/colors@4.1.6':
240 resolution: {integrity: sha512-H9xkIdFswbS8n1d6vmRd8+c10t2Qe+rZITbbDHHkQixH5+2x1FDGmi/0K+WgWiqQFKPSlIYB7jlH6Kpfn6Fleg==}
242 '@poppinss/dumper@0.6.5':
243 resolution: {integrity: sha512-NBdYIb90J7LfOI32dOewKI1r7wnkiH6m920puQ3qHUeZkxNkQiFnXVWoE6YtFSv6QOiPPf7ys6i+HWWecDz7sw==}
245 '@poppinss/exception@1.2.3':
246 resolution: {integrity: sha512-dCED+QRChTVatE9ibtoaxc+WkdzOSjYTKi/+uacHWIsfodVfpsueo3+DKpgU5Px8qXjgmXkSvhXvSCz3fnP9lw==}
248 '@sindresorhus/is@7.2.0':
249 resolution: {integrity: sha512-P1Cz1dWaFfR4IR+U13mqqiGsLFf1KbayybWwdd2vfctdV6hDpUkgCY0nKOLLTMSoRd/jJNjtbqzf13K8DCCXQw==}
250 engines: {node: '>=18'}
252 '@speed-highlight/core@1.2.24':
253 resolution: {integrity: sha512-qeW2e1l78afw8VhRPfPQ1Gjj+KU5XFQ/OFV5ti6eTa9bruO7mJyZtA4vw0ofqmA3tKCkROE9xLk3VZoeRc98nw==}
255 blake3-wasm@2.1.5:
256 resolution: {integrity: sha512-F1+K8EbfOZE49dtoPtmxUQrpXaBIl3ICvasLh+nJta0xkz+9kF/7uet9fLnwKqhDrmj6g+6K3Tw9yQPUg2ka5g==}
258 cf@1.0.0-beta.16:
259 resolution: {integrity: sha512-buY0XUHp+wAA0paOKxdUr5UgLKhO8xkeJL5Pn2Xt1UQLfqPFKrqTC3mKrGsrmOhf8Qyn4Omxc4F/8x37fa9kVA==}
260 engines: {node: '>=22'}
261 hasBin: true
263 cookie@1.1.1:
264 resolution: {integrity: sha512-ei8Aos7ja0weRpFzJnEA9UHJ/7XQmqglbRwnf2ATjcB9Wq874VKH9kfjjirM6UhU2/E5fFYadylyhFldcqSidQ==}
265 engines: {node: '>=18'}
267 detect-libc@2.1.2:
268 resolution: {integrity: sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==}
269 engines: {node: '>=8'}
271 error-stack-parser-es@1.0.5:
272 resolution: {integrity: sha512-5qucVt2XcuGMcEGgWI7i+yZpmpByQ8J1lHhcL7PwqCwu9FPP3VUXzT4ltHe5i2z9dePwEHcDVOAfSnHsOlCXRA==}
274 kleur@4.1.5:
275 resolution: {integrity: sha512-o+NO+8WrRiQEE4/7nwRJhN1HWpVmJm511pBHUxPLtp0BUISzlBplORYSmTclCnJvQq2tKu/sgl3xVpkc7ZWuQQ==}
276 engines: {node: '>=6'}
278 miniflare@5.20261006.2-beta:
279 resolution: {integrity: sha512-agufWI3mXF8xGzry2/sOF8Im8AoYs04DWBCLDWDmd4QtMSGEo9IgrPmYOwsCmQA3K3MbLzsvr01GpWc8x3Duqw==}
280 engines: {node: '>=22.0.0'}
282 minisearch@7.2.0:
283 resolution: {integrity: sha512-dqT2XBYUOZOiC5t2HRnwADjhNS2cecp9u+TJRiJ1Qp/f5qjkeT5APcGPjHw+bz89Ms8Jp+cG4AlE+QZ/QnDglg==}
285 semver@7.8.6:
286 resolution: {integrity: sha512-9lpSSU4Mly3mrtruwLs1eLK6+gzbzqeBFwRNjIjE+9LuDpWdYctrQlQ3ej1Ilgi7gknpsTRnPoLP8DpCHqHIJw==}
287 engines: {node: '>=10'}
288 hasBin: true
290 sharp@0.35.5:
291 resolution: {integrity: sha512-Ywn4OnzGukp7CDMrp08RQ50YKmuwG47brZgIVPTvBaaAfQlRlygrRqSrxdCiL9M+LlzLBiJ68IR1QqvzHyjC7g==}
292 engines: {node: '>=20.9.0'}
293 peerDependencies:
294 '@types/node': '*'
295 peerDependenciesMeta:
296 '@types/node':
297 optional: true
299 supports-color@10.2.2:
300 resolution: {integrity: sha512-SS+jx45GF1QjgEXQx4NJZV9ImqmO2NPz5FNsIHrsDjh2YsHnawpan7SNQ1o8NuhrbHZy9AZhIoCUiCeaW/C80g==}
301 engines: {node: '>=18'}
303 tslib@2.9.1:
304 resolution: {integrity: sha512-a4Ux9VKuIMHsOS7ENbEq6hK2ZGYIT27Rtl0E4eD9KqwxhKiQeMZE/9xb3IdYwWaSOyIBQLExhQgXDTYoiCxnWA==}
306 undici@7.29.1:
307 resolution: {integrity: sha512-RYONW2MeafgYlkVOKYKkA/Ag7BmXqgIWCa8t1m0JcxrQg9pI9lEqRhAOruOBCbAohOa/gkCF+iPi9hrgvTzu6Q==}
308 engines: {node: '>=20.18.1'}
310 workerd@1.20261006.1:
311 resolution: {integrity: sha512-8MadBuffZ5NdpLwZjUmsqT5QlaKXq4gjgT6wzcKeynZTICNXyePhc+5QVoKiK7+MMhFTLNrRO2KXLlpk8Q6BkA==}
312 engines: {node: '>=16'}
313 hasBin: true
315 ws@8.21.0:
316 resolution: {integrity: sha512-Vsp28b7DRcimFQvrqu2Wek3z1iYxDCWqHYB8Qsnk/S4RfaCQzPGPyBNuVjJV3cd6UiKtUtp6sNM77gWvzcCH+g==}
317 engines: {node: '>=10.0.0'}
318 peerDependencies:
319 bufferutil: ^4.0.1
320 utf-8-validate: '>=5.0.2'
321 peerDependenciesMeta:
322 bufferutil:
323 optional: true
324 utf-8-validate:
325 optional: true
327 youch-core@0.3.3:
328 resolution: {integrity: sha512-ho7XuGjLaJ2hWHoK8yFnsUGy2Y5uDpqSTq1FkHLK4/oqKtyUU1AFbOOxY4IpC9f0fTLjwYbslUz0Po5BpD1wrA==}
330 youch@4.1.0-beta.10:
331 resolution: {integrity: sha512-rLfVLB4FgQneDr0dv1oddCVZmKjcJ6yX6mS4pU82Mq/Dt9a3cLZQ62pDBL4AUO+uVrCvtWz3ZFUL2HFAFJ/BXQ==}
333 zod@4.6.5:
334 resolution: {integrity: sha512-v5l/aFXZQeai4awLbOpSoHecE9UiMrnfx75tEXLjNonXVARxQ5mOeipTjROUchszUNCqnE+hqAMujRsRHsut2Q==}
336snapshots:
338 '@cloudflare/build-output-utils@0.9.1':
339 dependencies:
340 '@cloudflare/config': 0.25.0
342 '@cloudflare/codemods@0.4.2': {}
344 '@cloudflare/config@0.25.0':
345 dependencies:
346 zod: 4.6.5
348 '@cloudflare/runtime-types@0.1.10':
349 dependencies:
350 miniflare: 5.20261006.2-beta
351 workerd: 1.20261006.1
352 transitivePeerDependencies:
353 - '@types/node'
354 - bufferutil
355 - utf-8-validate
357 '@cloudflare/workerd-darwin-64@1.20261006.1':
358 optional: true
360 '@cloudflare/workerd-darwin-arm64@1.20261006.1':
361 optional: true
363 '@cloudflare/workerd-linux-64@1.20261006.1':
364 optional: true
366 '@cloudflare/workerd-linux-arm64@1.20261006.1':
367 optional: true
369 '@cloudflare/workerd-windows-64@1.20261006.1':
370 optional: true
372 '@cspotcode/source-map-support@0.8.1':
373 dependencies:
374 '@jridgewell/trace-mapping': 0.3.9
376 '@emnapi/runtime@1.11.3':
377 dependencies:
378 tslib: 2.9.1
379 optional: true
381 '@img/colour@1.1.0': {}
383 '@img/sharp-darwin-arm64@0.35.5':
384 optionalDependencies:
385 '@img/sharp-libvips-darwin-arm64': 1.3.4
386 optional: true
388 '@img/sharp-darwin-x64@0.35.5':
389 optionalDependencies:
390 '@img/sharp-libvips-darwin-x64': 1.3.4
391 optional: true
393 '@img/sharp-freebsd-wasm32@0.35.5':
394 dependencies:
395 '@img/sharp-wasm32': 0.35.5
396 optional: true
398 '@img/sharp-libvips-darwin-arm64@1.3.4':
399 optional: true
401 '@img/sharp-libvips-darwin-x64@1.3.4':
402 optional: true
404 '@img/sharp-libvips-linux-arm64@1.3.4':
405 optional: true
407 '@img/sharp-libvips-linux-arm@1.3.4':
408 optional: true
410 '@img/sharp-libvips-linux-ppc64@1.3.4':
411 optional: true
413 '@img/sharp-libvips-linux-riscv64@1.3.4':
414 optional: true
416 '@img/sharp-libvips-linux-s390x@1.3.4':
417 optional: true
419 '@img/sharp-libvips-linux-x64@1.3.4':
420 optional: true
422 '@img/sharp-libvips-linuxmusl-arm64@1.3.4':
423 optional: true
425 '@img/sharp-libvips-linuxmusl-x64@1.3.4':
426 optional: true
428 '@img/sharp-linux-arm64@0.35.5':
429 optionalDependencies:
430 '@img/sharp-libvips-linux-arm64': 1.3.4
431 optional: true
433 '@img/sharp-linux-arm@0.35.5':
434 optionalDependencies:
435 '@img/sharp-libvips-linux-arm': 1.3.4
436 optional: true
438 '@img/sharp-linux-ppc64@0.35.5':
439 optionalDependencies:
440 '@img/sharp-libvips-linux-ppc64': 1.3.4
441 optional: true
443 '@img/sharp-linux-riscv64@0.35.5':
444 optionalDependencies:
445 '@img/sharp-libvips-linux-riscv64': 1.3.4
446 optional: true
448 '@img/sharp-linux-s390x@0.35.5':
449 optionalDependencies:
450 '@img/sharp-libvips-linux-s390x': 1.3.4
451 optional: true
453 '@img/sharp-linux-x64@0.35.5':
454 optionalDependencies:
455 '@img/sharp-libvips-linux-x64': 1.3.4
456 optional: true
458 '@img/sharp-linuxmusl-arm64@0.35.5':
459 optionalDependencies:
460 '@img/sharp-libvips-linuxmusl-arm64': 1.3.4
461 optional: true
463 '@img/sharp-linuxmusl-x64@0.35.5':
464 optionalDependencies:
465 '@img/sharp-libvips-linuxmusl-x64': 1.3.4
466 optional: true
468 '@img/sharp-wasm32@0.35.5':
469 dependencies:
470 '@emnapi/runtime': 1.11.3
471 optional: true
473 '@img/sharp-webcontainers-wasm32@0.35.5':
474 dependencies:
475 '@img/sharp-wasm32': 0.35.5
476 optional: true
478 '@img/sharp-win32-arm64@0.35.5':
479 optional: true
481 '@img/sharp-win32-ia32@0.35.5':
482 optional: true
484 '@img/sharp-win32-x64@0.35.5':
485 optional: true
487 '@jridgewell/resolve-uri@3.1.2': {}
489 '@jridgewell/sourcemap-codec@1.6.0': {}
491 '@jridgewell/trace-mapping@0.3.9':
492 dependencies:
493 '@jridgewell/resolve-uri': 3.1.2
494 '@jridgewell/sourcemap-codec': 1.6.0
496 '@poppinss/colors@4.1.6':
497 dependencies:
498 kleur: 4.1.5
500 '@poppinss/dumper@0.6.5':
501 dependencies:
502 '@poppinss/colors': 4.1.6
503 '@sindresorhus/is': 7.2.0
504 supports-color: 10.2.2
506 '@poppinss/exception@1.2.3': {}
508 '@sindresorhus/is@7.2.0': {}
510 '@speed-highlight/core@1.2.24': {}
512 blake3-wasm@2.1.5: {}
514 cf@1.0.0-beta.16:
515 dependencies:
516 '@cloudflare/build-output-utils': 0.9.1
517 '@cloudflare/codemods': 0.4.2
518 '@cloudflare/config': 0.25.0
519 '@cloudflare/runtime-types': 0.1.10
520 blake3-wasm: 2.1.5
521 miniflare: 5.20261006.2-beta
522 minisearch: 7.2.0
523 transitivePeerDependencies:
524 - '@types/node'
525 - bufferutil
526 - utf-8-validate
528 cookie@1.1.1: {}
530 detect-libc@2.1.2: {}
532 error-stack-parser-es@1.0.5: {}
534 kleur@4.1.5: {}
536 miniflare@5.20261006.2-beta:
537 dependencies:
538 '@cspotcode/source-map-support': 0.8.1
539 sharp: 0.35.5
540 undici: 7.29.1
541 workerd: 1.20261006.1
542 ws: 8.21.0
543 youch: 4.1.0-beta.10
544 transitivePeerDependencies:
545 - '@types/node'
546 - bufferutil
547 - utf-8-validate
549 minisearch@7.2.0: {}
551 semver@7.8.6: {}
553 sharp@0.35.5:
554 dependencies:
555 '@img/colour': 1.1.0
556 detect-libc: 2.1.2
557 semver: 7.8.6
558 optionalDependencies:
559 '@img/sharp-darwin-arm64': 0.35.5
560 '@img/sharp-darwin-x64': 0.35.5
561 '@img/sharp-freebsd-wasm32': 0.35.5
562 '@img/sharp-libvips-darwin-arm64': 1.3.4
563 '@img/sharp-libvips-darwin-x64': 1.3.4
564 '@img/sharp-libvips-linux-arm': 1.3.4
565 '@img/sharp-libvips-linux-arm64': 1.3.4
566 '@img/sharp-libvips-linux-ppc64': 1.3.4
567 '@img/sharp-libvips-linux-riscv64': 1.3.4
568 '@img/sharp-libvips-linux-s390x': 1.3.4
569 '@img/sharp-libvips-linux-x64': 1.3.4
570 '@img/sharp-libvips-linuxmusl-arm64': 1.3.4
571 '@img/sharp-libvips-linuxmusl-x64': 1.3.4
572 '@img/sharp-linux-arm': 0.35.5
573 '@img/sharp-linux-arm64': 0.35.5
574 '@img/sharp-linux-ppc64': 0.35.5
575 '@img/sharp-linux-riscv64': 0.35.5
576 '@img/sharp-linux-s390x': 0.35.5
577 '@img/sharp-linux-x64': 0.35.5
578 '@img/sharp-linuxmusl-arm64': 0.35.5
579 '@img/sharp-linuxmusl-x64': 0.35.5
580 '@img/sharp-webcontainers-wasm32': 0.35.5
581 '@img/sharp-win32-arm64': 0.35.5
582 '@img/sharp-win32-ia32': 0.35.5
583 '@img/sharp-win32-x64': 0.35.5
585 supports-color@10.2.2: {}
587 tslib@2.9.1:
588 optional: true
590 undici@7.29.1: {}
592 workerd@1.20261006.1:
593 optionalDependencies:
594 '@cloudflare/workerd-darwin-64': 1.20261006.1
595 '@cloudflare/workerd-darwin-arm64': 1.20261006.1
596 '@cloudflare/workerd-linux-64': 1.20261006.1
597 '@cloudflare/workerd-linux-arm64': 1.20261006.1
598 '@cloudflare/workerd-windows-64': 1.20261006.1
600 ws@8.21.0: {}
602 youch-core@0.3.3:
603 dependencies:
604 '@poppinss/exception': 1.2.3
605 error-stack-parser-es: 1.0.5
607 youch@4.1.0-beta.10:
608 dependencies:
609 '@poppinss/colors': 4.1.6
610 '@poppinss/dumper': 0.6.5
611 '@speed-highlight/core': 1.2.24
612 cookie: 1.1.1
613 youch-core: 0.3.3
615 zod@4.6.5: {}

mise/.mise/locks/npm-cf/1.0.0-beta.16/package.json

Added
new file mode 100644

+7 / −0 text lines

1{
2 "name": "mise-npm-install",
3 "private": true,
4 "dependencies": {
5 "cf": "1.0.0-beta.16"
6 }
7}

mise/config.linux-x64.toml

Added
new file mode 100644

+7 / −0 text lines

1# Private Godot client: Forward+ builds only.
2[tools."github:Bios-Marcel/call_of_slop_modern_warefare_2"]
3version = "latest"
4os = ["linux/x64"]
5lazy = true
6lazy_bins = ["rust-intervention"]
7platforms.linux-x64 = { asset_pattern = "rust-intervention-{{ version }}-linux-x86_64-forward-plus.zip", rename_exe = { "rust-intervention.x86_64" = "rust-intervention" } }

mise/config.linux.toml

Added
new file mode 100644

+3 / −0 text lines

1[tools]
2rust = { version = "latest", mr_boxington = true }
3mr-boxington = { version = "latest", workflow = "release.yml@refs/heads/main" }

mise/config.local.toml

Added
new file mode 100644

+3 / −0 text lines

1[settings.github]
2# Read the desktop gh login from the system keyring without using a Mise shim.
3credential_command = '/usr/bin/gh auth token --hostname "$MISE_CREDENTIAL_HOST"'

mise/config.macos.toml

Added
new file mode 100644

+3 / −0 text lines

1[tools]
2rust = { version = "latest", mr_boxington = true }
3mr-boxington = { version = "latest", workflow = "release.yml@refs/heads/main" }

mise/config.toml

Modified

+28 / −3 text lines

11[tools]
2"cargo:kdl-lsp" = "latest"
3"github:dev-cycles/contextive" = "latest"
4"npm:gh-actions-language-server" = "latest"
2# Android builds ast-grep via Cargo; aqua has no matching Android asset.
3ast-grep = { version = "latest", os = ["linux", "macos", "windows"] }
4"cargo:ast-grep" = { version = "latest", os = ["android"] }
5# Android/Termux uses the system carapace package.
6carapace = { version = "latest", os = ["linux", "macos", "windows"] }
7# Android/Termux has no aqua asset (cargo-binstall-aarch64-android.*); there the
8# binary comes from `pkg install cargo-binstall`, so skip the tool on that OS.
9cargo-binstall = { version = "latest", os = ["linux", "macos", "windows"] }
10"cargo:kdl-lsp" = { version = "latest", depends = "cargo-binstall" }
11"cargo:resvg" = { version = "latest", os = ["windows"], depends = "cargo-binstall" }
13# Syntax-aware git merge driver (see git/gitconfig). Not in pkg or the mise
14# registry; Codeberg publishes static musl builds that also run on Termux.
15"http:mergiraf" = { version = "0.19.1", platforms = { android-arm64 = { url = "https://codeberg.org/mergiraf/mergiraf/releases/download/v0.19.1/mergiraf_aarch64-unknown-linux-musl.tar.gz" }, linux-arm64 = { url = "https://codeberg.org/mergiraf/mergiraf/releases/download/v0.19.1/mergiraf_aarch64-unknown-linux-musl.tar.gz" }, linux-x64 = { url = "https://codeberg.org/mergiraf/mergiraf/releases/download/v0.19.1/mergiraf_x86_64-unknown-linux-musl.tar.gz" }, macos-arm64 = { url = "https://codeberg.org/mergiraf/mergiraf/releases/download/v0.19.1/mergiraf_aarch64-apple-darwin.tar.gz" }, macos-x64 = { url = "https://codeberg.org/mergiraf/mergiraf/releases/download/v0.19.1/mergiraf_x86_64-apple-darwin.tar.gz" }, windows-x64 = { url = "https://codeberg.org/mergiraf/mergiraf/releases/download/v0.19.1/mergiraf_x86_64-unknown-linux-musl.tar.gz" } } }
16"npm:cf" = { version = "1.0.0-beta.16", os = ["linux", "macos", "windows"] }
18[tools."http:git-revue"]
19version = "0.1.0"
20os = ["linux/x64", "android/arm64"]
21platforms.linux-x64 = { url = "https://pkg.bugabinga.net/releases/revue/git-revue-0.1.0-x86_64-unknown-linux-gnu.tar.gz" }
22platforms.android-arm64 = { url = "https://pkg.bugabinga.net/releases/revue/cross/git-revue-0.1.0-aarch64-linux-android.tar.gz" }
624[settings]
725experimental = true
27[settings.github]
28# Reuse Git's credential helper (Windows Credential Manager on NB-00718).
29use_git_credentials = true
31[settings.cargo]
32binstall_quickinstall = true

mise/config.windows-x64.toml

Added
new file mode 100644

+7 / −0 text lines

1# Private Godot client: Forward+ builds only.
2[tools."github:Bios-Marcel/call_of_slop_modern_warefare_2"]
3version = "latest"
4os = ["windows/x64"]
5lazy = true
6lazy_bins = ["rust-intervention"]
7platforms.windows-x64 = { asset_pattern = "rust-intervention-{{ version }}-windows-x86_64-forward-plus.zip" }

mise/config.windows.toml

Added
new file mode 100644

+3 / −0 text lines

1[tools]
2rust = { version = "latest", mr_boxington = true }
3mr-boxington = { version = "latest", workflow = "release.yml@refs/heads/main" }

mise/locks/npm-cf/1.0.0-beta.16/aube-lock.yaml

Added
new file mode 100644

+615 / −0 text lines

1lockfileVersion: '9.0'
2
3settings:
4 autoInstallPeers: true
5 excludeLinksFromLockfile: false
6
7importers:
8
9 .:
10 dependencies:
11 cf:
12 specifier: 1.0.0-beta.16
13 version: 1.0.0-beta.16
15packages:
17 '@cloudflare/build-output-utils@0.9.1':
18 resolution: {integrity: sha512-zTzHGwXD7dJ1+vWlVgvTWbg1k0x53+Wu1aR6MDWAflOwJD9KtHjz7Qqq6pnTbVxlR0m5GLlD6sshEuiKnB1KQA==}
20 '@cloudflare/codemods@0.4.2':
21 resolution: {integrity: sha512-oHvDlfhQEIkdf8Mvz4SMgk+6evVlu9rrntRv5KQfRK3H4RkXUmawzYQ7+zdBG0wiWdp/Ku/PqNMWVYAs8T4jrQ==}
22 hasBin: true
24 '@cloudflare/config@0.25.0':
25 resolution: {integrity: sha512-h4tgL9/pmeoIdKfs/irfV/eCotbEpbadO2RGPbHwRij6Ek7q8Gqx4juSoDSb/fk9IclansgAHXF9b8rb3Kw4jg==}
27 '@cloudflare/runtime-types@0.1.10':
28 resolution: {integrity: sha512-OXEpo7VZ/ALsLGzKCX4n0Dknnf1w3W6wCWELiKyW6MUd7JRvd23KSTrUKIHLJaBpXR1hTKCqWBUWUHBn2wZbnQ==}
30 '@cloudflare/workerd-darwin-64@1.20261006.1':
31 resolution: {integrity: sha512-lCX6avJO2It9AyDEYitjmOtJRVp/xmaW0TziyoLAnfxlzozyyRbSFfIIMMCiDx/sTP1++E4VLbV+7BHSD33f0Q==}
32 engines: {node: '>=16'}
33 cpu: [x64]
34 os: [darwin]
36 '@cloudflare/workerd-darwin-arm64@1.20261006.1':
37 resolution: {integrity: sha512-PyFGjOaldtppnLuKsdkoYWXfLVpDjuf8u+uoykX+1Xvxo2EPmCVViq0iDKm+U7c7PRno85ehS3/MPVXyk2HwHw==}
38 engines: {node: '>=16'}
39 cpu: [arm64]
40 os: [darwin]
42 '@cloudflare/workerd-linux-64@1.20261006.1':
43 resolution: {integrity: sha512-Ntf9S8eesmVufdjaT2kzWlz6Ng9XGYTc6cHQVRKAg59lFufwsIabGeMT6U4KkrpEeSIxgHq8aPtuLbZXE19tCA==}
44 engines: {node: '>=16'}
45 cpu: [x64]
46 os: [linux]
48 '@cloudflare/workerd-linux-arm64@1.20261006.1':
49 resolution: {integrity: sha512-JyeDBymVWw5tVRebSsVE8ojDYxd6UlZrAseHU8G+NpIyd5wF61tXlF/axLeCUqu0pOhBFHb8I5QKi0jwrCK41Q==}
50 engines: {node: '>=16'}
51 cpu: [arm64]
52 os: [linux]
54 '@cloudflare/workerd-windows-64@1.20261006.1':
55 resolution: {integrity: sha512-nWP0URNqOBN9fa/gZ7eh/w051DwjOXN8j4lDZDYVXyQPsux6sV3DfyYZT+CjR/rt9nKBSmJT9QE9/bWT18+84w==}
56 engines: {node: '>=16'}
57 cpu: [x64]
58 os: [win32]
60 '@cspotcode/source-map-support@0.8.1':
61 resolution: {integrity: sha512-IchNf6dN4tHoMFIn/7OE8LWZ19Y6q/67Bmf6vnGREv8RSbBVb9LPJxEcnwrcwX6ixSvaiGoomAUvu4YSxXrVgw==}
62 engines: {node: '>=12'}
64 '@emnapi/runtime@1.11.3':
65 resolution: {integrity: sha512-Xz4Tpyki7XyrpbUK1jR1AhdAdaXyhhY4lZ3neLodmhpuWfy2PAQN5B46sAiU4liOXGLkHypn/qU+jvfWSCYYLA==}
67 '@img/colour@1.1.0':
68 resolution: {integrity: sha512-Td76q7j57o/tLVdgS746cYARfSyxk8iEfRxewL9h4OMzYhbW4TAcppl0mT4eyqXddh6L/jwoM75mo7ixa/pCeQ==}
69 engines: {node: '>=18'}
71 '@img/sharp-darwin-arm64@0.35.5':
72 resolution: {integrity: sha512-QRUlFQ0WxvdWyqqG/WtI3iupfD5rBzmCHXSdPsY91sAtVtTo7Q4cb6zOccZ3gqEqkr0f1As1ehLqmEpDsRf+lg==}
73 engines: {node: '>=20.9.0'}
74 cpu: [arm64]
75 os: [darwin]
77 '@img/sharp-darwin-x64@0.35.5':
78 resolution: {integrity: sha512-+BR255RhDlpygUpOc/Jdt1nT6DQ3XG/ERo5wbcdOf5Q320dKtPCKPLR1LJs9VGXRaMa8l1uUa0tkCNOXiAxZUw==}
79 engines: {node: '>=20.9.0'}
80 cpu: [x64]
81 os: [darwin]
83 '@img/sharp-freebsd-wasm32@0.35.5':
84 resolution: {integrity: sha512-Y/z91nEZ4uIBX5X3nfTovjU9lHNKFYbL2lpHCLVNmXQK03VIZvXBBt0KxbPGp2SdGSF+2mQU4e+hQaWOt86iAw==}
85 engines: {node: '>=20.9.0'}
86 os: [freebsd]
88 '@img/sharp-libvips-darwin-arm64@1.3.4':
89 resolution: {integrity: sha512-5R89nBYiRdUlSWJxPhO+GVtaXzXSxKnRu/xqMn3KTA3L9EB9Oy/P+Nn2f2vlhPuUdy/Zusb2DarbyTpGCfEDuw==}
90 cpu: [arm64]
91 os: [darwin]
93 '@img/sharp-libvips-darwin-x64@1.3.4':
94 resolution: {integrity: sha512-iR2OKH80yi0U+dUplyh3/xdpFvps6YkCwsXenIJxqxR1v9o+xtKTGbS9H7cps+2Vxjc8B1j96p75NmTGjIhtpQ==}
95 cpu: [x64]
96 os: [darwin]
98 '@img/sharp-libvips-linux-arm64@1.3.4':
99 resolution: {integrity: sha512-Y3dgX/6lE2QhQb+Gxy0WZxfg9MEm/JBjamZpS2IklP7xIQoKN4hzAm7KcMVGtaVDt3neE9OKBC7vAfonA/Lr1A==}
100 cpu: [arm64]
101 os: [linux]
102 libc: [glibc]
104 '@img/sharp-libvips-linux-arm@1.3.4':
105 resolution: {integrity: sha512-LmRtTsOHuvM2+wlO2Db37dx5MiZhB0FvSunciw48YjdOkZz9KAiRbm8ujeMOA1INqmei5NapFxYEK1D1ZSidmw==}
106 cpu: [arm]
107 os: [linux]
108 libc: [glibc]
110 '@img/sharp-libvips-linux-ppc64@1.3.4':
111 resolution: {integrity: sha512-Le6boB8Tai0Nis+gIxIpKx68UDVVIqdR8Tin5Yf1z2LJJQLDJvCDRqRu+jC2qCoD+eIomonmOwB4smBRxfVpYQ==}
112 cpu: [ppc64]
113 os: [linux]
114 libc: [glibc]
116 '@img/sharp-libvips-linux-riscv64@1.3.4':
117 resolution: {integrity: sha512-aHkkIEHPRdQEegJN20MLmGtxYD9R2wQr3Cwpddnu5+YKMt6Uzax7S9h5gpZTo8wyrGuZSlfQ63OevL5mTyOC7Q==}
118 cpu: [riscv64]
119 os: [linux]
120 libc: [glibc]
122 '@img/sharp-libvips-linux-s390x@1.3.4':
123 resolution: {integrity: sha512-ra/mB6MikESDUO7Yg+Mi95bFBb9GsObURuhnOv3OqknjGe9sZrG8tCe9q0xSIGrtLgvgw0gKnFWcK4blSgQOuQ==}
124 cpu: [s390x]
125 os: [linux]
126 libc: [glibc]
128 '@img/sharp-libvips-linux-x64@1.3.4':
129 resolution: {integrity: sha512-GJ//SSXbnwSDes02umB3nDJLFcQzw8a18V8fyhqr6tV515tOEMdImjjxj1AoafMRz56F3PHgftnj1QEKSU1zkw==}
130 cpu: [x64]
131 os: [linux]
132 libc: [glibc]
134 '@img/sharp-libvips-linuxmusl-arm64@1.3.4':
135 resolution: {integrity: sha512-hvulFwtjUcagsis6BBxHwGFwWoNZjgYmULGVrZcyfNbjA8hKILbRxGg15/7w5HDyXHXUos/j6baAWqnCyQ2DWA==}
136 cpu: [arm64]
137 os: [linux]
138 libc: [musl]
140 '@img/sharp-libvips-linuxmusl-x64@1.3.4':
141 resolution: {integrity: sha512-6zXKeE/p39I1AmA3cJG35eyBGNqNddLnUXjhwBnsGjFPWqf5VKkDBEqaEkPDoTEtkxwi2vv8Tcr2mDyP4So7Fg==}
142 cpu: [x64]
143 os: [linux]
144 libc: [musl]
146 '@img/sharp-linux-arm64@0.35.5':
147 resolution: {integrity: sha512-LYVx5JTsOM2CBzmxreh+nl64/3H6Xb09iSLknqH47z2T2DFFxDeFLP5y4dJwe6H7uGQlHPyEEtIqyo3DYsRwdQ==}
148 engines: {node: '>=20.9.0'}
149 cpu: [arm64]
150 os: [linux]
151 libc: [glibc]
153 '@img/sharp-linux-arm@0.35.5':
154 resolution: {integrity: sha512-LEaXK2WdXVK5ykcw0buWyPMsmLLL2vpHLD6yrNSW+JGEL3BZPA4tpKN6iaMc4AxTTAoaX/sU1rOL51lcIz48ZQ==}
155 engines: {node: '>=20.9.0'}
156 cpu: [arm]
157 os: [linux]
158 libc: [glibc]
160 '@img/sharp-linux-ppc64@0.35.5':
161 resolution: {integrity: sha512-QVxAAq8evVRI9ia2vqgwrmWucn5Dfv+JdWzj75pD8omHLPSP7f8p20O8jxzjCcuCEQEOtYOZUmX1hkiZ0kdevA==}
162 engines: {node: '>=20.9.0'}
163 cpu: [ppc64]
164 os: [linux]
165 libc: [glibc]
167 '@img/sharp-linux-riscv64@0.35.5':
168 resolution: {integrity: sha512-LtdreXguaavKODPIfzJ4kffx7UNt1omwtK0rch4EBbbSTXPnxWmYSayXdLJw0fJzQ97kHt1gL/yh4tvU+nCyRQ==}
169 engines: {node: '>=20.9.0'}
170 cpu: [riscv64]
171 os: [linux]
172 libc: [glibc]
174 '@img/sharp-linux-s390x@0.35.5':
175 resolution: {integrity: sha512-UZasTOFiYzotTsGOCu42BfUzP6Tu6Do/947iRm1RsLKvlllxwGcn4RN27LibGWceix4Y+Pmw3jsnTcCQIgWjqA==}
176 engines: {node: '>=20.9.0'}
177 cpu: [s390x]
178 os: [linux]
179 libc: [glibc]
181 '@img/sharp-linux-x64@0.35.5':
182 resolution: {integrity: sha512-SxFtLTeJInhAA9Q836kux2vZNeOBQEx658qvbboZScr0wIARym3IcGmW7KpVD5sbVg0Ojy+udFQdayYIZyoNog==}
183 engines: {node: '>=20.9.0'}
184 cpu: [x64]
185 os: [linux]
186 libc: [glibc]
188 '@img/sharp-linuxmusl-arm64@0.35.5':
189 resolution: {integrity: sha512-9HbMclmI1zlNkFRs3z9/eBtDjfD0sGlrX1z6b1qwmiFY5ElDLh4BC0LPBdVp7z1DXFiKlIcznf+ZlsuZzLxQqg==}
190 engines: {node: '>=20.9.0'}
191 cpu: [arm64]
192 os: [linux]
193 libc: [musl]
195 '@img/sharp-linuxmusl-x64@0.35.5':
196 resolution: {integrity: sha512-4KOphqB035HrVdqLZfCgMzzERrQkkzOwRhl4OAkRO1YCldbaFjySXMaK534Mo0V+LndnlJk+sbUyLeU0ULyD1A==}
197 engines: {node: '>=20.9.0'}
198 cpu: [x64]
199 os: [linux]
200 libc: [musl]
202 '@img/sharp-wasm32@0.35.5':
203 resolution: {integrity: sha512-Ptsga1su4tQx+LLF1ECS9U6nz5kmrXKo6XVbtR48Ke3ZRxxgaWBu7IDtEe1quo8hiupwm6WFqxVlXaSf7IINGQ==}
204 engines: {node: '>=20.9.0'}
206 '@img/sharp-webcontainers-wasm32@0.35.5':
207 resolution: {integrity: sha512-hfhF/FmoQyTUkA0bIKFOtw536BQSeBMe6BF6QyWlrPxT754+TFLaZ7sKKTfvvM0yJgKgaYTwnFCIZ/GuDw5SUA==}
208 engines: {node: '>=20.9.0'}
209 cpu: [wasm32]
211 '@img/sharp-win32-arm64@0.35.5':
212 resolution: {integrity: sha512-X4t7g+7ZA5DKblCBEXGjUqqemj4vczING/5viFwAL8h4N3qYeyjwdCvRLHi4EdOUI+2Z7UFlp1VM+p/AuEtm6Q==}
213 engines: {node: '>=20.9.0'}
214 cpu: [arm64]
215 os: [win32]
217 '@img/sharp-win32-ia32@0.35.5':
218 resolution: {integrity: sha512-5Zm82LoBc43nhwNybZlG7Y1KO//Zhsn306fQl29ZOuStHLGTo3BWL83q3cznX0poxSAMuYL1On/BHBxkBeKr6A==}
219 engines: {node: ^20.9.0}
220 cpu: [ia32]
221 os: [win32]
223 '@img/sharp-win32-x64@0.35.5':
224 resolution: {integrity: sha512-x76eH0vEiHlcMQu8Y8IenntaACtddpT6W0wmXtWrnKcnKI7ME5DdgqhAD6SEWOEl1v2zDvkZDhFA9KnURwpfqg==}
225 engines: {node: '>=20.9.0'}
226 cpu: [x64]
227 os: [win32]
229 '@jridgewell/resolve-uri@3.1.2':
230 resolution: {integrity: sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==}
231 engines: {node: '>=6.0.0'}
233 '@jridgewell/sourcemap-codec@1.6.0':
234 resolution: {integrity: sha512-T7jf+5zgsZHwNJ4lvQ7/aezbyk0nNX+zJVWpmHA7VYsEx7a7qr5Rg5IbtJFqkgze5Y2sruq1RUY8Q837Od7iFw==}
236 '@jridgewell/trace-mapping@0.3.9':
237 resolution: {integrity: sha512-3Belt6tdc8bPgAtbcmdtNJlirVoTmEb5e2gC94PnkwEW9jI6CAHUeoG85tjWP5WquqfavoMtMwiG4P926ZKKuQ==}
239 '@poppinss/colors@4.1.6':
240 resolution: {integrity: sha512-H9xkIdFswbS8n1d6vmRd8+c10t2Qe+rZITbbDHHkQixH5+2x1FDGmi/0K+WgWiqQFKPSlIYB7jlH6Kpfn6Fleg==}
242 '@poppinss/dumper@0.6.5':
243 resolution: {integrity: sha512-NBdYIb90J7LfOI32dOewKI1r7wnkiH6m920puQ3qHUeZkxNkQiFnXVWoE6YtFSv6QOiPPf7ys6i+HWWecDz7sw==}
245 '@poppinss/exception@1.2.3':
246 resolution: {integrity: sha512-dCED+QRChTVatE9ibtoaxc+WkdzOSjYTKi/+uacHWIsfodVfpsueo3+DKpgU5Px8qXjgmXkSvhXvSCz3fnP9lw==}
248 '@sindresorhus/is@7.2.0':
249 resolution: {integrity: sha512-P1Cz1dWaFfR4IR+U13mqqiGsLFf1KbayybWwdd2vfctdV6hDpUkgCY0nKOLLTMSoRd/jJNjtbqzf13K8DCCXQw==}
250 engines: {node: '>=18'}
252 '@speed-highlight/core@1.2.24':
253 resolution: {integrity: sha512-qeW2e1l78afw8VhRPfPQ1Gjj+KU5XFQ/OFV5ti6eTa9bruO7mJyZtA4vw0ofqmA3tKCkROE9xLk3VZoeRc98nw==}
255 blake3-wasm@2.1.5:
256 resolution: {integrity: sha512-F1+K8EbfOZE49dtoPtmxUQrpXaBIl3ICvasLh+nJta0xkz+9kF/7uet9fLnwKqhDrmj6g+6K3Tw9yQPUg2ka5g==}
258 cf@1.0.0-beta.16:
259 resolution: {integrity: sha512-buY0XUHp+wAA0paOKxdUr5UgLKhO8xkeJL5Pn2Xt1UQLfqPFKrqTC3mKrGsrmOhf8Qyn4Omxc4F/8x37fa9kVA==}
260 engines: {node: '>=22'}
261 hasBin: true
263 cookie@1.1.1:
264 resolution: {integrity: sha512-ei8Aos7ja0weRpFzJnEA9UHJ/7XQmqglbRwnf2ATjcB9Wq874VKH9kfjjirM6UhU2/E5fFYadylyhFldcqSidQ==}
265 engines: {node: '>=18'}
267 detect-libc@2.1.2:
268 resolution: {integrity: sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==}
269 engines: {node: '>=8'}
271 error-stack-parser-es@1.0.5:
272 resolution: {integrity: sha512-5qucVt2XcuGMcEGgWI7i+yZpmpByQ8J1lHhcL7PwqCwu9FPP3VUXzT4ltHe5i2z9dePwEHcDVOAfSnHsOlCXRA==}
274 kleur@4.1.5:
275 resolution: {integrity: sha512-o+NO+8WrRiQEE4/7nwRJhN1HWpVmJm511pBHUxPLtp0BUISzlBplORYSmTclCnJvQq2tKu/sgl3xVpkc7ZWuQQ==}
276 engines: {node: '>=6'}
278 miniflare@5.20261006.2-beta:
279 resolution: {integrity: sha512-agufWI3mXF8xGzry2/sOF8Im8AoYs04DWBCLDWDmd4QtMSGEo9IgrPmYOwsCmQA3K3MbLzsvr01GpWc8x3Duqw==}
280 engines: {node: '>=22.0.0'}
282 minisearch@7.2.0:
283 resolution: {integrity: sha512-dqT2XBYUOZOiC5t2HRnwADjhNS2cecp9u+TJRiJ1Qp/f5qjkeT5APcGPjHw+bz89Ms8Jp+cG4AlE+QZ/QnDglg==}
285 semver@7.8.6:
286 resolution: {integrity: sha512-9lpSSU4Mly3mrtruwLs1eLK6+gzbzqeBFwRNjIjE+9LuDpWdYctrQlQ3ej1Ilgi7gknpsTRnPoLP8DpCHqHIJw==}
287 engines: {node: '>=10'}
288 hasBin: true
290 sharp@0.35.5:
291 resolution: {integrity: sha512-Ywn4OnzGukp7CDMrp08RQ50YKmuwG47brZgIVPTvBaaAfQlRlygrRqSrxdCiL9M+LlzLBiJ68IR1QqvzHyjC7g==}
292 engines: {node: '>=20.9.0'}
293 peerDependencies:
294 '@types/node': '*'
295 peerDependenciesMeta:
296 '@types/node':
297 optional: true
299 supports-color@10.2.2:
300 resolution: {integrity: sha512-SS+jx45GF1QjgEXQx4NJZV9ImqmO2NPz5FNsIHrsDjh2YsHnawpan7SNQ1o8NuhrbHZy9AZhIoCUiCeaW/C80g==}
301 engines: {node: '>=18'}
303 tslib@2.9.1:
304 resolution: {integrity: sha512-a4Ux9VKuIMHsOS7ENbEq6hK2ZGYIT27Rtl0E4eD9KqwxhKiQeMZE/9xb3IdYwWaSOyIBQLExhQgXDTYoiCxnWA==}
306 undici@7.29.1:
307 resolution: {integrity: sha512-RYONW2MeafgYlkVOKYKkA/Ag7BmXqgIWCa8t1m0JcxrQg9pI9lEqRhAOruOBCbAohOa/gkCF+iPi9hrgvTzu6Q==}
308 engines: {node: '>=20.18.1'}
310 workerd@1.20261006.1:
311 resolution: {integrity: sha512-8MadBuffZ5NdpLwZjUmsqT5QlaKXq4gjgT6wzcKeynZTICNXyePhc+5QVoKiK7+MMhFTLNrRO2KXLlpk8Q6BkA==}
312 engines: {node: '>=16'}
313 hasBin: true
315 ws@8.21.0:
316 resolution: {integrity: sha512-Vsp28b7DRcimFQvrqu2Wek3z1iYxDCWqHYB8Qsnk/S4RfaCQzPGPyBNuVjJV3cd6UiKtUtp6sNM77gWvzcCH+g==}
317 engines: {node: '>=10.0.0'}
318 peerDependencies:
319 bufferutil: ^4.0.1
320 utf-8-validate: '>=5.0.2'
321 peerDependenciesMeta:
322 bufferutil:
323 optional: true
324 utf-8-validate:
325 optional: true
327 youch-core@0.3.3:
328 resolution: {integrity: sha512-ho7XuGjLaJ2hWHoK8yFnsUGy2Y5uDpqSTq1FkHLK4/oqKtyUU1AFbOOxY4IpC9f0fTLjwYbslUz0Po5BpD1wrA==}
330 youch@4.1.0-beta.10:
331 resolution: {integrity: sha512-rLfVLB4FgQneDr0dv1oddCVZmKjcJ6yX6mS4pU82Mq/Dt9a3cLZQ62pDBL4AUO+uVrCvtWz3ZFUL2HFAFJ/BXQ==}
333 zod@4.6.5:
334 resolution: {integrity: sha512-v5l/aFXZQeai4awLbOpSoHecE9UiMrnfx75tEXLjNonXVARxQ5mOeipTjROUchszUNCqnE+hqAMujRsRHsut2Q==}
336snapshots:
338 '@cloudflare/build-output-utils@0.9.1':
339 dependencies:
340 '@cloudflare/config': 0.25.0
342 '@cloudflare/codemods@0.4.2': {}
344 '@cloudflare/config@0.25.0':
345 dependencies:
346 zod: 4.6.5
348 '@cloudflare/runtime-types@0.1.10':
349 dependencies:
350 miniflare: 5.20261006.2-beta
351 workerd: 1.20261006.1
352 transitivePeerDependencies:
353 - '@types/node'
354 - bufferutil
355 - utf-8-validate
357 '@cloudflare/workerd-darwin-64@1.20261006.1':
358 optional: true
360 '@cloudflare/workerd-darwin-arm64@1.20261006.1':
361 optional: true
363 '@cloudflare/workerd-linux-64@1.20261006.1':
364 optional: true
366 '@cloudflare/workerd-linux-arm64@1.20261006.1':
367 optional: true
369 '@cloudflare/workerd-windows-64@1.20261006.1':
370 optional: true
372 '@cspotcode/source-map-support@0.8.1':
373 dependencies:
374 '@jridgewell/trace-mapping': 0.3.9
376 '@emnapi/runtime@1.11.3':
377 dependencies:
378 tslib: 2.9.1
379 optional: true
381 '@img/colour@1.1.0': {}
383 '@img/sharp-darwin-arm64@0.35.5':
384 optionalDependencies:
385 '@img/sharp-libvips-darwin-arm64': 1.3.4
386 optional: true
388 '@img/sharp-darwin-x64@0.35.5':
389 optionalDependencies:
390 '@img/sharp-libvips-darwin-x64': 1.3.4
391 optional: true
393 '@img/sharp-freebsd-wasm32@0.35.5':
394 dependencies:
395 '@img/sharp-wasm32': 0.35.5
396 optional: true
398 '@img/sharp-libvips-darwin-arm64@1.3.4':
399 optional: true
401 '@img/sharp-libvips-darwin-x64@1.3.4':
402 optional: true
404 '@img/sharp-libvips-linux-arm64@1.3.4':
405 optional: true
407 '@img/sharp-libvips-linux-arm@1.3.4':
408 optional: true
410 '@img/sharp-libvips-linux-ppc64@1.3.4':
411 optional: true
413 '@img/sharp-libvips-linux-riscv64@1.3.4':
414 optional: true
416 '@img/sharp-libvips-linux-s390x@1.3.4':
417 optional: true
419 '@img/sharp-libvips-linux-x64@1.3.4':
420 optional: true
422 '@img/sharp-libvips-linuxmusl-arm64@1.3.4':
423 optional: true
425 '@img/sharp-libvips-linuxmusl-x64@1.3.4':
426 optional: true
428 '@img/sharp-linux-arm64@0.35.5':
429 optionalDependencies:
430 '@img/sharp-libvips-linux-arm64': 1.3.4
431 optional: true
433 '@img/sharp-linux-arm@0.35.5':
434 optionalDependencies:
435 '@img/sharp-libvips-linux-arm': 1.3.4
436 optional: true
438 '@img/sharp-linux-ppc64@0.35.5':
439 optionalDependencies:
440 '@img/sharp-libvips-linux-ppc64': 1.3.4
441 optional: true
443 '@img/sharp-linux-riscv64@0.35.5':
444 optionalDependencies:
445 '@img/sharp-libvips-linux-riscv64': 1.3.4
446 optional: true
448 '@img/sharp-linux-s390x@0.35.5':
449 optionalDependencies:
450 '@img/sharp-libvips-linux-s390x': 1.3.4
451 optional: true
453 '@img/sharp-linux-x64@0.35.5':
454 optionalDependencies:
455 '@img/sharp-libvips-linux-x64': 1.3.4
456 optional: true
458 '@img/sharp-linuxmusl-arm64@0.35.5':
459 optionalDependencies:
460 '@img/sharp-libvips-linuxmusl-arm64': 1.3.4
461 optional: true
463 '@img/sharp-linuxmusl-x64@0.35.5':
464 optionalDependencies:
465 '@img/sharp-libvips-linuxmusl-x64': 1.3.4
466 optional: true
468 '@img/sharp-wasm32@0.35.5':
469 dependencies:
470 '@emnapi/runtime': 1.11.3
471 optional: true
473 '@img/sharp-webcontainers-wasm32@0.35.5':
474 dependencies:
475 '@img/sharp-wasm32': 0.35.5
476 optional: true
478 '@img/sharp-win32-arm64@0.35.5':
479 optional: true
481 '@img/sharp-win32-ia32@0.35.5':
482 optional: true
484 '@img/sharp-win32-x64@0.35.5':
485 optional: true
487 '@jridgewell/resolve-uri@3.1.2': {}
489 '@jridgewell/sourcemap-codec@1.6.0': {}
491 '@jridgewell/trace-mapping@0.3.9':
492 dependencies:
493 '@jridgewell/resolve-uri': 3.1.2
494 '@jridgewell/sourcemap-codec': 1.6.0
496 '@poppinss/colors@4.1.6':
497 dependencies:
498 kleur: 4.1.5
500 '@poppinss/dumper@0.6.5':
501 dependencies:
502 '@poppinss/colors': 4.1.6
503 '@sindresorhus/is': 7.2.0
504 supports-color: 10.2.2
506 '@poppinss/exception@1.2.3': {}
508 '@sindresorhus/is@7.2.0': {}
510 '@speed-highlight/core@1.2.24': {}
512 blake3-wasm@2.1.5: {}
514 cf@1.0.0-beta.16:
515 dependencies:
516 '@cloudflare/build-output-utils': 0.9.1
517 '@cloudflare/codemods': 0.4.2
518 '@cloudflare/config': 0.25.0
519 '@cloudflare/runtime-types': 0.1.10
520 blake3-wasm: 2.1.5
521 miniflare: 5.20261006.2-beta
522 minisearch: 7.2.0
523 transitivePeerDependencies:
524 - '@types/node'
525 - bufferutil
526 - utf-8-validate
528 cookie@1.1.1: {}
530 detect-libc@2.1.2: {}
532 error-stack-parser-es@1.0.5: {}
534 kleur@4.1.5: {}
536 miniflare@5.20261006.2-beta:
537 dependencies:
538 '@cspotcode/source-map-support': 0.8.1
539 sharp: 0.35.5
540 undici: 7.29.1
541 workerd: 1.20261006.1
542 ws: 8.21.0
543 youch: 4.1.0-beta.10
544 transitivePeerDependencies:
545 - '@types/node'
546 - bufferutil
547 - utf-8-validate
549 minisearch@7.2.0: {}
551 semver@7.8.6: {}
553 sharp@0.35.5:
554 dependencies:
555 '@img/colour': 1.1.0
556 detect-libc: 2.1.2
557 semver: 7.8.6
558 optionalDependencies:
559 '@img/sharp-darwin-arm64': 0.35.5
560 '@img/sharp-darwin-x64': 0.35.5
561 '@img/sharp-freebsd-wasm32': 0.35.5
562 '@img/sharp-libvips-darwin-arm64': 1.3.4
563 '@img/sharp-libvips-darwin-x64': 1.3.4
564 '@img/sharp-libvips-linux-arm': 1.3.4
565 '@img/sharp-libvips-linux-arm64': 1.3.4
566 '@img/sharp-libvips-linux-ppc64': 1.3.4
567 '@img/sharp-libvips-linux-riscv64': 1.3.4
568 '@img/sharp-libvips-linux-s390x': 1.3.4
569 '@img/sharp-libvips-linux-x64': 1.3.4
570 '@img/sharp-libvips-linuxmusl-arm64': 1.3.4
571 '@img/sharp-libvips-linuxmusl-x64': 1.3.4
572 '@img/sharp-linux-arm': 0.35.5
573 '@img/sharp-linux-arm64': 0.35.5
574 '@img/sharp-linux-ppc64': 0.35.5
575 '@img/sharp-linux-riscv64': 0.35.5
576 '@img/sharp-linux-s390x': 0.35.5
577 '@img/sharp-linux-x64': 0.35.5
578 '@img/sharp-linuxmusl-arm64': 0.35.5
579 '@img/sharp-linuxmusl-x64': 0.35.5
580 '@img/sharp-webcontainers-wasm32': 0.35.5
581 '@img/sharp-win32-arm64': 0.35.5
582 '@img/sharp-win32-ia32': 0.35.5
583 '@img/sharp-win32-x64': 0.35.5
585 supports-color@10.2.2: {}
587 tslib@2.9.1:
588 optional: true
590 undici@7.29.1: {}
592 workerd@1.20261006.1:
593 optionalDependencies:
594 '@cloudflare/workerd-darwin-64': 1.20261006.1
595 '@cloudflare/workerd-darwin-arm64': 1.20261006.1
596 '@cloudflare/workerd-linux-64': 1.20261006.1
597 '@cloudflare/workerd-linux-arm64': 1.20261006.1
598 '@cloudflare/workerd-windows-64': 1.20261006.1
600 ws@8.21.0: {}
602 youch-core@0.3.3:
603 dependencies:
604 '@poppinss/exception': 1.2.3
605 error-stack-parser-es: 1.0.5
607 youch@4.1.0-beta.10:
608 dependencies:
609 '@poppinss/colors': 4.1.6
610 '@poppinss/dumper': 0.6.5
611 '@speed-highlight/core': 1.2.24
612 cookie: 1.1.1
613 youch-core: 0.3.3
615 zod@4.6.5: {}

mise/locks/npm-cf/1.0.0-beta.16/package.json

Added
new file mode 100644

+7 / −0 text lines

1{
2 "name": "mise-npm-install",
3 "private": true,
4 "dependencies": {
5 "cf": "1.0.0-beta.16"
6 }
7}

mise/mise.lock

Added
new file mode 100644

+170 / −0 text lines

1# @generated - this file is auto-generated by `mise lock` https://mise.jdx.dev/dev-tools/mise-lock.html
2
3lockfile_version = 3
4
5[[tools.ast-grep]]
6version = "0.51.1"
7backend = "aqua:ast-grep/ast-grep"
8specifiers = ["latest"]
9
10[tools.ast-grep."platforms.linux-x64"]
11checksum = "sha256:42514f77ae0c8a25d7d32154d31d3e7e16f3ab894f8ce76ce417de234ee49157"
12checksum_source = "mise-versions"
13url = "https://github.com/ast-grep/ast-grep/releases/download/0.51.1/app-x86_64-unknown-linux-gnu.zip"
14url_api = "https://api.github.com/repos/ast-grep/ast-grep/releases/assets/701823082"
16[tools.ast-grep."platforms.macos-arm64"]
17checksum = "sha256:a95772097b4d02bd9d45ed63b300c37041ae3c36632b3bf19250cc7c10187dc4"
18checksum_source = "mise-versions"
19url = "https://github.com/ast-grep/ast-grep/releases/download/0.51.1/app-aarch64-apple-darwin.zip"
20url_api = "https://api.github.com/repos/ast-grep/ast-grep/releases/assets/701845634"
22[tools.ast-grep."platforms.windows-x64"]
23checksum = "sha256:12a0cefb77498820ef6fb302ed8758cbda39be87d4c15120dc74c1dea968a50d"
24url = "https://github.com/ast-grep/ast-grep/releases/download/0.51.1/app-x86_64-pc-windows-msvc.zip"
25url_api = "https://api.github.com/repos/ast-grep/ast-grep/releases/assets/701859070"
27[[tools.carapace]]
28version = "1.8.2"
29backend = "aqua:carapace-sh/carapace-bin"
30specifiers = ["latest"]
32[tools.carapace."platforms.linux-x64"]
33checksum = "sha256:1b3dc4cab51361d3443400aefa4314ad8d44d8414bf4b1d18f41a6fe71b1b0e4"
34checksum_source = "mise-versions"
35url = "https://github.com/carapace-sh/carapace-bin/releases/download/v1.8.2/carapace-bin_1.8.2_linux_amd64.tar.gz"
36url_api = "https://api.github.com/repos/carapace-sh/carapace-bin/releases/assets/698585320"
38[tools.carapace."platforms.macos-arm64"]
39checksum = "sha256:d9c05be343f19005f4bd568f2cedd8307c358e82aff32ebfb2d42af0c52b28ea"
40checksum_source = "mise-versions"
41url = "https://github.com/carapace-sh/carapace-bin/releases/download/v1.8.2/carapace-bin_1.8.2_darwin_arm64.tar.gz"
42url_api = "https://api.github.com/repos/carapace-sh/carapace-bin/releases/assets/698585380"
44[tools.carapace."platforms.windows-x64"]
45checksum = "sha256:44ac5d1f16bf38df559259783680925fe9625e467e020b180ea1e8d7c721d4e5"
46url = "https://github.com/carapace-sh/carapace-bin/releases/download/v1.8.2/carapace-bin_1.8.2_windows_amd64.zip"
47url_api = "https://api.github.com/repos/carapace-sh/carapace-bin/releases/assets/698585413"
49[[tools.cargo-binstall]]
50version = "1.26.2"
51backend = "aqua:cargo-bins/cargo-binstall"
52specifiers = ["latest"]
54[tools.cargo-binstall."platforms.linux-x64"]
55checksum = "sha256:4f28eba175325f67f7c4bb8ae8686914d2d88fead279c0b8c4d3125264d7a512"
56url = "https://github.com/cargo-bins/cargo-binstall/releases/download/v1.26.2/cargo-binstall-x86_64-unknown-linux-gnu.tgz"
57url_api = "https://api.github.com/repos/cargo-bins/cargo-binstall/releases/assets/695464312"
58provenance = "github-attestations"
60[tools.cargo-binstall."platforms.macos-arm64"]
61checksum = "sha256:0f9ddd602d439ea64f03a5c188c59656d5ef389ecdcbff044c8d373e51c0e2b3"
62url = "https://github.com/cargo-bins/cargo-binstall/releases/download/v1.26.2/cargo-binstall-aarch64-apple-darwin.zip"
63url_api = "https://api.github.com/repos/cargo-bins/cargo-binstall/releases/assets/695465979"
64provenance = "github-attestations"
66[tools.cargo-binstall."platforms.windows-x64"]
67checksum = "sha256:c377a4977ffdbdcbf58dd263055b2f1d56ba873c69fbd6bfc60bef98256183a3"
68url = "https://github.com/cargo-bins/cargo-binstall/releases/download/v1.26.2/cargo-binstall-x86_64-pc-windows-msvc.zip"
69url_api = "https://api.github.com/repos/cargo-bins/cargo-binstall/releases/assets/695464456"
70provenance = "github-attestations"
72[[tools."cargo:kdl-lsp"]]
73version = "6.7.1"
74backend = "cargo:kdl-lsp"
75specifiers = ["latest"]
77[[tools."cargo:resvg"]]
78version = "0.49.0"
79backend = "cargo:resvg"
80specifiers = ["latest"]
82[[tools."github:Bios-Marcel/call_of_slop_modern_warefare_2"]]
83version = "0.5.9"
84backend = "github:Bios-Marcel/call_of_slop_modern_warefare_2"
85specifiers = ["latest"]
87[tools."github:Bios-Marcel/call_of_slop_modern_warefare_2".options]
88asset_pattern = "rust-intervention-{{ version }}-linux-x86_64-forward-plus.zip"
90[tools."github:Bios-Marcel/call_of_slop_modern_warefare_2"."platforms.linux-x64"]
91checksum = "sha256:3368134eb44fb63c0382508476d8d0318401fd4088061f7c92389c825cb09e16"
92url = "https://github.com/Bios-Marcel/call_of_slop_modern_warefare_2/releases/download/v0.5.9/rust-intervention-0.5.9-linux-x86_64-forward-plus.zip"
93url_api = "https://api.github.com/repos/Bios-Marcel/call_of_slop_modern_warefare_2/releases/assets/761122860"
95[[tools."github:Bios-Marcel/call_of_slop_modern_warefare_2"]]
96version = "0.5.9"
97backend = "github:Bios-Marcel/call_of_slop_modern_warefare_2"
98specifiers = ["latest"]
100[tools."github:Bios-Marcel/call_of_slop_modern_warefare_2".options]
101asset_pattern = "rust-intervention-{{ version }}-windows-x86_64-forward-plus.zip"
103[tools."github:Bios-Marcel/call_of_slop_modern_warefare_2"."platforms.windows-x64"]
104checksum = "sha256:be38c84637f70d599ec0867cc49d14ba400216a78be9388865acbaa05f3dd6ff"
105url = "https://github.com/Bios-Marcel/call_of_slop_modern_warefare_2/releases/download/v0.5.9/rust-intervention-0.5.9-windows-x86_64-forward-plus.zip"
106url_api = "https://api.github.com/repos/Bios-Marcel/call_of_slop_modern_warefare_2/releases/assets/761122859"
108[[tools."http:git-revue"]]
109version = "0.1.0"
110backend = "http:git-revue"
111specifiers = ["0.1.0"]
113[tools."http:git-revue"."platforms.linux-x64"]
114checksum = "sha256:8e4de1339e27e5ce1af5aa22f8b0d547cf4fb4553cc41e02eb1c97465e396062"
115url = "https://pkg.bugabinga.net/releases/revue/git-revue-0.1.0-x86_64-unknown-linux-gnu.tar.gz"
117[tools."http:git-revue"."platforms.android-arm64"]
118checksum = "sha256:7189215130426cdbee92160192327ab318f3fa56fdb49d3d99c509a3c3d82768"
119url = "https://pkg.bugabinga.net/releases/revue/cross/git-revue-0.1.0-aarch64-linux-android.tar.gz"
121[[tools."http:mergiraf"]]
122version = "0.19.1"
123backend = "http:mergiraf"
124specifiers = ["0.19.1"]
126[tools."http:mergiraf"."platforms.linux-x64"]
127checksum = "sha256:632ad77f90bf4874e8b89cfe7073bfbd6ad55c7565d2fa9530062b8df683cc30"
128url = "https://codeberg.org/mergiraf/mergiraf/releases/download/v0.19.1/mergiraf_x86_64-unknown-linux-musl.tar.gz"
130[tools."http:mergiraf"."platforms.macos-arm64"]
131checksum = "sha256:5bdcacc88dcabfd131591b3852a34c98fc9a23afdb5bc5ed1a58450269f7ddb2"
132url = "https://codeberg.org/mergiraf/mergiraf/releases/download/v0.19.1/mergiraf_aarch64-apple-darwin.tar.gz"
134[tools."http:mergiraf"."platforms.windows-x64"]
135checksum = "sha256:632ad77f90bf4874e8b89cfe7073bfbd6ad55c7565d2fa9530062b8df683cc30"
136url = "https://codeberg.org/mergiraf/mergiraf/releases/download/v0.19.1/mergiraf_x86_64-unknown-linux-musl.tar.gz"
138[[tools.mr-boxington]]
139version = "1.30.0"
140backend = "packslip:github.com/jdx/mr-boxington"
141specifiers = ["latest"]
143[tools.mr-boxington."platforms.linux-x64"]
144checksum = "sha256:f4992b401fe65744b7c6e7400933d2106da205b499405621d088051a31a8f3f2"
145url = "https://github.com/jdx/mr-boxington/releases/download/v1.30.0/mbx-x86_64-unknown-linux-gnu.tar.gz"
146signer = "sigstore-oidc:https://github.com/jdx/mr-boxington/.github/workflows/release.yml"
147repository_ids = { repository = "1340721957" }
149[tools.mr-boxington."platforms.macos-arm64"]
150checksum = "sha256:d5b957216c8b61c2df91c9e7aaf5febd45ec74274a60d3714ebe316edc144543"
151url = "https://github.com/jdx/mr-boxington/releases/download/v1.30.0/mbx-aarch64-apple-darwin.tar.gz"
152signer = "sigstore-oidc:https://github.com/jdx/mr-boxington/.github/workflows/release.yml"
153repository_ids = { repository = "1340721957" }
155[tools.mr-boxington."platforms.windows-x64"]
156checksum = "sha256:2d709445957ea5dae95d51379aa9e7e575cfedb12c0d5731de4761a6972626f5"
157url = "https://github.com/jdx/mr-boxington/releases/download/v1.30.0/mbx-x86_64-pc-windows-msvc.zip"
158signer = "sigstore-oidc:https://github.com/jdx/mr-boxington/.github/workflows/release.yml"
159repository_ids = { repository = "1340721957" }
161[[tools."npm:cf"]]
162version = "1.0.0-beta.16"
163aube = { path = "locks/npm-cf/1.0.0-beta.16", digest = "sha256:8b59d85ea4e450bfdf4da508f9692c4e6f1331d89be7af4340a79e5c505c7ab6" }
164backend = "npm:cf"
165specifiers = ["1.0.0-beta.16"]
167[[tools.rust]]
168version = "stable"
169backend = "core:rust"
170specifiers = ["latest"]

mise/miserc.toml

Added
new file mode 100644

+1 / −0 text lines

1auto_env = true

mpv/scripts/skip.lua

Modified

+29 / −29 text lines

1-- Importing mpv module
2local mpv = require('mp')
3local mpv_options = require("mp.options")
4
5local options = { -- setting default options
6 op_start = 0, op_end = 0, ed_start = 0, ed_end = 0,
7}
8mpv_options.read_options(options, "skip") --reading script-opts data
9
10-- Main function to check and skip if within the defined section
11local function skip()
12 local current_time = mp.get_property_number("time-pos")
13
14 if not current_time then
15 return
16 end
17
18 -- Check for opening sequence
19 if current_time >= options.op_start and current_time < options.op_end then
20 mp.set_property_number("time-pos", options.op_end)
21 end
22
23 -- Check for ending sequence
24 if current_time >= options.ed_start and current_time < options.ed_end then
25 mp.set_property_number("time-pos", options.ed_end)
26 end
27end
28
29-- Bind the function to be called whenever the time position is changed
1-- Importing mpv module
2local mpv = require('mp')
3local mpv_options = require("mp.options")
4
5local options = { -- setting default options
6 op_start = 0, op_end = 0, ed_start = 0, ed_end = 0,
7}
8mpv_options.read_options(options, "skip") --reading script-opts data
9
10-- Main function to check and skip if within the defined section
11local function skip()
12 local current_time = mp.get_property_number("time-pos")
13
14 if not current_time then
15 return
16 end
18 -- Check for opening sequence
19 if current_time >= options.op_start and current_time < options.op_end then
20 mp.set_property_number("time-pos", options.op_end)
21 end
22
23 -- Check for ending sequence
24 if current_time >= options.ed_start and current_time < options.ed_end then
25 mp.set_property_number("time-pos", options.ed_end)
26 end
27end
29-- Bind the function to be called whenever the time position is changed
3030mp.observe_property("time-pos", "number", skip)No final newline

mpv/shaders/Anime4K_AutoDownscalePre_x2.glsl

Modified

+36 / −36 text lines

1// This is free and unencumbered software released into the public domain.
2
3// Anyone is free to copy, modify, publish, use, compile, sell, or
4// distribute this software, either in source code form or as a compiled
5// binary, for any purpose, commercial or non-commercial, and by any
6// means.
7
8// In jurisdictions that recognize copyright laws, the author or authors
9// of this software dedicate any and all copyright interest in the
10// software to the public domain. We make this dedication for the benefit
11// of the public at large and to the detriment of our heirs and
12// successors. We intend this dedication to be an overt act of
13// relinquishment in perpetuity of all present and future rights to this
14// software under copyright law.
15
16// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
17// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
18// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
19// IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
20// OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
21// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
22// OTHER DEALINGS IN THE SOFTWARE.
23
24// For more information, please refer to <https://unlicense.org>
25
26//!DESC Anime4K-v4.0-AutoDownscalePre-x2
27//!HOOK MAIN
28//!BIND HOOKED
29//!BIND NATIVE
30//!WHEN OUTPUT.w NATIVE.w / 2.0 < OUTPUT.h NATIVE.h / 2.0 < * OUTPUT.w NATIVE.w / 1.2 > OUTPUT.h NATIVE.h / 1.2 > * *
31//!WIDTH OUTPUT.w
32//!HEIGHT OUTPUT.h
33
34vec4 hook() {
35 return HOOKED_tex(HOOKED_pos);
36}
1// This is free and unencumbered software released into the public domain.
2
3// Anyone is free to copy, modify, publish, use, compile, sell, or
4// distribute this software, either in source code form or as a compiled
5// binary, for any purpose, commercial or non-commercial, and by any
6// means.
7
8// In jurisdictions that recognize copyright laws, the author or authors
9// of this software dedicate any and all copyright interest in the
10// software to the public domain. We make this dedication for the benefit
11// of the public at large and to the detriment of our heirs and
12// successors. We intend this dedication to be an overt act of
13// relinquishment in perpetuity of all present and future rights to this
14// software under copyright law.
16// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
17// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
18// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
19// IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
20// OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
21// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
22// OTHER DEALINGS IN THE SOFTWARE.
24// For more information, please refer to <https://unlicense.org>
26//!DESC Anime4K-v4.0-AutoDownscalePre-x2
27//!HOOK MAIN
28//!BIND HOOKED
29//!BIND NATIVE
30//!WHEN OUTPUT.w NATIVE.w / 2.0 < OUTPUT.h NATIVE.h / 2.0 < * OUTPUT.w NATIVE.w / 1.2 > OUTPUT.h NATIVE.h / 1.2 > * *
31//!WIDTH OUTPUT.w
32//!HEIGHT OUTPUT.h
34vec4 hook() {
35 return HOOKED_tex(HOOKED_pos);
36}

mpv/shaders/Anime4K_AutoDownscalePre_x4.glsl

Modified

+36 / −36 text lines

1// This is free and unencumbered software released into the public domain.
2
3// Anyone is free to copy, modify, publish, use, compile, sell, or
4// distribute this software, either in source code form or as a compiled
5// binary, for any purpose, commercial or non-commercial, and by any
6// means.
7
8// In jurisdictions that recognize copyright laws, the author or authors
9// of this software dedicate any and all copyright interest in the
10// software to the public domain. We make this dedication for the benefit
11// of the public at large and to the detriment of our heirs and
12// successors. We intend this dedication to be an overt act of
13// relinquishment in perpetuity of all present and future rights to this
14// software under copyright law.
15
16// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
17// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
18// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
19// IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
20// OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
21// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
22// OTHER DEALINGS IN THE SOFTWARE.
23
24// For more information, please refer to <https://unlicense.org>
25
26//!DESC Anime4K-v3.2-AutoDownscalePre-x4
27//!HOOK MAIN
28//!BIND HOOKED
29//!BIND NATIVE
30//!WHEN OUTPUT.w NATIVE.w / 4.0 < OUTPUT.h NATIVE.h / 4.0 < * OUTPUT.w NATIVE.w / 2.4 > OUTPUT.h NATIVE.h / 2.4 > * *
31//!WIDTH OUTPUT.w 2 /
32//!HEIGHT OUTPUT.h 2 /
33
34vec4 hook() {
35 return HOOKED_tex(HOOKED_pos);
36}
1// This is free and unencumbered software released into the public domain.
2
3// Anyone is free to copy, modify, publish, use, compile, sell, or
4// distribute this software, either in source code form or as a compiled
5// binary, for any purpose, commercial or non-commercial, and by any
6// means.
7
8// In jurisdictions that recognize copyright laws, the author or authors
9// of this software dedicate any and all copyright interest in the
10// software to the public domain. We make this dedication for the benefit
11// of the public at large and to the detriment of our heirs and
12// successors. We intend this dedication to be an overt act of
13// relinquishment in perpetuity of all present and future rights to this
14// software under copyright law.
16// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
17// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
18// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
19// IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
20// OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
21// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
22// OTHER DEALINGS IN THE SOFTWARE.
24// For more information, please refer to <https://unlicense.org>
26//!DESC Anime4K-v3.2-AutoDownscalePre-x4
27//!HOOK MAIN
28//!BIND HOOKED
29//!BIND NATIVE
30//!WHEN OUTPUT.w NATIVE.w / 4.0 < OUTPUT.h NATIVE.h / 4.0 < * OUTPUT.w NATIVE.w / 2.4 > OUTPUT.h NATIVE.h / 2.4 > * *
31//!WIDTH OUTPUT.w 2 /
32//!HEIGHT OUTPUT.h 2 /
34vec4 hook() {
35 return HOOKED_tex(HOOKED_pos);
36}

mpv/shaders/Anime4K_Clamp_Highlights.glsl

Modified

+89 / −89 text lines

1// MIT License
2
3// Copyright (c) 2019-2021 bloc97
4// All rights reserved.
5
6// Permission is hereby granted, free of charge, to any person obtaining a copy
7// of this software and associated documentation files (the "Software"), to deal
8// in the Software without restriction, including without limitation the rights
9// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10// copies of the Software, and to permit persons to whom the Software is
11// furnished to do so, subject to the following conditions:
12
13// The above copyright notice and this permission notice shall be included in all
14// copies or substantial portions of the Software.
15
16// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22// SOFTWARE.
23
24//!DESC Anime4K-v4.0-De-Ring-Compute-Statistics
25//!HOOK MAIN
26//!BIND HOOKED
27//!SAVE STATSMAX
28//!COMPONENTS 1
29
30#define KERNELSIZE 5 //Kernel size, must be an positive odd integer.
31#define KERNELHALFSIZE 2 //Half of the kernel size without remainder. Must be equal to trunc(KERNELSIZE/2).
32
33float get_luma(vec4 rgba) {
34 return dot(vec4(0.299, 0.587, 0.114, 0.0), rgba);
35}
36
37vec4 hook() {
38
39 float gmax = 0.0;
40
41 for (int i=0; i<KERNELSIZE; i++) {
42 float g = get_luma(MAIN_texOff(vec2(i - KERNELHALFSIZE, 0)));
43
44 gmax = max(g, gmax);
45 }
46
47 return vec4(gmax, 0.0, 0.0, 0.0);
48}
49
50//!DESC Anime4K-v4.0-De-Ring-Compute-Statistics
51//!HOOK MAIN
52//!BIND HOOKED
53//!BIND STATSMAX
54//!SAVE STATSMAX
55//!COMPONENTS 1
56
57#define KERNELSIZE 5 //Kernel size, must be an positive odd integer.
58#define KERNELHALFSIZE 2 //Half of the kernel size without remainder. Must be equal to trunc(KERNELSIZE/2).
59
60vec4 hook() {
61
62 float gmax = 0.0;
63
64 for (int i=0; i<KERNELSIZE; i++) {
65 float g = STATSMAX_texOff(vec2(0, i - KERNELHALFSIZE)).x;
66
67 gmax = max(g, gmax);
68 }
69
70 return vec4(gmax, 0.0, 0.0, 0.0);
71}
72
73//!DESC Anime4K-v4.0-De-Ring-Clamp
74//!HOOK PREKERNEL
75//!BIND HOOKED
76//!BIND STATSMAX
77
78float get_luma(vec4 rgba) {
79 return dot(vec4(0.299, 0.587, 0.114, 0.0), rgba);
80}
81
82vec4 hook() {
83
84 float current_luma = get_luma(HOOKED_tex(HOOKED_pos));
85 float new_luma = min(current_luma, STATSMAX_tex(HOOKED_pos).x);
86
87 //This trick is only possible if the inverse Y->RGB matrix has 1 for every row... (which is the case for BT.709)
88 //Otherwise we would need to convert RGB to YUV, modify Y then convert back to RGB.
89 return HOOKED_tex(HOOKED_pos) - (current_luma - new_luma);
1// MIT License
2
3// Copyright (c) 2019-2021 bloc97
4// All rights reserved.
5
6// Permission is hereby granted, free of charge, to any person obtaining a copy
7// of this software and associated documentation files (the "Software"), to deal
8// in the Software without restriction, including without limitation the rights
9// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10// copies of the Software, and to permit persons to whom the Software is
11// furnished to do so, subject to the following conditions:
13// The above copyright notice and this permission notice shall be included in all
14// copies or substantial portions of the Software.
16// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22// SOFTWARE.
24//!DESC Anime4K-v4.0-De-Ring-Compute-Statistics
25//!HOOK MAIN
26//!BIND HOOKED
27//!SAVE STATSMAX
28//!COMPONENTS 1
30#define KERNELSIZE 5 //Kernel size, must be an positive odd integer.
31#define KERNELHALFSIZE 2 //Half of the kernel size without remainder. Must be equal to trunc(KERNELSIZE/2).
33float get_luma(vec4 rgba) {
34 return dot(vec4(0.299, 0.587, 0.114, 0.0), rgba);
35}
37vec4 hook() {
39 float gmax = 0.0;
40
41 for (int i=0; i<KERNELSIZE; i++) {
42 float g = get_luma(MAIN_texOff(vec2(i - KERNELHALFSIZE, 0)));
43
44 gmax = max(g, gmax);
45 }
46
47 return vec4(gmax, 0.0, 0.0, 0.0);
48}
50//!DESC Anime4K-v4.0-De-Ring-Compute-Statistics
51//!HOOK MAIN
52//!BIND HOOKED
53//!BIND STATSMAX
54//!SAVE STATSMAX
55//!COMPONENTS 1
57#define KERNELSIZE 5 //Kernel size, must be an positive odd integer.
58#define KERNELHALFSIZE 2 //Half of the kernel size without remainder. Must be equal to trunc(KERNELSIZE/2).
60vec4 hook() {
62 float gmax = 0.0;
63
64 for (int i=0; i<KERNELSIZE; i++) {
65 float g = STATSMAX_texOff(vec2(0, i - KERNELHALFSIZE)).x;
66
67 gmax = max(g, gmax);
68 }
69
70 return vec4(gmax, 0.0, 0.0, 0.0);
71}
73//!DESC Anime4K-v4.0-De-Ring-Clamp
74//!HOOK PREKERNEL
75//!BIND HOOKED
76//!BIND STATSMAX
78float get_luma(vec4 rgba) {
79 return dot(vec4(0.299, 0.587, 0.114, 0.0), rgba);
80}
82vec4 hook() {
84 float current_luma = get_luma(HOOKED_tex(HOOKED_pos));
85 float new_luma = min(current_luma, STATSMAX_tex(HOOKED_pos).x);
86
87 //This trick is only possible if the inverse Y->RGB matrix has 1 for every row... (which is the case for BT.709)
88 //Otherwise we would need to convert RGB to YUV, modify Y then convert back to RGB.
89 return HOOKED_tex(HOOKED_pos) - (current_luma - new_luma);
9090}No final newline

mpv/shaders/Anime4K_Darken_Fast.glsl

Modified

+216 / −216 text lines

1// MIT License
2
3// Copyright (c) 2019-2021 bloc97
4// All rights reserved.
5
6// Permission is hereby granted, free of charge, to any person obtaining a copy
7// of this software and associated documentation files (the "Software"), to deal
8// in the Software without restriction, including without limitation the rights
9// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10// copies of the Software, and to permit persons to whom the Software is
11// furnished to do so, subject to the following conditions:
12
13// The above copyright notice and this permission notice shall be included in all
14// copies or substantial portions of the Software.
15
16// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22// SOFTWARE.
23
24//!DESC Anime4K-v3.2-Darken-DoG-(HQ)-Luma
25//!HOOK MAIN
26//!BIND HOOKED
27//!SAVE LINELUMA
28//!COMPONENTS 1
29
30float get_luma(vec4 rgba) {
31 return dot(vec4(0.299, 0.587, 0.114, 0.0), rgba);
32}
33
34vec4 hook() {
35 return vec4(get_luma(HOOKED_tex(HOOKED_pos)), 0.0, 0.0, 0.0);
36}
37
38//!DESC Anime4K-v3.2-Darken-DoG-(Fast)-Difference-X
39//!HOOK MAIN
40//!BIND HOOKED
41//!BIND LINELUMA
42//!SAVE LINEKERNEL
43//!WIDTH HOOKED.w 2 /
44//!HEIGHT HOOKED.h 2 /
45//!COMPONENTS 1
46
47#define SPATIAL_SIGMA (1.0 * float(HOOKED_size.y) / 1080.0) //Spatial window size, must be a positive real number.
48
49#define KERNELSIZE (max(int(ceil(SPATIAL_SIGMA * 2.0)), 1) * 2 + 1) //Kernel size, must be an positive odd integer.
50#define KERNELHALFSIZE (int(KERNELSIZE/2)) //Half of the kernel size without remainder. Must be equal to trunc(KERNELSIZE/2).
51#define KERNELLEN (KERNELSIZE * KERNELSIZE) //Total area of kernel. Must be equal to KERNELSIZE * KERNELSIZE.
52
53float gaussian(float x, float s, float m) {
54 float scaled = (x - m) / s;
55 return exp(-0.5 * scaled * scaled);
56}
57
58float comp_gaussian_x() {
59
60 float g = 0.0;
61 float gn = 0.0;
62
63 for (int i=0; i<KERNELSIZE; i++) {
64 float di = float(i - KERNELHALFSIZE);
65 float gf = gaussian(di, SPATIAL_SIGMA, 0.0);
66
67 g = g + LINELUMA_texOff(vec2(di, 0.0)).x * gf;
68 gn = gn + gf;
69
70 }
71
72 return g / gn;
73}
74
75vec4 hook() {
76 return vec4(comp_gaussian_x(), 0.0, 0.0, 0.0);
77}
78
79//!DESC Anime4K-v3.2-Darken-DoG-(Fast)-Difference-Y
80//!HOOK MAIN
81//!BIND HOOKED
82//!BIND LINELUMA
83//!BIND LINEKERNEL
84//!SAVE LINEKERNEL
85//!WIDTH HOOKED.w 2 /
86//!HEIGHT HOOKED.h 2 /
87//!COMPONENTS 1
88
89#define SPATIAL_SIGMA (0.5 * float(HOOKED_size.y) / 1080.0) //Spatial window size, must be a positive real number.
90
91#define KERNELSIZE (max(int(ceil(SPATIAL_SIGMA * 2.0)), 1) * 2 + 1) //Kernel size, must be an positive odd integer.
92#define KERNELHALFSIZE (int(KERNELSIZE/2)) //Half of the kernel size without remainder. Must be equal to trunc(KERNELSIZE/2).
93#define KERNELLEN (KERNELSIZE * KERNELSIZE) //Total area of kernel. Must be equal to KERNELSIZE * KERNELSIZE.
94
95float gaussian(float x, float s, float m) {
96 float scaled = (x - m) / s;
97 return exp(-0.5 * scaled * scaled);
98}
99
100float comp_gaussian_y() {
101
102 float g = 0.0;
103 float gn = 0.0;
104
105 for (int i=0; i<KERNELSIZE; i++) {
106 float di = float(i - KERNELHALFSIZE);
107 float gf = gaussian(di, SPATIAL_SIGMA, 0.0);
108
109 g = g + LINEKERNEL_texOff(vec2(0.0, di)).x * gf;
110 gn = gn + gf;
111
112 }
113
114 return g / gn;
115}
116
117vec4 hook() {
118 return vec4(min(LINELUMA_tex(HOOKED_pos).x - comp_gaussian_y(), 0.0), 0.0, 0.0, 0.0);
119}
120
121//!DESC Anime4K-v3.2-Darken-DoG-(Fast)-Gaussian-X
122//!HOOK MAIN
123//!BIND HOOKED
124//!BIND LINEKERNEL
125//!SAVE LINEKERNEL
126//!WIDTH HOOKED.w 2 /
127//!HEIGHT HOOKED.h 2 /
128//!COMPONENTS 1
129
130#define SPATIAL_SIGMA (0.5 * float(HOOKED_size.y) / 1080.0) //Spatial window size, must be a positive real number.
131
132#define KERNELSIZE (max(int(ceil(SPATIAL_SIGMA * 2.0)), 1) * 2 + 1) //Kernel size, must be an positive odd integer.
133#define KERNELHALFSIZE (int(KERNELSIZE/2)) //Half of the kernel size without remainder. Must be equal to trunc(KERNELSIZE/2).
134#define KERNELLEN (KERNELSIZE * KERNELSIZE) //Total area of kernel. Must be equal to KERNELSIZE * KERNELSIZE.
135
136float gaussian(float x, float s, float m) {
137 float scaled = (x - m) / s;
138 return exp(-0.5 * scaled * scaled);
139}
140
141float comp_gaussian_x() {
142
143 float g = 0.0;
144 float gn = 0.0;
145
146 for (int i=0; i<KERNELSIZE; i++) {
147 float di = float(i - KERNELHALFSIZE);
148 float gf = gaussian(di, SPATIAL_SIGMA, 0.0);
149
150 g = g + LINEKERNEL_texOff(vec2(di, 0.0)).x * gf;
151 gn = gn + gf;
152
153 }
154
155 return g / gn;
156}
157
158vec4 hook() {
159 return vec4(comp_gaussian_x(), 0.0, 0.0, 0.0);
160}
161
162//!DESC Anime4K-v3.2-Darken-DoG-(Fast)-Gaussian-Y
163//!HOOK MAIN
164//!BIND HOOKED
165//!BIND LINEKERNEL
166//!SAVE LINEKERNEL
167//!WIDTH HOOKED.w 2 /
168//!HEIGHT HOOKED.h 2 /
169//!COMPONENTS 1
170
171#define SPATIAL_SIGMA (0.5 * float(HOOKED_size.y) / 1080.0) //Spatial window size, must be a positive real number.
172
173#define KERNELSIZE (max(int(ceil(SPATIAL_SIGMA * 2.0)), 1) * 2 + 1) //Kernel size, must be an positive odd integer.
174#define KERNELHALFSIZE (int(KERNELSIZE/2)) //Half of the kernel size without remainder. Must be equal to trunc(KERNELSIZE/2).
175#define KERNELLEN (KERNELSIZE * KERNELSIZE) //Total area of kernel. Must be equal to KERNELSIZE * KERNELSIZE.
176
177float gaussian(float x, float s, float m) {
178 float scaled = (x - m) / s;
179 return exp(-0.5 * scaled * scaled);
180}
181
182float comp_gaussian_y() {
183
184 float g = 0.0;
185 float gn = 0.0;
186
187 for (int i=0; i<KERNELSIZE; i++) {
188 float di = float(i - KERNELHALFSIZE);
189 float gf = gaussian(di, SPATIAL_SIGMA, 0.0);
190
191 g = g + LINEKERNEL_texOff(vec2(0.0, di)).x * gf;
192 gn = gn + gf;
193
194 }
195
196 return g / gn;
197}
198
199vec4 hook() {
200 return vec4(comp_gaussian_y(), 0.0, 0.0, 0.0);
201}
202
203
204//!DESC Anime4K-v3.2-Darken-DoG-(Fast)-Upsample
205//!HOOK MAIN
206//!BIND HOOKED
207//!BIND LINEKERNEL
208
209#define STRENGTH 1.5 //Line darken proportional strength, higher is darker.
210
211vec4 hook() {
212 //This trick is only possible if the inverse Y->RGB matrix has 1 for every row... (which is the case for BT.709)
213 //Otherwise we would need to convert RGB to YUV, modify Y then convert back to RGB.
214 return HOOKED_tex(HOOKED_pos) + (LINEKERNEL_tex(HOOKED_pos).x * STRENGTH);
215}
216
1// MIT License
2
3// Copyright (c) 2019-2021 bloc97
4// All rights reserved.
5
6// Permission is hereby granted, free of charge, to any person obtaining a copy
7// of this software and associated documentation files (the "Software"), to deal
8// in the Software without restriction, including without limitation the rights
9// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10// copies of the Software, and to permit persons to whom the Software is
11// furnished to do so, subject to the following conditions:
13// The above copyright notice and this permission notice shall be included in all
14// copies or substantial portions of the Software.
16// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22// SOFTWARE.
24//!DESC Anime4K-v3.2-Darken-DoG-(HQ)-Luma
25//!HOOK MAIN
26//!BIND HOOKED
27//!SAVE LINELUMA
28//!COMPONENTS 1
30float get_luma(vec4 rgba) {
31 return dot(vec4(0.299, 0.587, 0.114, 0.0), rgba);
32}
34vec4 hook() {
35 return vec4(get_luma(HOOKED_tex(HOOKED_pos)), 0.0, 0.0, 0.0);
36}
38//!DESC Anime4K-v3.2-Darken-DoG-(Fast)-Difference-X
39//!HOOK MAIN
40//!BIND HOOKED
41//!BIND LINELUMA
42//!SAVE LINEKERNEL
43//!WIDTH HOOKED.w 2 /
44//!HEIGHT HOOKED.h 2 /
45//!COMPONENTS 1
47#define SPATIAL_SIGMA (1.0 * float(HOOKED_size.y) / 1080.0) //Spatial window size, must be a positive real number.
49#define KERNELSIZE (max(int(ceil(SPATIAL_SIGMA * 2.0)), 1) * 2 + 1) //Kernel size, must be an positive odd integer.
50#define KERNELHALFSIZE (int(KERNELSIZE/2)) //Half of the kernel size without remainder. Must be equal to trunc(KERNELSIZE/2).
51#define KERNELLEN (KERNELSIZE * KERNELSIZE) //Total area of kernel. Must be equal to KERNELSIZE * KERNELSIZE.
53float gaussian(float x, float s, float m) {
54 float scaled = (x - m) / s;
55 return exp(-0.5 * scaled * scaled);
56}
58float comp_gaussian_x() {
60 float g = 0.0;
61 float gn = 0.0;
62
63 for (int i=0; i<KERNELSIZE; i++) {
64 float di = float(i - KERNELHALFSIZE);
65 float gf = gaussian(di, SPATIAL_SIGMA, 0.0);
66
67 g = g + LINELUMA_texOff(vec2(di, 0.0)).x * gf;
68 gn = gn + gf;
69
70 }
71
72 return g / gn;
73}
75vec4 hook() {
76 return vec4(comp_gaussian_x(), 0.0, 0.0, 0.0);
77}
79//!DESC Anime4K-v3.2-Darken-DoG-(Fast)-Difference-Y
80//!HOOK MAIN
81//!BIND HOOKED
82//!BIND LINELUMA
83//!BIND LINEKERNEL
84//!SAVE LINEKERNEL
85//!WIDTH HOOKED.w 2 /
86//!HEIGHT HOOKED.h 2 /
87//!COMPONENTS 1
89#define SPATIAL_SIGMA (0.5 * float(HOOKED_size.y) / 1080.0) //Spatial window size, must be a positive real number.
91#define KERNELSIZE (max(int(ceil(SPATIAL_SIGMA * 2.0)), 1) * 2 + 1) //Kernel size, must be an positive odd integer.
92#define KERNELHALFSIZE (int(KERNELSIZE/2)) //Half of the kernel size without remainder. Must be equal to trunc(KERNELSIZE/2).
93#define KERNELLEN (KERNELSIZE * KERNELSIZE) //Total area of kernel. Must be equal to KERNELSIZE * KERNELSIZE.
95float gaussian(float x, float s, float m) {
96 float scaled = (x - m) / s;
97 return exp(-0.5 * scaled * scaled);
98}
100float comp_gaussian_y() {
102 float g = 0.0;
103 float gn = 0.0;
104
105 for (int i=0; i<KERNELSIZE; i++) {
106 float di = float(i - KERNELHALFSIZE);
107 float gf = gaussian(di, SPATIAL_SIGMA, 0.0);
108
109 g = g + LINEKERNEL_texOff(vec2(0.0, di)).x * gf;
110 gn = gn + gf;
111
112 }
113
114 return g / gn;
115}
117vec4 hook() {
118 return vec4(min(LINELUMA_tex(HOOKED_pos).x - comp_gaussian_y(), 0.0), 0.0, 0.0, 0.0);
119}
121//!DESC Anime4K-v3.2-Darken-DoG-(Fast)-Gaussian-X
122//!HOOK MAIN
123//!BIND HOOKED
124//!BIND LINEKERNEL
125//!SAVE LINEKERNEL
126//!WIDTH HOOKED.w 2 /
127//!HEIGHT HOOKED.h 2 /
128//!COMPONENTS 1
130#define SPATIAL_SIGMA (0.5 * float(HOOKED_size.y) / 1080.0) //Spatial window size, must be a positive real number.
132#define KERNELSIZE (max(int(ceil(SPATIAL_SIGMA * 2.0)), 1) * 2 + 1) //Kernel size, must be an positive odd integer.
133#define KERNELHALFSIZE (int(KERNELSIZE/2)) //Half of the kernel size without remainder. Must be equal to trunc(KERNELSIZE/2).
134#define KERNELLEN (KERNELSIZE * KERNELSIZE) //Total area of kernel. Must be equal to KERNELSIZE * KERNELSIZE.
136float gaussian(float x, float s, float m) {
137 float scaled = (x - m) / s;
138 return exp(-0.5 * scaled * scaled);
139}
141float comp_gaussian_x() {
143 float g = 0.0;
144 float gn = 0.0;
145
146 for (int i=0; i<KERNELSIZE; i++) {
147 float di = float(i - KERNELHALFSIZE);
148 float gf = gaussian(di, SPATIAL_SIGMA, 0.0);
149
150 g = g + LINEKERNEL_texOff(vec2(di, 0.0)).x * gf;
151 gn = gn + gf;
152
153 }
154
155 return g / gn;
156}
158vec4 hook() {
159 return vec4(comp_gaussian_x(), 0.0, 0.0, 0.0);
160}
162//!DESC Anime4K-v3.2-Darken-DoG-(Fast)-Gaussian-Y
163//!HOOK MAIN
164//!BIND HOOKED
165//!BIND LINEKERNEL
166//!SAVE LINEKERNEL
167//!WIDTH HOOKED.w 2 /
168//!HEIGHT HOOKED.h 2 /
169//!COMPONENTS 1
171#define SPATIAL_SIGMA (0.5 * float(HOOKED_size.y) / 1080.0) //Spatial window size, must be a positive real number.
173#define KERNELSIZE (max(int(ceil(SPATIAL_SIGMA * 2.0)), 1) * 2 + 1) //Kernel size, must be an positive odd integer.
174#define KERNELHALFSIZE (int(KERNELSIZE/2)) //Half of the kernel size without remainder. Must be equal to trunc(KERNELSIZE/2).
175#define KERNELLEN (KERNELSIZE * KERNELSIZE) //Total area of kernel. Must be equal to KERNELSIZE * KERNELSIZE.
177float gaussian(float x, float s, float m) {
178 float scaled = (x - m) / s;
179 return exp(-0.5 * scaled * scaled);
180}
182float comp_gaussian_y() {
184 float g = 0.0;
185 float gn = 0.0;
186
187 for (int i=0; i<KERNELSIZE; i++) {
188 float di = float(i - KERNELHALFSIZE);
189 float gf = gaussian(di, SPATIAL_SIGMA, 0.0);
190
191 g = g + LINEKERNEL_texOff(vec2(0.0, di)).x * gf;
192 gn = gn + gf;
193
194 }
195
196 return g / gn;
197}
199vec4 hook() {
200 return vec4(comp_gaussian_y(), 0.0, 0.0, 0.0);
201}
204//!DESC Anime4K-v3.2-Darken-DoG-(Fast)-Upsample
205//!HOOK MAIN
206//!BIND HOOKED
207//!BIND LINEKERNEL
209#define STRENGTH 1.5 //Line darken proportional strength, higher is darker.
211vec4 hook() {
212 //This trick is only possible if the inverse Y->RGB matrix has 1 for every row... (which is the case for BT.709)
213 //Otherwise we would need to convert RGB to YUV, modify Y then convert back to RGB.
214 return HOOKED_tex(HOOKED_pos) + (LINEKERNEL_tex(HOOKED_pos).x * STRENGTH);
215}

mpv/shaders/Anime4K_Darken_HQ.glsl

Modified

+198 / −198 text lines

1// MIT License
2
3// Copyright (c) 2019-2021 bloc97
4// All rights reserved.
5
6// Permission is hereby granted, free of charge, to any person obtaining a copy
7// of this software and associated documentation files (the "Software"), to deal
8// in the Software without restriction, including without limitation the rights
9// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10// copies of the Software, and to permit persons to whom the Software is
11// furnished to do so, subject to the following conditions:
12
13// The above copyright notice and this permission notice shall be included in all
14// copies or substantial portions of the Software.
15
16// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22// SOFTWARE.
23
24//!DESC Anime4K-v3.2-Darken-DoG-(HQ)-Luma
25//!HOOK MAIN
26//!BIND HOOKED
27//!SAVE LINELUMA
28//!COMPONENTS 1
29
30float get_luma(vec4 rgba) {
31 return dot(vec4(0.299, 0.587, 0.114, 0.0), rgba);
32}
33
34vec4 hook() {
35 return vec4(get_luma(HOOKED_tex(HOOKED_pos)), 0.0, 0.0, 0.0);
36}
37
38//!DESC Anime4K-v3.2-Darken-DoG-(HQ)-Difference-X
39//!HOOK MAIN
40//!BIND HOOKED
41//!BIND LINELUMA
42//!SAVE LINEKERNEL
43//!COMPONENTS 1
44
45#define SPATIAL_SIGMA (1.0 * float(HOOKED_size.y) / 1080.0) //Spatial window size, must be a positive real number.
46
47#define KERNELSIZE (max(int(ceil(SPATIAL_SIGMA * 2.0)), 1) * 2 + 1) //Kernel size, must be an positive odd integer.
48#define KERNELHALFSIZE (int(KERNELSIZE/2)) //Half of the kernel size without remainder. Must be equal to trunc(KERNELSIZE/2).
49#define KERNELLEN (KERNELSIZE * KERNELSIZE) //Total area of kernel. Must be equal to KERNELSIZE * KERNELSIZE.
50
51float gaussian(float x, float s, float m) {
52 float scaled = (x - m) / s;
53 return exp(-0.5 * scaled * scaled);
54}
55
56float comp_gaussian_x() {
57
58 float g = 0.0;
59 float gn = 0.0;
60
61 for (int i=0; i<KERNELSIZE; i++) {
62 float di = float(i - KERNELHALFSIZE);
63 float gf = gaussian(di, SPATIAL_SIGMA, 0.0);
64
65 g = g + LINELUMA_texOff(vec2(di, 0.0)).x * gf;
66 gn = gn + gf;
67
68 }
69
70 return g / gn;
71}
72
73vec4 hook() {
74 return vec4(comp_gaussian_x(), 0.0, 0.0, 0.0);
75}
76
77//!DESC Anime4K-v3.2-Darken-DoG-(HQ)-Difference-Y
78//!HOOK MAIN
79//!BIND HOOKED
80//!BIND LINELUMA
81//!BIND LINEKERNEL
82//!SAVE LINEKERNEL
83//!COMPONENTS 1
84
85#define SPATIAL_SIGMA (1.0 * float(HOOKED_size.y) / 1080.0) //Spatial window size, must be a positive real number.
86
87#define KERNELSIZE (max(int(ceil(SPATIAL_SIGMA * 2.0)), 1) * 2 + 1) //Kernel size, must be an positive odd integer.
88#define KERNELHALFSIZE (int(KERNELSIZE/2)) //Half of the kernel size without remainder. Must be equal to trunc(KERNELSIZE/2).
89#define KERNELLEN (KERNELSIZE * KERNELSIZE) //Total area of kernel. Must be equal to KERNELSIZE * KERNELSIZE.
90
91float gaussian(float x, float s, float m) {
92 float scaled = (x - m) / s;
93 return exp(-0.5 * scaled * scaled);
94}
95
96float comp_gaussian_y() {
97
98 float g = 0.0;
99 float gn = 0.0;
100
101 for (int i=0; i<KERNELSIZE; i++) {
102 float di = float(i - KERNELHALFSIZE);
103 float gf = gaussian(di, SPATIAL_SIGMA, 0.0);
104
105 g = g + LINEKERNEL_texOff(vec2(0.0, di)).x * gf;
106 gn = gn + gf;
107
108 }
109
110 return g / gn;
111}
112
113vec4 hook() {
114 return vec4(min(LINELUMA_tex(HOOKED_pos).x - comp_gaussian_y(), 0.0), 0.0, 0.0, 0.0);
115}
116
117//!DESC Anime4K-v3.2-Darken-DoG-(HQ)-Gaussian-X
118//!HOOK MAIN
119//!BIND HOOKED
120//!BIND LINEKERNEL
121//!SAVE LINEKERNEL
122//!COMPONENTS 1
123
124#define SPATIAL_SIGMA (1.0 * float(HOOKED_size.y) / 1080.0) //Spatial window size, must be a positive real number.
125
126#define KERNELSIZE (max(int(ceil(SPATIAL_SIGMA * 2.0)), 1) * 2 + 1) //Kernel size, must be an positive odd integer.
127#define KERNELHALFSIZE (int(KERNELSIZE/2)) //Half of the kernel size without remainder. Must be equal to trunc(KERNELSIZE/2).
128#define KERNELLEN (KERNELSIZE * KERNELSIZE) //Total area of kernel. Must be equal to KERNELSIZE * KERNELSIZE.
129
130float gaussian(float x, float s, float m) {
131 float scaled = (x - m) / s;
132 return exp(-0.5 * scaled * scaled);
133}
134
135float comp_gaussian_x() {
136
137 float g = 0.0;
138 float gn = 0.0;
139
140 for (int i=0; i<KERNELSIZE; i++) {
141 float di = float(i - KERNELHALFSIZE);
142 float gf = gaussian(di, SPATIAL_SIGMA, 0.0);
143
144 g = g + LINEKERNEL_texOff(vec2(di, 0.0)).x * gf;
145 gn = gn + gf;
146
147 }
148
149 return g / gn;
150}
151
152vec4 hook() {
153 return vec4(comp_gaussian_x(), 0.0, 0.0, 0.0);
154}
155
156//!DESC Anime4K-v3.2-Darken-DoG-(HQ)-Gaussian-Y
157//!HOOK MAIN
158//!BIND HOOKED
159//!BIND LINEKERNEL
160
161#define SPATIAL_SIGMA (1.0 * float(HOOKED_size.y) / 1080.0) //Spatial window size, must be a positive real number.
162
163#define KERNELSIZE (max(int(ceil(SPATIAL_SIGMA * 2.0)), 1) * 2 + 1) //Kernel size, must be an positive odd integer.
164#define KERNELHALFSIZE (int(KERNELSIZE/2)) //Half of the kernel size without remainder. Must be equal to trunc(KERNELSIZE/2).
165#define KERNELLEN (KERNELSIZE * KERNELSIZE) //Total area of kernel. Must be equal to KERNELSIZE * KERNELSIZE.
166
167float gaussian(float x, float s, float m) {
168 float scaled = (x - m) / s;
169 return exp(-0.5 * scaled * scaled);
170}
171
172float comp_gaussian_y() {
173
174 float g = 0.0;
175 float gn = 0.0;
176
177 for (int i=0; i<KERNELSIZE; i++) {
178 float di = float(i - KERNELHALFSIZE);
179 float gf = gaussian(di, SPATIAL_SIGMA, 0.0);
180
181 g = g + LINEKERNEL_texOff(vec2(0.0, di)).x * gf;
182 gn = gn + gf;
183
184 }
185
186 return g / gn;
187}
188
189
190
191#define STRENGTH 1.5 //Line darken proportional strength, higher is darker.
192
193vec4 hook() {
194 //This trick is only possible if the inverse Y->RGB matrix has 1 for every row... (which is the case for BT.709)
195 //Otherwise we would need to convert RGB to YUV, modify Y then convert back to RGB.
196 return HOOKED_tex(HOOKED_pos) + (comp_gaussian_y() * STRENGTH);
197}
198
1// MIT License
2
3// Copyright (c) 2019-2021 bloc97
4// All rights reserved.
5
6// Permission is hereby granted, free of charge, to any person obtaining a copy
7// of this software and associated documentation files (the "Software"), to deal
8// in the Software without restriction, including without limitation the rights
9// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10// copies of the Software, and to permit persons to whom the Software is
11// furnished to do so, subject to the following conditions:
13// The above copyright notice and this permission notice shall be included in all
14// copies or substantial portions of the Software.
16// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22// SOFTWARE.
24//!DESC Anime4K-v3.2-Darken-DoG-(HQ)-Luma
25//!HOOK MAIN
26//!BIND HOOKED
27//!SAVE LINELUMA
28//!COMPONENTS 1
30float get_luma(vec4 rgba) {
31 return dot(vec4(0.299, 0.587, 0.114, 0.0), rgba);
32}
34vec4 hook() {
35 return vec4(get_luma(HOOKED_tex(HOOKED_pos)), 0.0, 0.0, 0.0);
36}
38//!DESC Anime4K-v3.2-Darken-DoG-(HQ)-Difference-X
39//!HOOK MAIN
40//!BIND HOOKED
41//!BIND LINELUMA
42//!SAVE LINEKERNEL
43//!COMPONENTS 1
45#define SPATIAL_SIGMA (1.0 * float(HOOKED_size.y) / 1080.0) //Spatial window size, must be a positive real number.
47#define KERNELSIZE (max(int(ceil(SPATIAL_SIGMA * 2.0)), 1) * 2 + 1) //Kernel size, must be an positive odd integer.
48#define KERNELHALFSIZE (int(KERNELSIZE/2)) //Half of the kernel size without remainder. Must be equal to trunc(KERNELSIZE/2).
49#define KERNELLEN (KERNELSIZE * KERNELSIZE) //Total area of kernel. Must be equal to KERNELSIZE * KERNELSIZE.
51float gaussian(float x, float s, float m) {
52 float scaled = (x - m) / s;
53 return exp(-0.5 * scaled * scaled);
54}
56float comp_gaussian_x() {
58 float g = 0.0;
59 float gn = 0.0;
60
61 for (int i=0; i<KERNELSIZE; i++) {
62 float di = float(i - KERNELHALFSIZE);
63 float gf = gaussian(di, SPATIAL_SIGMA, 0.0);
64
65 g = g + LINELUMA_texOff(vec2(di, 0.0)).x * gf;
66 gn = gn + gf;
67
68 }
69
70 return g / gn;
71}
73vec4 hook() {
74 return vec4(comp_gaussian_x(), 0.0, 0.0, 0.0);
75}
77//!DESC Anime4K-v3.2-Darken-DoG-(HQ)-Difference-Y
78//!HOOK MAIN
79//!BIND HOOKED
80//!BIND LINELUMA
81//!BIND LINEKERNEL
82//!SAVE LINEKERNEL
83//!COMPONENTS 1
85#define SPATIAL_SIGMA (1.0 * float(HOOKED_size.y) / 1080.0) //Spatial window size, must be a positive real number.
87#define KERNELSIZE (max(int(ceil(SPATIAL_SIGMA * 2.0)), 1) * 2 + 1) //Kernel size, must be an positive odd integer.
88#define KERNELHALFSIZE (int(KERNELSIZE/2)) //Half of the kernel size without remainder. Must be equal to trunc(KERNELSIZE/2).
89#define KERNELLEN (KERNELSIZE * KERNELSIZE) //Total area of kernel. Must be equal to KERNELSIZE * KERNELSIZE.
91float gaussian(float x, float s, float m) {
92 float scaled = (x - m) / s;
93 return exp(-0.5 * scaled * scaled);
94}
96float comp_gaussian_y() {
98 float g = 0.0;
99 float gn = 0.0;
100
101 for (int i=0; i<KERNELSIZE; i++) {
102 float di = float(i - KERNELHALFSIZE);
103 float gf = gaussian(di, SPATIAL_SIGMA, 0.0);
104
105 g = g + LINEKERNEL_texOff(vec2(0.0, di)).x * gf;
106 gn = gn + gf;
107
108 }
109
110 return g / gn;
111}
113vec4 hook() {
114 return vec4(min(LINELUMA_tex(HOOKED_pos).x - comp_gaussian_y(), 0.0), 0.0, 0.0, 0.0);
115}
117//!DESC Anime4K-v3.2-Darken-DoG-(HQ)-Gaussian-X
118//!HOOK MAIN
119//!BIND HOOKED
120//!BIND LINEKERNEL
121//!SAVE LINEKERNEL
122//!COMPONENTS 1
124#define SPATIAL_SIGMA (1.0 * float(HOOKED_size.y) / 1080.0) //Spatial window size, must be a positive real number.
126#define KERNELSIZE (max(int(ceil(SPATIAL_SIGMA * 2.0)), 1) * 2 + 1) //Kernel size, must be an positive odd integer.
127#define KERNELHALFSIZE (int(KERNELSIZE/2)) //Half of the kernel size without remainder. Must be equal to trunc(KERNELSIZE/2).
128#define KERNELLEN (KERNELSIZE * KERNELSIZE) //Total area of kernel. Must be equal to KERNELSIZE * KERNELSIZE.
130float gaussian(float x, float s, float m) {
131 float scaled = (x - m) / s;
132 return exp(-0.5 * scaled * scaled);
133}
135float comp_gaussian_x() {
137 float g = 0.0;
138 float gn = 0.0;
139
140 for (int i=0; i<KERNELSIZE; i++) {
141 float di = float(i - KERNELHALFSIZE);
142 float gf = gaussian(di, SPATIAL_SIGMA, 0.0);
143
144 g = g + LINEKERNEL_texOff(vec2(di, 0.0)).x * gf;
145 gn = gn + gf;
146
147 }
148
149 return g / gn;
150}
152vec4 hook() {
153 return vec4(comp_gaussian_x(), 0.0, 0.0, 0.0);
154}
156//!DESC Anime4K-v3.2-Darken-DoG-(HQ)-Gaussian-Y
157//!HOOK MAIN
158//!BIND HOOKED
159//!BIND LINEKERNEL
161#define SPATIAL_SIGMA (1.0 * float(HOOKED_size.y) / 1080.0) //Spatial window size, must be a positive real number.
163#define KERNELSIZE (max(int(ceil(SPATIAL_SIGMA * 2.0)), 1) * 2 + 1) //Kernel size, must be an positive odd integer.
164#define KERNELHALFSIZE (int(KERNELSIZE/2)) //Half of the kernel size without remainder. Must be equal to trunc(KERNELSIZE/2).
165#define KERNELLEN (KERNELSIZE * KERNELSIZE) //Total area of kernel. Must be equal to KERNELSIZE * KERNELSIZE.
167float gaussian(float x, float s, float m) {
168 float scaled = (x - m) / s;
169 return exp(-0.5 * scaled * scaled);
170}
172float comp_gaussian_y() {
174 float g = 0.0;
175 float gn = 0.0;
176
177 for (int i=0; i<KERNELSIZE; i++) {
178 float di = float(i - KERNELHALFSIZE);
179 float gf = gaussian(di, SPATIAL_SIGMA, 0.0);
180
181 g = g + LINEKERNEL_texOff(vec2(0.0, di)).x * gf;
182 gn = gn + gf;
183
184 }
185
186 return g / gn;
187}
191#define STRENGTH 1.5 //Line darken proportional strength, higher is darker.
193vec4 hook() {
194 //This trick is only possible if the inverse Y->RGB matrix has 1 for every row... (which is the case for BT.709)
195 //Otherwise we would need to convert RGB to YUV, modify Y then convert back to RGB.
196 return HOOKED_tex(HOOKED_pos) + (comp_gaussian_y() * STRENGTH);
197}

mpv/shaders/Anime4K_Darken_VeryFast.glsl

Modified

+218 / −218 text lines

1// MIT License
2
3// Copyright (c) 2019-2021 bloc97
4// All rights reserved.
5
6// Permission is hereby granted, free of charge, to any person obtaining a copy
7// of this software and associated documentation files (the "Software"), to deal
8// in the Software without restriction, including without limitation the rights
9// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10// copies of the Software, and to permit persons to whom the Software is
11// furnished to do so, subject to the following conditions:
12
13// The above copyright notice and this permission notice shall be included in all
14// copies or substantial portions of the Software.
15
16// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22// SOFTWARE.
23
24//!DESC Anime4K-v3.2-Darken-DoG-(HQ)-Luma
25//!HOOK MAIN
26//!BIND HOOKED
27//!SAVE LINELUMA
28//!WIDTH HOOKED.w 2 /
29//!HEIGHT HOOKED.h 2 /
30//!COMPONENTS 1
31
32float get_luma(vec4 rgba) {
33 return dot(vec4(0.299, 0.587, 0.114, 0.0), rgba);
34}
35
36vec4 hook() {
37 return vec4(get_luma(HOOKED_tex(HOOKED_pos)), 0.0, 0.0, 0.0);
38}
39
40//!DESC Anime4K-v3.2-Darken-DoG-(VeryFast)-Gaussian-X
41//!HOOK MAIN
42//!BIND HOOKED
43//!BIND LINELUMA
44//!SAVE LINEKERNEL
45//!WIDTH HOOKED.w 4 /
46//!HEIGHT HOOKED.h 4 /
47//!COMPONENTS 1
48
49#define SPATIAL_SIGMA (0.5 * float(HOOKED_size.y) / 1080.0) //Spatial window size, must be a positive real number.
50
51#define KERNELSIZE (max(int(ceil(SPATIAL_SIGMA * 2.0)), 1) * 2 + 1) //Kernel size, must be an positive odd integer.
52#define KERNELHALFSIZE (int(KERNELSIZE/2)) //Half of the kernel size without remainder. Must be equal to trunc(KERNELSIZE/2).
53#define KERNELLEN (KERNELSIZE * KERNELSIZE) //Total area of kernel. Must be equal to KERNELSIZE * KERNELSIZE.
54
55float gaussian(float x, float s, float m) {
56 float scaled = (x - m) / s;
57 return exp(-0.5 * scaled * scaled);
58}
59
60float comp_gaussian_x() {
61
62 float g = 0.0;
63 float gn = 0.0;
64
65 for (int i=0; i<KERNELSIZE; i++) {
66 float di = float(i - KERNELHALFSIZE);
67 float gf = gaussian(di, SPATIAL_SIGMA, 0.0);
68
69 g = g + LINELUMA_texOff(vec2(di, 0.0)).x * gf;
70 gn = gn + gf;
71
72 }
73
74 return g / gn;
75}
76
77vec4 hook() {
78 return vec4(comp_gaussian_x(), 0.0, 0.0, 0.0);
79}
80
81//!DESC Anime4K-v3.2-Darken-DoG-(VeryFast)-Gaussian-Y
82//!HOOK MAIN
83//!BIND HOOKED
84//!BIND LINELUMA
85//!BIND LINEKERNEL
86//!SAVE LINEKERNEL
87//!WIDTH HOOKED.w 4 /
88//!HEIGHT HOOKED.h 4 /
89//!COMPONENTS 1
90
91#define SPATIAL_SIGMA (0.25 * float(HOOKED_size.y) / 1080.0) //Spatial window size, must be a positive real number.
92
93#define KERNELSIZE (max(int(ceil(SPATIAL_SIGMA * 2.0)), 1) * 2 + 1) //Kernel size, must be an positive odd integer.
94#define KERNELHALFSIZE (int(KERNELSIZE/2)) //Half of the kernel size without remainder. Must be equal to trunc(KERNELSIZE/2).
95#define KERNELLEN (KERNELSIZE * KERNELSIZE) //Total area of kernel. Must be equal to KERNELSIZE * KERNELSIZE.
96
97float gaussian(float x, float s, float m) {
98 float scaled = (x - m) / s;
99 return exp(-0.5 * scaled * scaled);
100}
101
102float comp_gaussian_y() {
103
104 float g = 0.0;
105 float gn = 0.0;
106
107 for (int i=0; i<KERNELSIZE; i++) {
108 float di = float(i - KERNELHALFSIZE);
109 float gf = gaussian(di, SPATIAL_SIGMA, 0.0);
110
111 g = g + LINEKERNEL_texOff(vec2(0.0, di)).x * gf;
112 gn = gn + gf;
113
114 }
115
116 return g / gn;
117}
118
119vec4 hook() {
120 return vec4(min(LINELUMA_tex(HOOKED_pos).x - comp_gaussian_y(), 0.0), 0.0, 0.0, 0.0);
121}
122
123//!DESC Anime4K-v3.2-Darken-DoG-(VeryFast)-Gaussian-X
124//!HOOK MAIN
125//!BIND HOOKED
126//!BIND LINEKERNEL
127//!SAVE LINEKERNEL
128//!WIDTH HOOKED.w 4 /
129//!HEIGHT HOOKED.h 4 /
130//!COMPONENTS 1
131
132#define SPATIAL_SIGMA (0.25 * float(HOOKED_size.y) / 1080.0) //Spatial window size, must be a positive real number.
133
134#define KERNELSIZE (max(int(ceil(SPATIAL_SIGMA * 2.0)), 1) * 2 + 1) //Kernel size, must be an positive odd integer.
135#define KERNELHALFSIZE (int(KERNELSIZE/2)) //Half of the kernel size without remainder. Must be equal to trunc(KERNELSIZE/2).
136#define KERNELLEN (KERNELSIZE * KERNELSIZE) //Total area of kernel. Must be equal to KERNELSIZE * KERNELSIZE.
137
138float gaussian(float x, float s, float m) {
139 float scaled = (x - m) / s;
140 return exp(-0.5 * scaled * scaled);
141}
142
143float comp_gaussian_x() {
144
145 float g = 0.0;
146 float gn = 0.0;
147
148 for (int i=0; i<KERNELSIZE; i++) {
149 float di = float(i - KERNELHALFSIZE);
150 float gf = gaussian(di, SPATIAL_SIGMA, 0.0);
151
152 g = g + LINEKERNEL_texOff(vec2(di, 0.0)).x * gf;
153 gn = gn + gf;
154
155 }
156
157 return g / gn;
158}
159
160vec4 hook() {
161 return vec4(comp_gaussian_x(), 0.0, 0.0, 0.0);
162}
163
164//!DESC Anime4K-v3.2-Darken-DoG-(VeryFast)-Gaussian-Y
165//!HOOK MAIN
166//!BIND HOOKED
167//!BIND LINEKERNEL
168//!SAVE LINEKERNEL
169//!WIDTH HOOKED.w 4 /
170//!HEIGHT HOOKED.h 4 /
171//!COMPONENTS 1
172
173#define SPATIAL_SIGMA (0.25 * float(HOOKED_size.y) / 1080.0) //Spatial window size, must be a positive real number.
174
175#define KERNELSIZE (max(int(ceil(SPATIAL_SIGMA * 2.0)), 1) * 2 + 1) //Kernel size, must be an positive odd integer.
176#define KERNELHALFSIZE (int(KERNELSIZE/2)) //Half of the kernel size without remainder. Must be equal to trunc(KERNELSIZE/2).
177#define KERNELLEN (KERNELSIZE * KERNELSIZE) //Total area of kernel. Must be equal to KERNELSIZE * KERNELSIZE.
178
179float gaussian(float x, float s, float m) {
180 float scaled = (x - m) / s;
181 return exp(-0.5 * scaled * scaled);
182}
183
184float comp_gaussian_y() {
185
186 float g = 0.0;
187 float gn = 0.0;
188
189 for (int i=0; i<KERNELSIZE; i++) {
190 float di = float(i - KERNELHALFSIZE);
191 float gf = gaussian(di, SPATIAL_SIGMA, 0.0);
192
193 g = g + LINEKERNEL_texOff(vec2(0.0, di)).x * gf;
194 gn = gn + gf;
195
196 }
197
198 return g / gn;
199}
200
201vec4 hook() {
202 return vec4(comp_gaussian_y(), 0.0, 0.0, 0.0);
203}
204
205
206//!DESC Anime4K-v3.2-Darken-DoG-(VeryFast)-Upsample
207//!HOOK MAIN
208//!BIND HOOKED
209//!BIND LINEKERNEL
210
211#define STRENGTH 1.5 //Line darken proportional strength, higher is darker.
212
213vec4 hook() {
214 //This trick is only possible if the inverse Y->RGB matrix has 1 for every row... (which is the case for BT.709)
215 //Otherwise we would need to convert RGB to YUV, modify Y then convert back to RGB.
216 return HOOKED_tex(HOOKED_pos) + (LINEKERNEL_tex(HOOKED_pos).x * STRENGTH);
217}
218
1// MIT License
2
3// Copyright (c) 2019-2021 bloc97
4// All rights reserved.
5
6// Permission is hereby granted, free of charge, to any person obtaining a copy
7// of this software and associated documentation files (the "Software"), to deal
8// in the Software without restriction, including without limitation the rights
9// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10// copies of the Software, and to permit persons to whom the Software is
11// furnished to do so, subject to the following conditions:
13// The above copyright notice and this permission notice shall be included in all
14// copies or substantial portions of the Software.
16// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22// SOFTWARE.
24//!DESC Anime4K-v3.2-Darken-DoG-(HQ)-Luma
25//!HOOK MAIN
26//!BIND HOOKED
27//!SAVE LINELUMA
28//!WIDTH HOOKED.w 2 /
29//!HEIGHT HOOKED.h 2 /
30//!COMPONENTS 1
32float get_luma(vec4 rgba) {
33 return dot(vec4(0.299, 0.587, 0.114, 0.0), rgba);
34}
36vec4 hook() {
37 return vec4(get_luma(HOOKED_tex(HOOKED_pos)), 0.0, 0.0, 0.0);
38}
40//!DESC Anime4K-v3.2-Darken-DoG-(VeryFast)-Gaussian-X
41//!HOOK MAIN
42//!BIND HOOKED
43//!BIND LINELUMA
44//!SAVE LINEKERNEL
45//!WIDTH HOOKED.w 4 /
46//!HEIGHT HOOKED.h 4 /
47//!COMPONENTS 1
49#define SPATIAL_SIGMA (0.5 * float(HOOKED_size.y) / 1080.0) //Spatial window size, must be a positive real number.
51#define KERNELSIZE (max(int(ceil(SPATIAL_SIGMA * 2.0)), 1) * 2 + 1) //Kernel size, must be an positive odd integer.
52#define KERNELHALFSIZE (int(KERNELSIZE/2)) //Half of the kernel size without remainder. Must be equal to trunc(KERNELSIZE/2).
53#define KERNELLEN (KERNELSIZE * KERNELSIZE) //Total area of kernel. Must be equal to KERNELSIZE * KERNELSIZE.
55float gaussian(float x, float s, float m) {
56 float scaled = (x - m) / s;
57 return exp(-0.5 * scaled * scaled);
58}
60float comp_gaussian_x() {
62 float g = 0.0;
63 float gn = 0.0;
64
65 for (int i=0; i<KERNELSIZE; i++) {
66 float di = float(i - KERNELHALFSIZE);
67 float gf = gaussian(di, SPATIAL_SIGMA, 0.0);
68
69 g = g + LINELUMA_texOff(vec2(di, 0.0)).x * gf;
70 gn = gn + gf;
71
72 }
73
74 return g / gn;
75}
77vec4 hook() {
78 return vec4(comp_gaussian_x(), 0.0, 0.0, 0.0);
79}
81//!DESC Anime4K-v3.2-Darken-DoG-(VeryFast)-Gaussian-Y
82//!HOOK MAIN
83//!BIND HOOKED
84//!BIND LINELUMA
85//!BIND LINEKERNEL
86//!SAVE LINEKERNEL
87//!WIDTH HOOKED.w 4 /
88//!HEIGHT HOOKED.h 4 /
89//!COMPONENTS 1
91#define SPATIAL_SIGMA (0.25 * float(HOOKED_size.y) / 1080.0) //Spatial window size, must be a positive real number.
93#define KERNELSIZE (max(int(ceil(SPATIAL_SIGMA * 2.0)), 1) * 2 + 1) //Kernel size, must be an positive odd integer.
94#define KERNELHALFSIZE (int(KERNELSIZE/2)) //Half of the kernel size without remainder. Must be equal to trunc(KERNELSIZE/2).
95#define KERNELLEN (KERNELSIZE * KERNELSIZE) //Total area of kernel. Must be equal to KERNELSIZE * KERNELSIZE.
97float gaussian(float x, float s, float m) {
98 float scaled = (x - m) / s;
99 return exp(-0.5 * scaled * scaled);
100}
102float comp_gaussian_y() {
104 float g = 0.0;
105 float gn = 0.0;
106
107 for (int i=0; i<KERNELSIZE; i++) {
108 float di = float(i - KERNELHALFSIZE);
109 float gf = gaussian(di, SPATIAL_SIGMA, 0.0);
110
111 g = g + LINEKERNEL_texOff(vec2(0.0, di)).x * gf;
112 gn = gn + gf;
113
114 }
115
116 return g / gn;
117}
119vec4 hook() {
120 return vec4(min(LINELUMA_tex(HOOKED_pos).x - comp_gaussian_y(), 0.0), 0.0, 0.0, 0.0);
121}
123//!DESC Anime4K-v3.2-Darken-DoG-(VeryFast)-Gaussian-X
124//!HOOK MAIN
125//!BIND HOOKED
126//!BIND LINEKERNEL
127//!SAVE LINEKERNEL
128//!WIDTH HOOKED.w 4 /
129//!HEIGHT HOOKED.h 4 /
130//!COMPONENTS 1
132#define SPATIAL_SIGMA (0.25 * float(HOOKED_size.y) / 1080.0) //Spatial window size, must be a positive real number.
134#define KERNELSIZE (max(int(ceil(SPATIAL_SIGMA * 2.0)), 1) * 2 + 1) //Kernel size, must be an positive odd integer.
135#define KERNELHALFSIZE (int(KERNELSIZE/2)) //Half of the kernel size without remainder. Must be equal to trunc(KERNELSIZE/2).
136#define KERNELLEN (KERNELSIZE * KERNELSIZE) //Total area of kernel. Must be equal to KERNELSIZE * KERNELSIZE.
138float gaussian(float x, float s, float m) {
139 float scaled = (x - m) / s;
140 return exp(-0.5 * scaled * scaled);
141}
143float comp_gaussian_x() {
145 float g = 0.0;
146 float gn = 0.0;
147
148 for (int i=0; i<KERNELSIZE; i++) {
149 float di = float(i - KERNELHALFSIZE);
150 float gf = gaussian(di, SPATIAL_SIGMA, 0.0);
151
152 g = g + LINEKERNEL_texOff(vec2(di, 0.0)).x * gf;
153 gn = gn + gf;
154
155 }
156
157 return g / gn;
158}
160vec4 hook() {
161 return vec4(comp_gaussian_x(), 0.0, 0.0, 0.0);
162}
164//!DESC Anime4K-v3.2-Darken-DoG-(VeryFast)-Gaussian-Y
165//!HOOK MAIN
166//!BIND HOOKED
167//!BIND LINEKERNEL
168//!SAVE LINEKERNEL
169//!WIDTH HOOKED.w 4 /
170//!HEIGHT HOOKED.h 4 /
171//!COMPONENTS 1
173#define SPATIAL_SIGMA (0.25 * float(HOOKED_size.y) / 1080.0) //Spatial window size, must be a positive real number.
175#define KERNELSIZE (max(int(ceil(SPATIAL_SIGMA * 2.0)), 1) * 2 + 1) //Kernel size, must be an positive odd integer.
176#define KERNELHALFSIZE (int(KERNELSIZE/2)) //Half of the kernel size without remainder. Must be equal to trunc(KERNELSIZE/2).
177#define KERNELLEN (KERNELSIZE * KERNELSIZE) //Total area of kernel. Must be equal to KERNELSIZE * KERNELSIZE.
179float gaussian(float x, float s, float m) {
180 float scaled = (x - m) / s;
181 return exp(-0.5 * scaled * scaled);
182}
184float comp_gaussian_y() {
186 float g = 0.0;
187 float gn = 0.0;
188
189 for (int i=0; i<KERNELSIZE; i++) {
190 float di = float(i - KERNELHALFSIZE);
191 float gf = gaussian(di, SPATIAL_SIGMA, 0.0);
192
193 g = g + LINEKERNEL_texOff(vec2(0.0, di)).x * gf;
194 gn = gn + gf;
195
196 }
197
198 return g / gn;
199}
201vec4 hook() {
202 return vec4(comp_gaussian_y(), 0.0, 0.0, 0.0);
203}
206//!DESC Anime4K-v3.2-Darken-DoG-(VeryFast)-Upsample
207//!HOOK MAIN
208//!BIND HOOKED
209//!BIND LINEKERNEL
211#define STRENGTH 1.5 //Line darken proportional strength, higher is darker.
213vec4 hook() {
214 //This trick is only possible if the inverse Y->RGB matrix has 1 for every row... (which is the case for BT.709)
215 //Otherwise we would need to convert RGB to YUV, modify Y then convert back to RGB.
216 return HOOKED_tex(HOOKED_pos) + (LINEKERNEL_tex(HOOKED_pos).x * STRENGTH);
217}

mpv/shaders/Anime4K_Deblur_DoG.glsl

Modified

+153 / −153 text lines

1// MIT License
2
3// Copyright (c) 2019-2021 bloc97
4// All rights reserved.
5
6// Permission is hereby granted, free of charge, to any person obtaining a copy
7// of this software and associated documentation files (the "Software"), to deal
8// in the Software without restriction, including without limitation the rights
9// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10// copies of the Software, and to permit persons to whom the Software is
11// furnished to do so, subject to the following conditions:
12
13// The above copyright notice and this permission notice shall be included in all
14// copies or substantial portions of the Software.
15
16// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22// SOFTWARE.
23
24//!DESC Anime4K-v3.2-Deblur-DoG-(HQ)-Luma
25//!HOOK MAIN
26//!BIND HOOKED
27//!SAVE LINELUMA
28//!COMPONENTS 1
29
30float get_luma(vec4 rgba) {
31 return dot(vec4(0.299, 0.587, 0.114, 0.0), rgba);
32}
33
34vec4 hook() {
35 return vec4(get_luma(HOOKED_tex(HOOKED_pos)), 0.0, 0.0, 0.0);
36}
37
38//!DESC Anime4K-v3.2-Deblur-DoG-Kernel-X
39//!HOOK MAIN
40//!BIND HOOKED
41//!BIND LINELUMA
42//!SAVE MMKERNEL
43//!COMPONENTS 3
44
45#define L_tex LINELUMA_tex
46
47float max3v(float a, float b, float c) {
48 return max(max(a, b), c);
49}
50float min3v(float a, float b, float c) {
51 return min(min(a, b), c);
52}
53
54vec2 minmax3(vec2 pos, vec2 d) {
55 float a = L_tex(pos - d).x;
56 float b = L_tex(pos).x;
57 float c = L_tex(pos + d).x;
58
59 return vec2(min3v(a, b, c), max3v(a, b, c));
60}
61
62float lumGaussian7(vec2 pos, vec2 d) {
63 float g = (L_tex(pos - (d + d)).x + L_tex(pos + (d + d)).x) * 0.06136;
64 g = g + (L_tex(pos - d).x + L_tex(pos + d).x) * 0.24477;
65 g = g + (L_tex(pos).x) * 0.38774;
66
67 return g;
68}
69
70
71vec4 hook() {
72 return vec4(lumGaussian7(HOOKED_pos, vec2(HOOKED_pt.x, 0.0)), minmax3(HOOKED_pos, vec2(HOOKED_pt.x, 0.0)), 0.0);
73}
74
75
76//!DESC Anime4K-v3.2-Deblur-DoG-Kernel-Y
77//!HOOK MAIN
78//!BIND HOOKED
79//!BIND MMKERNEL
80//!SAVE MMKERNEL
81//!COMPONENTS 3
82
83#define L_tex MMKERNEL_tex
84
85float max3v(float a, float b, float c) {
86 return max(max(a, b), c);
87}
88float min3v(float a, float b, float c) {
89 return min(min(a, b), c);
90}
91
92vec2 minmax3(vec2 pos, vec2 d) {
93 float a0 = L_tex(pos - d).y;
94 float b0 = L_tex(pos).y;
95 float c0 = L_tex(pos + d).y;
96
97 float a1 = L_tex(pos - d).z;
98 float b1 = L_tex(pos).z;
99 float c1 = L_tex(pos + d).z;
100
101 return vec2(min3v(a0, b0, c0), max3v(a1, b1, c1));
102}
103
104float lumGaussian7(vec2 pos, vec2 d) {
105 float g = (L_tex(pos - (d + d)).x + L_tex(pos + (d + d)).x) * 0.06136;
106 g = g + (L_tex(pos - d).x + L_tex(pos + d).x) * 0.24477;
107 g = g + (L_tex(pos).x) * 0.38774;
108
109 return g;
110}
111
112
113vec4 hook() {
114 return vec4(lumGaussian7(HOOKED_pos, vec2(0.0, HOOKED_pt.y)), minmax3(HOOKED_pos, vec2(0.0, HOOKED_pt.y)), 0.0);
115}
116
117//!DESC Anime4K-v3.2-Deblur-DoG-Apply
118//!HOOK MAIN
119//!BIND HOOKED
120//!BIND LINELUMA
121//!BIND MMKERNEL
122
123#define STRENGTH 0.6 //De-blur proportional strength, higher is sharper. However, it is better to tweak BLUR_CURVE instead to avoid ringing.
124#define BLUR_CURVE 0.6 //De-blur power curve, lower is sharper. Good values are between 0.3 - 1. Values greater than 1 softens the image;
125#define BLUR_THRESHOLD 0.1 //Value where curve kicks in, used to not de-blur already sharp edges. Only de-blur values that fall below this threshold.
126#define NOISE_THRESHOLD 0.001 //Value where curve stops, used to not sharpen noise. Only de-blur values that fall above this threshold.
127
128#define L_tex LINELUMA_tex
129
130vec4 hook() {
131 float c = (L_tex(HOOKED_pos).x - MMKERNEL_tex(HOOKED_pos).x) * STRENGTH;
132
133 float t_range = BLUR_THRESHOLD - NOISE_THRESHOLD;
134
135 float c_t = abs(c);
136 if (c_t > NOISE_THRESHOLD) {
137 c_t = (c_t - NOISE_THRESHOLD) / t_range;
138 c_t = pow(c_t, BLUR_CURVE);
139 c_t = c_t * t_range + NOISE_THRESHOLD;
140 c_t = c_t * sign(c);
141 } else {
142 c_t = c;
143 }
144
145 float cc = clamp(c_t + L_tex(HOOKED_pos).x, MMKERNEL_tex(HOOKED_pos).y, MMKERNEL_tex(HOOKED_pos).z) - L_tex(HOOKED_pos).x;
146
147 //This trick is only possible if the inverse Y->RGB matrix has 1 for every row... (which is the case for BT.709)
148 //Otherwise we would need to convert RGB to YUV, modify Y then convert back to RGB.
149 return HOOKED_tex(HOOKED_pos) + cc;
150}
151
152
153
1// MIT License
2
3// Copyright (c) 2019-2021 bloc97
4// All rights reserved.
5
6// Permission is hereby granted, free of charge, to any person obtaining a copy
7// of this software and associated documentation files (the "Software"), to deal
8// in the Software without restriction, including without limitation the rights
9// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10// copies of the Software, and to permit persons to whom the Software is
11// furnished to do so, subject to the following conditions:
13// The above copyright notice and this permission notice shall be included in all
14// copies or substantial portions of the Software.
16// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22// SOFTWARE.
24//!DESC Anime4K-v3.2-Deblur-DoG-(HQ)-Luma
25//!HOOK MAIN
26//!BIND HOOKED
27//!SAVE LINELUMA
28//!COMPONENTS 1
30float get_luma(vec4 rgba) {
31 return dot(vec4(0.299, 0.587, 0.114, 0.0), rgba);
32}
34vec4 hook() {
35 return vec4(get_luma(HOOKED_tex(HOOKED_pos)), 0.0, 0.0, 0.0);
36}
38//!DESC Anime4K-v3.2-Deblur-DoG-Kernel-X
39//!HOOK MAIN
40//!BIND HOOKED
41//!BIND LINELUMA
42//!SAVE MMKERNEL
43//!COMPONENTS 3
45#define L_tex LINELUMA_tex
47float max3v(float a, float b, float c) {
48 return max(max(a, b), c);
49}
50float min3v(float a, float b, float c) {
51 return min(min(a, b), c);
52}
54vec2 minmax3(vec2 pos, vec2 d) {
55 float a = L_tex(pos - d).x;
56 float b = L_tex(pos).x;
57 float c = L_tex(pos + d).x;
58
59 return vec2(min3v(a, b, c), max3v(a, b, c));
60}
62float lumGaussian7(vec2 pos, vec2 d) {
63 float g = (L_tex(pos - (d + d)).x + L_tex(pos + (d + d)).x) * 0.06136;
64 g = g + (L_tex(pos - d).x + L_tex(pos + d).x) * 0.24477;
65 g = g + (L_tex(pos).x) * 0.38774;
66
67 return g;
68}
71vec4 hook() {
72 return vec4(lumGaussian7(HOOKED_pos, vec2(HOOKED_pt.x, 0.0)), minmax3(HOOKED_pos, vec2(HOOKED_pt.x, 0.0)), 0.0);
73}
76//!DESC Anime4K-v3.2-Deblur-DoG-Kernel-Y
77//!HOOK MAIN
78//!BIND HOOKED
79//!BIND MMKERNEL
80//!SAVE MMKERNEL
81//!COMPONENTS 3
83#define L_tex MMKERNEL_tex
85float max3v(float a, float b, float c) {
86 return max(max(a, b), c);
87}
88float min3v(float a, float b, float c) {
89 return min(min(a, b), c);
90}
92vec2 minmax3(vec2 pos, vec2 d) {
93 float a0 = L_tex(pos - d).y;
94 float b0 = L_tex(pos).y;
95 float c0 = L_tex(pos + d).y;
96
97 float a1 = L_tex(pos - d).z;
98 float b1 = L_tex(pos).z;
99 float c1 = L_tex(pos + d).z;
100
101 return vec2(min3v(a0, b0, c0), max3v(a1, b1, c1));
102}
104float lumGaussian7(vec2 pos, vec2 d) {
105 float g = (L_tex(pos - (d + d)).x + L_tex(pos + (d + d)).x) * 0.06136;
106 g = g + (L_tex(pos - d).x + L_tex(pos + d).x) * 0.24477;
107 g = g + (L_tex(pos).x) * 0.38774;
108
109 return g;
110}
113vec4 hook() {
114 return vec4(lumGaussian7(HOOKED_pos, vec2(0.0, HOOKED_pt.y)), minmax3(HOOKED_pos, vec2(0.0, HOOKED_pt.y)), 0.0);
115}
117//!DESC Anime4K-v3.2-Deblur-DoG-Apply
118//!HOOK MAIN
119//!BIND HOOKED
120//!BIND LINELUMA
121//!BIND MMKERNEL
123#define STRENGTH 0.6 //De-blur proportional strength, higher is sharper. However, it is better to tweak BLUR_CURVE instead to avoid ringing.
124#define BLUR_CURVE 0.6 //De-blur power curve, lower is sharper. Good values are between 0.3 - 1. Values greater than 1 softens the image;
125#define BLUR_THRESHOLD 0.1 //Value where curve kicks in, used to not de-blur already sharp edges. Only de-blur values that fall below this threshold.
126#define NOISE_THRESHOLD 0.001 //Value where curve stops, used to not sharpen noise. Only de-blur values that fall above this threshold.
128#define L_tex LINELUMA_tex
130vec4 hook() {
131 float c = (L_tex(HOOKED_pos).x - MMKERNEL_tex(HOOKED_pos).x) * STRENGTH;
132
133 float t_range = BLUR_THRESHOLD - NOISE_THRESHOLD;
134
135 float c_t = abs(c);
136 if (c_t > NOISE_THRESHOLD) {
137 c_t = (c_t - NOISE_THRESHOLD) / t_range;
138 c_t = pow(c_t, BLUR_CURVE);
139 c_t = c_t * t_range + NOISE_THRESHOLD;
140 c_t = c_t * sign(c);
141 } else {
142 c_t = c;
143 }
144
145 float cc = clamp(c_t + L_tex(HOOKED_pos).x, MMKERNEL_tex(HOOKED_pos).y, MMKERNEL_tex(HOOKED_pos).z) - L_tex(HOOKED_pos).x;
146
147 //This trick is only possible if the inverse Y->RGB matrix has 1 for every row... (which is the case for BT.709)
148 //Otherwise we would need to convert RGB to YUV, modify Y then convert back to RGB.
149 return HOOKED_tex(HOOKED_pos) + cc;
150}

mpv/shaders/Anime4K_Deblur_Original.glsl

Modified

+286 / −286 text lines

1// MIT License
2
3// Copyright (c) 2019-2021 bloc97
4// All rights reserved.
5
6// Permission is hereby granted, free of charge, to any person obtaining a copy
7// of this software and associated documentation files (the "Software"), to deal
8// in the Software without restriction, including without limitation the rights
9// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10// copies of the Software, and to permit persons to whom the Software is
11// furnished to do so, subject to the following conditions:
12
13// The above copyright notice and this permission notice shall be included in all
14// copies or substantial portions of the Software.
15
16// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22// SOFTWARE.
23
24//!DESC Anime4K-v3.2-Deblur-Original-Luma
25//!HOOK MAIN
26//!BIND HOOKED
27//!SAVE LINELUMA
28//!COMPONENTS 1
29
30float get_luma(vec4 rgba) {
31 return dot(vec4(0.299, 0.587, 0.114, 0.0), rgba);
32}
33
34vec4 hook() {
35 return vec4(get_luma(HOOKED_tex(HOOKED_pos)), 0.0, 0.0, 0.0);
36}
37
38//!DESC Anime4K-v3.2-Deblur-Original-Kernel-X
39//!HOOK MAIN
40//!BIND HOOKED
41//!BIND LINELUMA
42//!SAVE LUMAD
43//!WIDTH MAIN.w 2 *
44//!HEIGHT MAIN.h 2 *
45//!COMPONENTS 2
46
47vec4 hook() {
48 vec2 d = HOOKED_pt;
49
50 //[tl t tr]
51 //[ l c r]
52 //[bl b br]
53 float l = LINELUMA_tex(HOOKED_pos + vec2(-d.x, 0.0)).x;
54 float c = LINELUMA_tex(HOOKED_pos).x;
55 float r = LINELUMA_tex(HOOKED_pos + vec2(d.x, 0.0)).x;
56
57
58 //Horizontal Gradient
59 //[-1 0 1]
60 //[-2 0 2]
61 //[-1 0 1]
62 float xgrad = (-l + r);
63
64 //Vertical Gradient
65 //[-1 -2 -1]
66 //[ 0 0 0]
67 //[ 1 2 1]
68 float ygrad = (l + c + c + r);
69
70 //Computes the luminance's gradient
71 return vec4(xgrad, ygrad, 0.0, 0.0);
72}
73
74
75//!DESC Anime4K-v3.2-Deblur-Original-Kernel-Y
76//!HOOK MAIN
77//!BIND HOOKED
78//!BIND LUMAD
79//!SAVE LUMAD
80//!WIDTH MAIN.w 2 *
81//!HEIGHT MAIN.h 2 *
82//!COMPONENTS 2
83
84
85/* --------------------- SETTINGS --------------------- */
86
87//Strength of edge refinement, good values are between 0.2 and 4
88#define REFINE_STRENGTH 1.0
89
90
91/* --- MODIFY THESE SETTINGS BELOW AT YOUR OWN RISK --- */
92
93//Bias of the refinement function, good values are between 0 and 1
94#define REFINE_BIAS 0.0
95
96//Polynomial fit obtained by minimizing MSE error on image
97#define P5 ( 11.68129591)
98#define P4 (-42.46906057)
99#define P3 ( 60.28286266)
100#define P2 (-41.84451327)
101#define P1 ( 14.05517353)
102#define P0 (-1.081521930)
103
104/* ----------------- END OF SETTINGS ----------------- */
105
106float power_function(float x) {
107 float x2 = x * x;
108 float x3 = x2 * x;
109 float x4 = x2 * x2;
110 float x5 = x2 * x3;
111
112 return P5*x5 + P4*x4 + P3*x3 + P2*x2 + P1*x + P0;
113}
114
115vec4 hook() {
116 vec2 d = HOOKED_pt;
117
118 //[tl t tr]
119 //[ l cc r]
120 //[bl b br]
121 float tx = LUMAD_tex(HOOKED_pos + vec2(0.0, -d.y)).x;
122 float cx = LUMAD_tex(HOOKED_pos).x;
123 float bx = LUMAD_tex(HOOKED_pos + vec2(0.0, d.y)).x;
124
125
126 float ty = LUMAD_tex(HOOKED_pos + vec2(0.0, -d.y)).y;
127 //float cy = LUMAD_tex(HOOKED_pos).y;
128 float by = LUMAD_tex(HOOKED_pos + vec2(0.0, d.y)).y;
129
130
131 //Horizontal Gradient
132 //[-1 0 1]
133 //[-2 0 2]
134 //[-1 0 1]
135 float xgrad = (tx + cx + cx + bx);
136
137 //Vertical Gradient
138 //[-1 -2 -1]
139 //[ 0 0 0]
140 //[ 1 2 1]
141 float ygrad = (-ty + by);
142
143 //Computes the luminance's gradient
144 float sobel_norm = clamp(sqrt(xgrad * xgrad + ygrad * ygrad), 0.0, 1.0);
145
146 float dval = clamp(power_function(clamp(sobel_norm, 0.0, 1.0)) * REFINE_STRENGTH + REFINE_BIAS, 0.0, 1.0);
147
148 return vec4(sobel_norm, dval, 0.0, 0.0);
149}
150
151//!DESC Anime4K-v3.2-Deblur-Original-Kernel-X
152//!HOOK MAIN
153//!BIND HOOKED
154//!BIND LUMAD
155//!SAVE LUMAMM
156//!WIDTH MAIN.w 2 *
157//!HEIGHT MAIN.h 2 *
158//!COMPONENTS 2
159
160
161vec4 hook() {
162 vec2 d = HOOKED_pt;
163
164 if (LUMAD_tex(HOOKED_pos).y < 0.1) {
165 return vec4(0.0);
166 }
167
168 //[tl t tr]
169 //[ l c r]
170 //[bl b br]
171 float l = LUMAD_tex(HOOKED_pos + vec2(-d.x, 0.0)).x;
172 float c = LUMAD_tex(HOOKED_pos).x;
173 float r = LUMAD_tex(HOOKED_pos + vec2(d.x, 0.0)).x;
174
175 //Horizontal Gradient
176 //[-1 0 1]
177 //[-2 0 2]
178 //[-1 0 1]
179 float xgrad = (-l + r);
180
181 //Vertical Gradient
182 //[-1 -2 -1]
183 //[ 0 0 0]
184 //[ 1 2 1]
185 float ygrad = (l + c + c + r);
186
187
188 return vec4(xgrad, ygrad, 0.0, 0.0);
189}
190
191
192//!DESC Anime4K-v3.2-Deblur-Original-Kernel-Y
193//!HOOK MAIN
194//!BIND HOOKED
195//!BIND LUMAD
196//!BIND LUMAMM
197//!SAVE LUMAMM
198//!WIDTH MAIN.w 2 *
199//!HEIGHT MAIN.h 2 *
200//!COMPONENTS 2
201
202vec4 hook() {
203 vec2 d = HOOKED_pt;
204
205 if (LUMAD_tex(HOOKED_pos).y < 0.1) {
206 return vec4(0.0);
207 }
208
209 //[tl t tr]
210 //[ l cc r]
211 //[bl b br]
212 float tx = LUMAMM_tex(HOOKED_pos + vec2(0.0, -d.y)).x;
213 float cx = LUMAMM_tex(HOOKED_pos).x;
214 float bx = LUMAMM_tex(HOOKED_pos + vec2(0.0, d.y)).x;
215
216 float ty = LUMAMM_tex(HOOKED_pos + vec2(0.0, -d.y)).y;
217 //float cy = LUMAMM_tex(HOOKED_pos).y;
218 float by = LUMAMM_tex(HOOKED_pos + vec2(0.0, d.y)).y;
219
220 //Horizontal Gradient
221 //[-1 0 1]
222 //[-2 0 2]
223 //[-1 0 1]
224 float xgrad = (tx + cx + cx + bx);
225
226 //Vertical Gradient
227 //[-1 -2 -1]
228 //[ 0 0 0]
229 //[ 1 2 1]
230 float ygrad = (-ty + by);
231
232 float norm = sqrt(xgrad * xgrad + ygrad * ygrad);
233 if (norm <= 0.001) {
234 xgrad = 0.0;
235 ygrad = 0.0;
236 norm = 1.0;
237 }
238
239 return vec4(xgrad/norm, ygrad/norm, 0.0, 0.0);
240}
241
242
243//!DESC Anime4K-v3.2-Deblur-Original-Apply
244//!HOOK MAIN
245//!BIND HOOKED
246//!BIND LUMAD
247//!BIND LUMAMM
248//!WIDTH MAIN.w 2 *
249//!HEIGHT MAIN.h 2 *
250//!SAVE RESAMPLED
251
252
253vec4 hook() {
254 vec2 d = HOOKED_pt;
255
256 float dval = LUMAD_tex(HOOKED_pos).y;
257 if (dval < 0.1) {
258 return HOOKED_tex(HOOKED_pos);
259 }
260
261 vec4 dc = LUMAMM_tex(HOOKED_pos);
262 if (abs(dc.x + dc.y) <= 0.0001) {
263 return HOOKED_tex(HOOKED_pos);
264 }
265
266 float xpos = -sign(dc.x);
267 float ypos = -sign(dc.y);
268
269 vec4 xval = HOOKED_tex(HOOKED_pos + vec2(d.x * xpos, 0.0));
270 vec4 yval = HOOKED_tex(HOOKED_pos + vec2(0.0, d.y * ypos));
271
272 float xyratio = abs(dc.x) / (abs(dc.x) + abs(dc.y));
273
274 vec4 avg = xyratio * xval + (1.0 - xyratio) * yval;
275
276 return avg * dval + HOOKED_tex(HOOKED_pos) * (1.0 - dval);
277
278}
279
280//!DESC Anime4K-v3.2-Deblur-Original-Resample
281//!HOOK MAIN
282//!BIND HOOKED
283//!BIND RESAMPLED
284
285vec4 hook() {
286 return RESAMPLED_tex(HOOKED_pos);
1// MIT License
2
3// Copyright (c) 2019-2021 bloc97
4// All rights reserved.
5
6// Permission is hereby granted, free of charge, to any person obtaining a copy
7// of this software and associated documentation files (the "Software"), to deal
8// in the Software without restriction, including without limitation the rights
9// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10// copies of the Software, and to permit persons to whom the Software is
11// furnished to do so, subject to the following conditions:
13// The above copyright notice and this permission notice shall be included in all
14// copies or substantial portions of the Software.
16// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22// SOFTWARE.
24//!DESC Anime4K-v3.2-Deblur-Original-Luma
25//!HOOK MAIN
26//!BIND HOOKED
27//!SAVE LINELUMA
28//!COMPONENTS 1
30float get_luma(vec4 rgba) {
31 return dot(vec4(0.299, 0.587, 0.114, 0.0), rgba);
32}
34vec4 hook() {
35 return vec4(get_luma(HOOKED_tex(HOOKED_pos)), 0.0, 0.0, 0.0);
36}
38//!DESC Anime4K-v3.2-Deblur-Original-Kernel-X
39//!HOOK MAIN
40//!BIND HOOKED
41//!BIND LINELUMA
42//!SAVE LUMAD
43//!WIDTH MAIN.w 2 *
44//!HEIGHT MAIN.h 2 *
45//!COMPONENTS 2
47vec4 hook() {
48 vec2 d = HOOKED_pt;
49
50 //[tl t tr]
51 //[ l c r]
52 //[bl b br]
53 float l = LINELUMA_tex(HOOKED_pos + vec2(-d.x, 0.0)).x;
54 float c = LINELUMA_tex(HOOKED_pos).x;
55 float r = LINELUMA_tex(HOOKED_pos + vec2(d.x, 0.0)).x;
56
57
58 //Horizontal Gradient
59 //[-1 0 1]
60 //[-2 0 2]
61 //[-1 0 1]
62 float xgrad = (-l + r);
63
64 //Vertical Gradient
65 //[-1 -2 -1]
66 //[ 0 0 0]
67 //[ 1 2 1]
68 float ygrad = (l + c + c + r);
69
70 //Computes the luminance's gradient
71 return vec4(xgrad, ygrad, 0.0, 0.0);
72}
75//!DESC Anime4K-v3.2-Deblur-Original-Kernel-Y
76//!HOOK MAIN
77//!BIND HOOKED
78//!BIND LUMAD
79//!SAVE LUMAD
80//!WIDTH MAIN.w 2 *
81//!HEIGHT MAIN.h 2 *
82//!COMPONENTS 2
85/* --------------------- SETTINGS --------------------- */
87//Strength of edge refinement, good values are between 0.2 and 4
88#define REFINE_STRENGTH 1.0
91/* --- MODIFY THESE SETTINGS BELOW AT YOUR OWN RISK --- */
93//Bias of the refinement function, good values are between 0 and 1
94#define REFINE_BIAS 0.0
96//Polynomial fit obtained by minimizing MSE error on image
97#define P5 ( 11.68129591)
98#define P4 (-42.46906057)
99#define P3 ( 60.28286266)
100#define P2 (-41.84451327)
101#define P1 ( 14.05517353)
102#define P0 (-1.081521930)
104/* ----------------- END OF SETTINGS ----------------- */
106float power_function(float x) {
107 float x2 = x * x;
108 float x3 = x2 * x;
109 float x4 = x2 * x2;
110 float x5 = x2 * x3;
111
112 return P5*x5 + P4*x4 + P3*x3 + P2*x2 + P1*x + P0;
113}
115vec4 hook() {
116 vec2 d = HOOKED_pt;
117
118 //[tl t tr]
119 //[ l cc r]
120 //[bl b br]
121 float tx = LUMAD_tex(HOOKED_pos + vec2(0.0, -d.y)).x;
122 float cx = LUMAD_tex(HOOKED_pos).x;
123 float bx = LUMAD_tex(HOOKED_pos + vec2(0.0, d.y)).x;
124
125
126 float ty = LUMAD_tex(HOOKED_pos + vec2(0.0, -d.y)).y;
127 //float cy = LUMAD_tex(HOOKED_pos).y;
128 float by = LUMAD_tex(HOOKED_pos + vec2(0.0, d.y)).y;
129
130
131 //Horizontal Gradient
132 //[-1 0 1]
133 //[-2 0 2]
134 //[-1 0 1]
135 float xgrad = (tx + cx + cx + bx);
136
137 //Vertical Gradient
138 //[-1 -2 -1]
139 //[ 0 0 0]
140 //[ 1 2 1]
141 float ygrad = (-ty + by);
142
143 //Computes the luminance's gradient
144 float sobel_norm = clamp(sqrt(xgrad * xgrad + ygrad * ygrad), 0.0, 1.0);
145
146 float dval = clamp(power_function(clamp(sobel_norm, 0.0, 1.0)) * REFINE_STRENGTH + REFINE_BIAS, 0.0, 1.0);
147
148 return vec4(sobel_norm, dval, 0.0, 0.0);
149}
151//!DESC Anime4K-v3.2-Deblur-Original-Kernel-X
152//!HOOK MAIN
153//!BIND HOOKED
154//!BIND LUMAD
155//!SAVE LUMAMM
156//!WIDTH MAIN.w 2 *
157//!HEIGHT MAIN.h 2 *
158//!COMPONENTS 2
161vec4 hook() {
162 vec2 d = HOOKED_pt;
163
164 if (LUMAD_tex(HOOKED_pos).y < 0.1) {
165 return vec4(0.0);
166 }
167
168 //[tl t tr]
169 //[ l c r]
170 //[bl b br]
171 float l = LUMAD_tex(HOOKED_pos + vec2(-d.x, 0.0)).x;
172 float c = LUMAD_tex(HOOKED_pos).x;
173 float r = LUMAD_tex(HOOKED_pos + vec2(d.x, 0.0)).x;
174
175 //Horizontal Gradient
176 //[-1 0 1]
177 //[-2 0 2]
178 //[-1 0 1]
179 float xgrad = (-l + r);
180
181 //Vertical Gradient
182 //[-1 -2 -1]
183 //[ 0 0 0]
184 //[ 1 2 1]
185 float ygrad = (l + c + c + r);
186
187
188 return vec4(xgrad, ygrad, 0.0, 0.0);
189}
192//!DESC Anime4K-v3.2-Deblur-Original-Kernel-Y
193//!HOOK MAIN
194//!BIND HOOKED
195//!BIND LUMAD
196//!BIND LUMAMM
197//!SAVE LUMAMM
198//!WIDTH MAIN.w 2 *
199//!HEIGHT MAIN.h 2 *
200//!COMPONENTS 2
202vec4 hook() {
203 vec2 d = HOOKED_pt;
204
205 if (LUMAD_tex(HOOKED_pos).y < 0.1) {
206 return vec4(0.0);
207 }
208
209 //[tl t tr]
210 //[ l cc r]
211 //[bl b br]
212 float tx = LUMAMM_tex(HOOKED_pos + vec2(0.0, -d.y)).x;
213 float cx = LUMAMM_tex(HOOKED_pos).x;
214 float bx = LUMAMM_tex(HOOKED_pos + vec2(0.0, d.y)).x;
215
216 float ty = LUMAMM_tex(HOOKED_pos + vec2(0.0, -d.y)).y;
217 //float cy = LUMAMM_tex(HOOKED_pos).y;
218 float by = LUMAMM_tex(HOOKED_pos + vec2(0.0, d.y)).y;
219
220 //Horizontal Gradient
221 //[-1 0 1]
222 //[-2 0 2]
223 //[-1 0 1]
224 float xgrad = (tx + cx + cx + bx);
225
226 //Vertical Gradient
227 //[-1 -2 -1]
228 //[ 0 0 0]
229 //[ 1 2 1]
230 float ygrad = (-ty + by);
231
232 float norm = sqrt(xgrad * xgrad + ygrad * ygrad);
233 if (norm <= 0.001) {
234 xgrad = 0.0;
235 ygrad = 0.0;
236 norm = 1.0;
237 }
238
239 return vec4(xgrad/norm, ygrad/norm, 0.0, 0.0);
240}
243//!DESC Anime4K-v3.2-Deblur-Original-Apply
244//!HOOK MAIN
245//!BIND HOOKED
246//!BIND LUMAD
247//!BIND LUMAMM
248//!WIDTH MAIN.w 2 *
249//!HEIGHT MAIN.h 2 *
250//!SAVE RESAMPLED
253vec4 hook() {
254 vec2 d = HOOKED_pt;
255
256 float dval = LUMAD_tex(HOOKED_pos).y;
257 if (dval < 0.1) {
258 return HOOKED_tex(HOOKED_pos);
259 }
260
261 vec4 dc = LUMAMM_tex(HOOKED_pos);
262 if (abs(dc.x + dc.y) <= 0.0001) {
263 return HOOKED_tex(HOOKED_pos);
264 }
265
266 float xpos = -sign(dc.x);
267 float ypos = -sign(dc.y);
268
269 vec4 xval = HOOKED_tex(HOOKED_pos + vec2(d.x * xpos, 0.0));
270 vec4 yval = HOOKED_tex(HOOKED_pos + vec2(0.0, d.y * ypos));
271
272 float xyratio = abs(dc.x) / (abs(dc.x) + abs(dc.y));
273
274 vec4 avg = xyratio * xval + (1.0 - xyratio) * yval;
275
276 return avg * dval + HOOKED_tex(HOOKED_pos) * (1.0 - dval);
277
278}
280//!DESC Anime4K-v3.2-Deblur-Original-Resample
281//!HOOK MAIN
282//!BIND HOOKED
283//!BIND RESAMPLED
285vec4 hook() {
286 return RESAMPLED_tex(HOOKED_pos);
287287}No final newline

mpv/shaders/Anime4K_Denoise_Bilateral_Mean.glsl

Modified

+66 / −66 text lines

1// MIT License
2
3// Copyright (c) 2019-2021 bloc97
4// All rights reserved.
5
6// Permission is hereby granted, free of charge, to any person obtaining a copy
7// of this software and associated documentation files (the "Software"), to deal
8// in the Software without restriction, including without limitation the rights
9// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10// copies of the Software, and to permit persons to whom the Software is
11// furnished to do so, subject to the following conditions:
12
13// The above copyright notice and this permission notice shall be included in all
14// copies or substantial portions of the Software.
15
16// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22// SOFTWARE.
23
24//!DESC Anime4K-v3.2-Denoise-Bilateral-Mean
25//!HOOK MAIN
26//!BIND HOOKED
27
28#define INTENSITY_SIGMA 0.1 //Intensity window size, higher is stronger denoise, must be a positive real number
29#define SPATIAL_SIGMA 1.0 //Spatial window size, higher is stronger denoise, must be a positive real number.
30
31#define INTENSITY_POWER_CURVE 1.0 //Intensity window power curve. Setting it to 0 will make the intensity window treat all intensities equally, while increasing it will make the window narrower in darker intensities and wider in brighter intensities.
32
33#define KERNELSIZE (max(int(ceil(SPATIAL_SIGMA * 2.0)), 1) * 2 + 1) //Kernel size, must be an positive odd integer.
34#define KERNELHALFSIZE (int(KERNELSIZE/2)) //Half of the kernel size without remainder. Must be equal to trunc(KERNELSIZE/2).
35#define KERNELLEN (KERNELSIZE * KERNELSIZE) //Total area of kernel. Must be equal to KERNELSIZE * KERNELSIZE.
36
37#define GETOFFSET(i) vec2((i % KERNELSIZE) - KERNELHALFSIZE, (i / KERNELSIZE) - KERNELHALFSIZE)
38
39vec4 gaussian_vec(vec4 x, vec4 s, vec4 m) {
40 vec4 scaled = (x - m) / s;
41 return exp(-0.5 * scaled * scaled);
42}
43
44float gaussian(float x, float s, float m) {
45 float scaled = (x - m) / s;
46 return exp(-0.5 * scaled * scaled);
47}
48
49vec4 hook() {
50 vec4 sum = vec4(0.0);
51 vec4 n = vec4(0.0);
52
53 vec4 vc = HOOKED_tex(HOOKED_pos);
54
55 vec4 is = pow(vc + 0.0001, vec4(INTENSITY_POWER_CURVE)) * INTENSITY_SIGMA;
56 float ss = SPATIAL_SIGMA;
57
58 for (int i=0; i<KERNELLEN; i++) {
59 vec2 ipos = GETOFFSET(i);
60 vec4 v = HOOKED_texOff(ipos);
61 vec4 d = gaussian_vec(v, is, vc) * gaussian(length(ipos), ss, 0.0);
62 sum += d * v;
63 n += d;
64 }
65
66 return sum / n;
1// MIT License
2
3// Copyright (c) 2019-2021 bloc97
4// All rights reserved.
5
6// Permission is hereby granted, free of charge, to any person obtaining a copy
7// of this software and associated documentation files (the "Software"), to deal
8// in the Software without restriction, including without limitation the rights
9// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10// copies of the Software, and to permit persons to whom the Software is
11// furnished to do so, subject to the following conditions:
13// The above copyright notice and this permission notice shall be included in all
14// copies or substantial portions of the Software.
16// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22// SOFTWARE.
24//!DESC Anime4K-v3.2-Denoise-Bilateral-Mean
25//!HOOK MAIN
26//!BIND HOOKED
28#define INTENSITY_SIGMA 0.1 //Intensity window size, higher is stronger denoise, must be a positive real number
29#define SPATIAL_SIGMA 1.0 //Spatial window size, higher is stronger denoise, must be a positive real number.
31#define INTENSITY_POWER_CURVE 1.0 //Intensity window power curve. Setting it to 0 will make the intensity window treat all intensities equally, while increasing it will make the window narrower in darker intensities and wider in brighter intensities.
33#define KERNELSIZE (max(int(ceil(SPATIAL_SIGMA * 2.0)), 1) * 2 + 1) //Kernel size, must be an positive odd integer.
34#define KERNELHALFSIZE (int(KERNELSIZE/2)) //Half of the kernel size without remainder. Must be equal to trunc(KERNELSIZE/2).
35#define KERNELLEN (KERNELSIZE * KERNELSIZE) //Total area of kernel. Must be equal to KERNELSIZE * KERNELSIZE.
37#define GETOFFSET(i) vec2((i % KERNELSIZE) - KERNELHALFSIZE, (i / KERNELSIZE) - KERNELHALFSIZE)
39vec4 gaussian_vec(vec4 x, vec4 s, vec4 m) {
40 vec4 scaled = (x - m) / s;
41 return exp(-0.5 * scaled * scaled);
42}
44float gaussian(float x, float s, float m) {
45 float scaled = (x - m) / s;
46 return exp(-0.5 * scaled * scaled);
47}
49vec4 hook() {
50 vec4 sum = vec4(0.0);
51 vec4 n = vec4(0.0);
52
53 vec4 vc = HOOKED_tex(HOOKED_pos);
54
55 vec4 is = pow(vc + 0.0001, vec4(INTENSITY_POWER_CURVE)) * INTENSITY_SIGMA;
56 float ss = SPATIAL_SIGMA;
57
58 for (int i=0; i<KERNELLEN; i++) {
59 vec2 ipos = GETOFFSET(i);
60 vec4 v = HOOKED_texOff(ipos);
61 vec4 d = gaussian_vec(v, is, vc) * gaussian(length(ipos), ss, 0.0);
62 sum += d * v;
63 n += d;
64 }
65
66 return sum / n;
6767}No final newline

mpv/shaders/Anime4K_Denoise_Bilateral_Median.glsl

Modified

+119 / −119 text lines

1// MIT License
2
3// Copyright (c) 2019-2021 bloc97
4// All rights reserved.
5
6// Permission is hereby granted, free of charge, to any person obtaining a copy
7// of this software and associated documentation files (the "Software"), to deal
8// in the Software without restriction, including without limitation the rights
9// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10// copies of the Software, and to permit persons to whom the Software is
11// furnished to do so, subject to the following conditions:
12
13// The above copyright notice and this permission notice shall be included in all
14// copies or substantial portions of the Software.
15
16// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22// SOFTWARE.
23
24//!DESC Anime4K-v3.2-Denoise-Bilateral-Median-Luma
25//!HOOK MAIN
26//!BIND HOOKED
27//!SAVE LINELUMA
28//!COMPONENTS 1
29
30float get_luma(vec4 rgba) {
31 return dot(vec4(0.299, 0.587, 0.114, 0.0), rgba);
32}
33
34vec4 hook() {
35 return vec4(get_luma(HOOKED_tex(HOOKED_pos)), 0.0, 0.0, 0.0);
36}
37
38//!DESC Anime4K-v3.2-Denoise-Bilateral-Median-Apply
39//!HOOK MAIN
40//!BIND HOOKED
41//!BIND LINELUMA
42
43#define INTENSITY_SIGMA 0.1 //Intensity window size, higher is stronger denoise, must be a positive real number
44#define SPATIAL_SIGMA 1.0 //Spatial window size, higher is stronger denoise, must be a positive real number.
45#define HISTOGRAM_REGULARIZATION 0.0 //Histogram regularization window size, higher values approximate a bilateral "closest-to-mean" filter.
46
47#define INTENSITY_POWER_CURVE 1.0 //Intensity window power curve. Setting it to 0 will make the intensity window treat all intensities equally, while increasing it will make the window narrower in darker intensities and wider in brighter intensities.
48
49#define KERNELSIZE int(max(int(SPATIAL_SIGMA), 1) * 2 + 1) //Kernel size, must be an positive odd integer.
50#define KERNELHALFSIZE (int(KERNELSIZE/2)) //Half of the kernel size without remainder. Must be equal to trunc(KERNELSIZE/2).
51#define KERNELLEN (KERNELSIZE * KERNELSIZE) //Total area of kernel. Must be equal to KERNELSIZE * KERNELSIZE.
52
53#define GETOFFSET(i) vec2((i % KERNELSIZE) - KERNELHALFSIZE, (i / KERNELSIZE) - KERNELHALFSIZE)
54
55float gaussian(float x, float s, float m) {
56 float scaled = (x - m) / s;
57 return exp(-0.5 * scaled * scaled);
58}
59
60vec4 getMedian(vec4 v[KERNELLEN], float w[KERNELLEN], float n) {
61
62 for (int i=0; i<KERNELLEN; i++) {
63 float w_above = 0.0;
64 float w_below = 0.0;
65 for (int j=0; j<KERNELLEN; j++) {
66 if (v[j].x > v[i].x) {
67 w_above += w[j];
68 } else if (v[j].x < v[i].x) {
69 w_below += w[j];
70 }
71 }
72
73 if ((n - w_above) / n >= 0.5 && w_below / n <= 0.5) {
74 return v[i];
75 }
76 }
77}
78
79vec4 hook() {
80 vec4 histogram_v[KERNELLEN];
81 float histogram_l[KERNELLEN];
82 float histogram_w[KERNELLEN];
83 float n = 0.0;
84
85 float vc = LINELUMA_tex(HOOKED_pos).x;
86
87 float is = pow(vc + 0.0001, INTENSITY_POWER_CURVE) * INTENSITY_SIGMA;
88 float ss = SPATIAL_SIGMA;
89
90 for (int i=0; i<KERNELLEN; i++) {
91 vec2 ipos = GETOFFSET(i);
92 histogram_v[i] = HOOKED_texOff(ipos);
93 histogram_l[i] = LINELUMA_texOff(ipos).x;
94 histogram_w[i] = gaussian(histogram_l[i], is, vc) * gaussian(length(ipos), ss, 0.0);
95 n += histogram_w[i];
96 }
97
98 if (HISTOGRAM_REGULARIZATION > 0.0) {
99 float histogram_wn[KERNELLEN];
100 n = 0.0;
101
102 for (int i=0; i<KERNELLEN; i++) {
103 histogram_wn[i] = 0.0;
104 }
105
106 for (int i=0; i<KERNELLEN; i++) {
107 histogram_wn[i] += gaussian(0.0, HISTOGRAM_REGULARIZATION, 0.0) * histogram_w[i];
108 for (int j=(i+1); j<KERNELLEN; j++) {
109 float d = gaussian(histogram_l[j], HISTOGRAM_REGULARIZATION, histogram_l[i]);
110 histogram_wn[j] += d * histogram_w[i];
111 histogram_wn[i] += d * histogram_w[j];
112 }
113 n += histogram_wn[i];
114 }
115
116 return getMedian(histogram_v, histogram_wn, n);
117 }
118
119 return getMedian(histogram_v, histogram_w, n);
1// MIT License
2
3// Copyright (c) 2019-2021 bloc97
4// All rights reserved.
5
6// Permission is hereby granted, free of charge, to any person obtaining a copy
7// of this software and associated documentation files (the "Software"), to deal
8// in the Software without restriction, including without limitation the rights
9// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10// copies of the Software, and to permit persons to whom the Software is
11// furnished to do so, subject to the following conditions:
13// The above copyright notice and this permission notice shall be included in all
14// copies or substantial portions of the Software.
16// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22// SOFTWARE.
24//!DESC Anime4K-v3.2-Denoise-Bilateral-Median-Luma
25//!HOOK MAIN
26//!BIND HOOKED
27//!SAVE LINELUMA
28//!COMPONENTS 1
30float get_luma(vec4 rgba) {
31 return dot(vec4(0.299, 0.587, 0.114, 0.0), rgba);
32}
34vec4 hook() {
35 return vec4(get_luma(HOOKED_tex(HOOKED_pos)), 0.0, 0.0, 0.0);
36}
38//!DESC Anime4K-v3.2-Denoise-Bilateral-Median-Apply
39//!HOOK MAIN
40//!BIND HOOKED
41//!BIND LINELUMA
43#define INTENSITY_SIGMA 0.1 //Intensity window size, higher is stronger denoise, must be a positive real number
44#define SPATIAL_SIGMA 1.0 //Spatial window size, higher is stronger denoise, must be a positive real number.
45#define HISTOGRAM_REGULARIZATION 0.0 //Histogram regularization window size, higher values approximate a bilateral "closest-to-mean" filter.
47#define INTENSITY_POWER_CURVE 1.0 //Intensity window power curve. Setting it to 0 will make the intensity window treat all intensities equally, while increasing it will make the window narrower in darker intensities and wider in brighter intensities.
49#define KERNELSIZE int(max(int(SPATIAL_SIGMA), 1) * 2 + 1) //Kernel size, must be an positive odd integer.
50#define KERNELHALFSIZE (int(KERNELSIZE/2)) //Half of the kernel size without remainder. Must be equal to trunc(KERNELSIZE/2).
51#define KERNELLEN (KERNELSIZE * KERNELSIZE) //Total area of kernel. Must be equal to KERNELSIZE * KERNELSIZE.
53#define GETOFFSET(i) vec2((i % KERNELSIZE) - KERNELHALFSIZE, (i / KERNELSIZE) - KERNELHALFSIZE)
55float gaussian(float x, float s, float m) {
56 float scaled = (x - m) / s;
57 return exp(-0.5 * scaled * scaled);
58}
60vec4 getMedian(vec4 v[KERNELLEN], float w[KERNELLEN], float n) {
61
62 for (int i=0; i<KERNELLEN; i++) {
63 float w_above = 0.0;
64 float w_below = 0.0;
65 for (int j=0; j<KERNELLEN; j++) {
66 if (v[j].x > v[i].x) {
67 w_above += w[j];
68 } else if (v[j].x < v[i].x) {
69 w_below += w[j];
70 }
71 }
72
73 if ((n - w_above) / n >= 0.5 && w_below / n <= 0.5) {
74 return v[i];
75 }
76 }
77}
79vec4 hook() {
80 vec4 histogram_v[KERNELLEN];
81 float histogram_l[KERNELLEN];
82 float histogram_w[KERNELLEN];
83 float n = 0.0;
84
85 float vc = LINELUMA_tex(HOOKED_pos).x;
86
87 float is = pow(vc + 0.0001, INTENSITY_POWER_CURVE) * INTENSITY_SIGMA;
88 float ss = SPATIAL_SIGMA;
89
90 for (int i=0; i<KERNELLEN; i++) {
91 vec2 ipos = GETOFFSET(i);
92 histogram_v[i] = HOOKED_texOff(ipos);
93 histogram_l[i] = LINELUMA_texOff(ipos).x;
94 histogram_w[i] = gaussian(histogram_l[i], is, vc) * gaussian(length(ipos), ss, 0.0);
95 n += histogram_w[i];
96 }
97
98 if (HISTOGRAM_REGULARIZATION > 0.0) {
99 float histogram_wn[KERNELLEN];
100 n = 0.0;
101
102 for (int i=0; i<KERNELLEN; i++) {
103 histogram_wn[i] = 0.0;
104 }
105
106 for (int i=0; i<KERNELLEN; i++) {
107 histogram_wn[i] += gaussian(0.0, HISTOGRAM_REGULARIZATION, 0.0) * histogram_w[i];
108 for (int j=(i+1); j<KERNELLEN; j++) {
109 float d = gaussian(histogram_l[j], HISTOGRAM_REGULARIZATION, histogram_l[i]);
110 histogram_wn[j] += d * histogram_w[i];
111 histogram_wn[i] += d * histogram_w[j];
112 }
113 n += histogram_wn[i];
114 }
115
116 return getMedian(histogram_v, histogram_wn, n);
117 }
118
119 return getMedian(histogram_v, histogram_w, n);
120120}No final newline

mpv/shaders/Anime4K_Denoise_Bilateral_Mode.glsl

Modified

+102 / −102 text lines

1// MIT License
2
3// Copyright (c) 2019-2021 bloc97
4// All rights reserved.
5
6// Permission is hereby granted, free of charge, to any person obtaining a copy
7// of this software and associated documentation files (the "Software"), to deal
8// in the Software without restriction, including without limitation the rights
9// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10// copies of the Software, and to permit persons to whom the Software is
11// furnished to do so, subject to the following conditions:
12
13// The above copyright notice and this permission notice shall be included in all
14// copies or substantial portions of the Software.
15
16// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22// SOFTWARE.
23
24//!DESC Anime4K-v3.2-Denoise-Bilateral-Mode-Luma
25//!HOOK MAIN
26//!BIND HOOKED
27//!SAVE LINELUMA
28//!COMPONENTS 1
29
30float get_luma(vec4 rgba) {
31 return dot(vec4(0.299, 0.587, 0.114, 0.0), rgba);
32}
33
34vec4 hook() {
35 return vec4(get_luma(HOOKED_tex(HOOKED_pos)), 0.0, 0.0, 0.0);
36}
37
38//!DESC Anime4K-v3.1-Denoise-Bilateral-Mode-Apply
39//!HOOK MAIN
40//!BIND HOOKED
41//!BIND LINELUMA
42
43#define INTENSITY_SIGMA 0.1 //Intensity window size, higher is stronger denoise, must be a positive real number
44#define SPATIAL_SIGMA 1.0 //Spatial window size, higher is stronger denoise, must be a positive real number.
45#define HISTOGRAM_REGULARIZATION 0.2 //Histogram regularization window size, higher values approximate a bilateral "closest-to-mean" filter.
46
47#define INTENSITY_POWER_CURVE 1.0 //Intensity window power curve. Setting it to 0 will make the intensity window treat all intensities equally, while increasing it will make the window narrower in darker intensities and wider in brighter intensities.
48
49#define KERNELSIZE int(max(int(SPATIAL_SIGMA), 1) * 2 + 1) //Kernel size, must be an positive odd integer.
50#define KERNELHALFSIZE (int(KERNELSIZE/2)) //Half of the kernel size without remainder. Must be equal to trunc(KERNELSIZE/2).
51#define KERNELLEN (KERNELSIZE * KERNELSIZE) //Total area of kernel. Must be equal to KERNELSIZE * KERNELSIZE.
52
53#define GETOFFSET(i) vec2((i % KERNELSIZE) - KERNELHALFSIZE, (i / KERNELSIZE) - KERNELHALFSIZE)
54
55float gaussian(float x, float s, float m) {
56 float scaled = (x - m) / s;
57 return exp(-0.5 * scaled * scaled);
58}
59
60vec4 getMode(vec4 v[KERNELLEN], float w[KERNELLEN]) {
61 vec4 maxv = vec4(0);
62 float maxw = 0.0;
63
64 for (int i=0; i<KERNELLEN; i++) {
65 if (w[i] >= maxw) {
66 maxw = w[i];
67 maxv = v[i];
68 }
69 }
70
71 return maxv;
72}
73
74vec4 hook() {
75 vec4 histogram_v[KERNELLEN];
76 float histogram_l[KERNELLEN];
77 float histogram_w[KERNELLEN];
78 float histogram_wn[KERNELLEN];
79
80 float vc = LINELUMA_tex(HOOKED_pos).x;
81
82 float is = pow(vc + 0.0001, INTENSITY_POWER_CURVE) * INTENSITY_SIGMA;
83 float ss = SPATIAL_SIGMA;
84
85 for (int i=0; i<KERNELLEN; i++) {
86 vec2 ipos = GETOFFSET(i);
87 histogram_v[i] = HOOKED_texOff(ipos);
88 histogram_l[i] = LINELUMA_texOff(ipos).x;
89 histogram_w[i] = gaussian(histogram_l[i], is, vc) * gaussian(length(ipos), ss, 0.0);
90 histogram_wn[i] = 0.0;
91 }
92
93 for (int i=0; i<KERNELLEN; i++) {
94 histogram_wn[i] += gaussian(0.0, HISTOGRAM_REGULARIZATION, 0.0) * histogram_w[i];
95 for (int j=(i+1); j<KERNELLEN; j++) {
96 float d = gaussian(histogram_l[j], HISTOGRAM_REGULARIZATION, histogram_l[i]);
97 histogram_wn[j] += d * histogram_w[i];
98 histogram_wn[i] += d * histogram_w[j];
99 }
100 }
101
102 return getMode(histogram_v, histogram_wn);
1// MIT License
2
3// Copyright (c) 2019-2021 bloc97
4// All rights reserved.
5
6// Permission is hereby granted, free of charge, to any person obtaining a copy
7// of this software and associated documentation files (the "Software"), to deal
8// in the Software without restriction, including without limitation the rights
9// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10// copies of the Software, and to permit persons to whom the Software is
11// furnished to do so, subject to the following conditions:
13// The above copyright notice and this permission notice shall be included in all
14// copies or substantial portions of the Software.
16// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22// SOFTWARE.
24//!DESC Anime4K-v3.2-Denoise-Bilateral-Mode-Luma
25//!HOOK MAIN
26//!BIND HOOKED
27//!SAVE LINELUMA
28//!COMPONENTS 1
30float get_luma(vec4 rgba) {
31 return dot(vec4(0.299, 0.587, 0.114, 0.0), rgba);
32}
34vec4 hook() {
35 return vec4(get_luma(HOOKED_tex(HOOKED_pos)), 0.0, 0.0, 0.0);
36}
38//!DESC Anime4K-v3.1-Denoise-Bilateral-Mode-Apply
39//!HOOK MAIN
40//!BIND HOOKED
41//!BIND LINELUMA
43#define INTENSITY_SIGMA 0.1 //Intensity window size, higher is stronger denoise, must be a positive real number
44#define SPATIAL_SIGMA 1.0 //Spatial window size, higher is stronger denoise, must be a positive real number.
45#define HISTOGRAM_REGULARIZATION 0.2 //Histogram regularization window size, higher values approximate a bilateral "closest-to-mean" filter.
47#define INTENSITY_POWER_CURVE 1.0 //Intensity window power curve. Setting it to 0 will make the intensity window treat all intensities equally, while increasing it will make the window narrower in darker intensities and wider in brighter intensities.
49#define KERNELSIZE int(max(int(SPATIAL_SIGMA), 1) * 2 + 1) //Kernel size, must be an positive odd integer.
50#define KERNELHALFSIZE (int(KERNELSIZE/2)) //Half of the kernel size without remainder. Must be equal to trunc(KERNELSIZE/2).
51#define KERNELLEN (KERNELSIZE * KERNELSIZE) //Total area of kernel. Must be equal to KERNELSIZE * KERNELSIZE.
53#define GETOFFSET(i) vec2((i % KERNELSIZE) - KERNELHALFSIZE, (i / KERNELSIZE) - KERNELHALFSIZE)
55float gaussian(float x, float s, float m) {
56 float scaled = (x - m) / s;
57 return exp(-0.5 * scaled * scaled);
58}
60vec4 getMode(vec4 v[KERNELLEN], float w[KERNELLEN]) {
61 vec4 maxv = vec4(0);
62 float maxw = 0.0;
63
64 for (int i=0; i<KERNELLEN; i++) {
65 if (w[i] >= maxw) {
66 maxw = w[i];
67 maxv = v[i];
68 }
69 }
70
71 return maxv;
72}
74vec4 hook() {
75 vec4 histogram_v[KERNELLEN];
76 float histogram_l[KERNELLEN];
77 float histogram_w[KERNELLEN];
78 float histogram_wn[KERNELLEN];
79
80 float vc = LINELUMA_tex(HOOKED_pos).x;
81
82 float is = pow(vc + 0.0001, INTENSITY_POWER_CURVE) * INTENSITY_SIGMA;
83 float ss = SPATIAL_SIGMA;
84
85 for (int i=0; i<KERNELLEN; i++) {
86 vec2 ipos = GETOFFSET(i);
87 histogram_v[i] = HOOKED_texOff(ipos);
88 histogram_l[i] = LINELUMA_texOff(ipos).x;
89 histogram_w[i] = gaussian(histogram_l[i], is, vc) * gaussian(length(ipos), ss, 0.0);
90 histogram_wn[i] = 0.0;
91 }
92
93 for (int i=0; i<KERNELLEN; i++) {
94 histogram_wn[i] += gaussian(0.0, HISTOGRAM_REGULARIZATION, 0.0) * histogram_w[i];
95 for (int j=(i+1); j<KERNELLEN; j++) {
96 float d = gaussian(histogram_l[j], HISTOGRAM_REGULARIZATION, histogram_l[i]);
97 histogram_wn[j] += d * histogram_w[i];
98 histogram_wn[i] += d * histogram_w[j];
99 }
100 }
101
102 return getMode(histogram_v, histogram_wn);
103103}No final newline

mpv/shaders/Anime4K_Thin_Fast.glsl

Modified

+234 / −234 text lines

1// MIT License
2
3// Copyright (c) 2019-2021 bloc97
4// All rights reserved.
5
6// Permission is hereby granted, free of charge, to any person obtaining a copy
7// of this software and associated documentation files (the "Software"), to deal
8// in the Software without restriction, including without limitation the rights
9// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10// copies of the Software, and to permit persons to whom the Software is
11// furnished to do so, subject to the following conditions:
12
13// The above copyright notice and this permission notice shall be included in all
14// copies or substantial portions of the Software.
15
16// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22// SOFTWARE.
23
24//!DESC Anime4K-v3.2-Thin-(Fast)-Luma
25//!HOOK MAIN
26//!BIND HOOKED
27//!SAVE LINELUMA
28//!COMPONENTS 1
29
30float get_luma(vec4 rgba) {
31 return dot(vec4(0.299, 0.587, 0.114, 0.0), rgba);
32}
33
34vec4 hook() {
35 return vec4(get_luma(HOOKED_tex(HOOKED_pos)), 0.0, 0.0, 0.0);
36}
37
38//!DESC Anime4K-v3.2-Thin-(Fast)-Sobel-X
39//!HOOK MAIN
40//!BIND LINELUMA
41//!SAVE LINESOBEL
42//!WIDTH HOOKED.w 2 /
43//!HEIGHT HOOKED.h 2 /
44//!COMPONENTS 2
45
46vec4 hook() {
47 float l = LINELUMA_texOff(vec2(-1.0, 0.0)).x;
48 float c = LINELUMA_tex(LINELUMA_pos).x;
49 float r = LINELUMA_texOff(vec2(1.0, 0.0)).x;
50
51 float xgrad = (-l + r);
52 float ygrad = (l + c + c + r);
53
54 return vec4(xgrad, ygrad, 0.0, 0.0);
55}
56
57
58//!DESC Anime4K-v3.2-Thin-(Fast)-Sobel-Y
59//!HOOK MAIN
60//!BIND LINESOBEL
61//!SAVE LINESOBEL
62//!WIDTH HOOKED.w 2 /
63//!HEIGHT HOOKED.h 2 /
64//!COMPONENTS 1
65
66vec4 hook() {
67 float tx = LINESOBEL_texOff(vec2(0.0, -0.5)).x;
68 float cx = LINESOBEL_tex(LINESOBEL_pos).x;
69 float bx = LINESOBEL_texOff(vec2(0.0, 0.5)).x;
70
71 float ty = LINESOBEL_texOff(vec2(0.0, -0.5)).y;
72 float by = LINESOBEL_texOff(vec2(0.0, 0.5)).y;
73
74 float xgrad = (tx + cx + cx + bx) / 8.0;
75
76 float ygrad = (-ty + by) / 8.0;
77
78 //Computes the luminance's gradient
79 float norm = sqrt(xgrad * xgrad + ygrad * ygrad);
80 return vec4(pow(norm, 0.7));
81}
82
83
84//!DESC Anime4K-v3.2-Thin-(Fast)-Gaussian-X
85//!HOOK MAIN
86//!BIND HOOKED
87//!BIND LINESOBEL
88//!SAVE LINESOBEL
89//!WIDTH HOOKED.w 2 /
90//!HEIGHT HOOKED.h 2 /
91//!COMPONENTS 1
92
93#define SPATIAL_SIGMA (1.0 * float(HOOKED_size.y) / 1080.0) //Spatial window size, must be a positive real number.
94
95#define KERNELSIZE (max(int(ceil(SPATIAL_SIGMA * 2.0)), 1) * 2 + 1) //Kernel size, must be an positive odd integer.
96#define KERNELHALFSIZE (int(KERNELSIZE/2)) //Half of the kernel size without remainder. Must be equal to trunc(KERNELSIZE/2).
97#define KERNELLEN (KERNELSIZE * KERNELSIZE) //Total area of kernel. Must be equal to KERNELSIZE * KERNELSIZE.
98
99float gaussian(float x, float s, float m) {
100 float scaled = (x - m) / s;
101 return exp(-0.5 * scaled * scaled);
102}
103
104float comp_gaussian_x() {
105
106 float g = 0.0;
107 float gn = 0.0;
108
109 for (int i=0; i<KERNELSIZE; i++) {
110 float di = float(i - KERNELHALFSIZE);
111 float gf = gaussian(di, SPATIAL_SIGMA, 0.0);
112
113 g = g + LINESOBEL_texOff(vec2(di, 0.0)).x * gf;
114 gn = gn + gf;
115
116 }
117
118 return g / gn;
119}
120
121vec4 hook() {
122 return vec4(comp_gaussian_x(), 0.0, 0.0, 0.0);
123}
124
125
126//!DESC Anime4K-v3.2-Thin-(Fast)-Gaussian-Y
127//!HOOK MAIN
128//!BIND HOOKED
129//!BIND LINESOBEL
130//!SAVE LINESOBEL
131//!WIDTH HOOKED.w 2 /
132//!HEIGHT HOOKED.h 2 /
133//!COMPONENTS 1
134
135#define SPATIAL_SIGMA (1.0 * float(HOOKED_size.y) / 1080.0) //Spatial window size, must be a positive real number.
136
137#define KERNELSIZE (max(int(ceil(SPATIAL_SIGMA * 2.0)), 1) * 2 + 1) //Kernel size, must be an positive odd integer.
138#define KERNELHALFSIZE (int(KERNELSIZE/2)) //Half of the kernel size without remainder. Must be equal to trunc(KERNELSIZE/2).
139#define KERNELLEN (KERNELSIZE * KERNELSIZE) //Total area of kernel. Must be equal to KERNELSIZE * KERNELSIZE.
140
141float gaussian(float x, float s, float m) {
142 float scaled = (x - m) / s;
143 return exp(-0.5 * scaled * scaled);
144}
145
146float comp_gaussian_y() {
147
148 float g = 0.0;
149 float gn = 0.0;
150
151 for (int i=0; i<KERNELSIZE; i++) {
152 float di = float(i - KERNELHALFSIZE);
153 float gf = gaussian(di, SPATIAL_SIGMA, 0.0);
154
155 g = g + LINESOBEL_texOff(vec2(0.0, di)).x * gf;
156 gn = gn + gf;
157
158 }
159
160 return g / gn;
161}
162
163vec4 hook() {
164 return vec4(comp_gaussian_y(), 0.0, 0.0, 0.0);
165}
166
167//!DESC Anime4K-v3.2-Thin-(Fast)-Kernel-X
168//!HOOK MAIN
169//!BIND LINESOBEL
170//!SAVE LINESOBEL
171//!WIDTH HOOKED.w 2 /
172//!HEIGHT HOOKED.h 2 /
173//!COMPONENTS 2
174
175vec4 hook() {
176 float l = LINESOBEL_texOff(vec2(-0.5, 0.0)).x;
177 float c = LINESOBEL_tex(LINESOBEL_pos).x;
178 float r = LINESOBEL_texOff(vec2(0.5, 0.0)).x;
179
180 float xgrad = (-l + r);
181 float ygrad = (l + c + c + r);
182
183 return vec4(xgrad, ygrad, 0.0, 0.0);
184}
185
186
187//!DESC Anime4K-v3.2-Thin-(Fast)-Kernel-Y
188//!HOOK MAIN
189//!BIND LINESOBEL
190//!SAVE LINESOBEL
191//!WIDTH HOOKED.w 2 /
192//!HEIGHT HOOKED.h 2 /
193//!COMPONENTS 2
194
195vec4 hook() {
196 float tx = LINESOBEL_texOff(vec2(0.0, -0.5)).x;
197 float cx = LINESOBEL_tex(LINESOBEL_pos).x;
198 float bx = LINESOBEL_texOff(vec2(0.0, 0.5)).x;
199
200 float ty = LINESOBEL_texOff(vec2(0.0, -0.5)).y;
201 float by = LINESOBEL_texOff(vec2(0.0, 0.5)).y;
202
203 float xgrad = (tx + cx + cx + bx) / 8.0;
204
205 float ygrad = (-ty + by) / 8.0;
206
207 //Computes the luminance's gradient
208 return vec4(xgrad, ygrad, 0.0, 0.0);
209}
210
211
212//!DESC Anime4K-v3.2-Thin-(Fast)-Warp
213//!HOOK MAIN
214//!BIND HOOKED
215//!BIND LINESOBEL
216
217#define STRENGTH 0.6 //Strength of warping for each iteration
218#define ITERATIONS 1 //Number of iterations for the forwards solver, decreasing strength and increasing iterations improves quality at the cost of speed.
219
220vec4 hook() {
221 vec2 d = HOOKED_pt;
222
223 float relstr = HOOKED_size.y / 1080.0 * STRENGTH;
224
225 vec2 pos = HOOKED_pos;
226 for (int i=0; i<ITERATIONS; i++) {
227 vec2 dn = LINESOBEL_tex(pos).xy;
228 vec2 dd = (dn / (length(dn) + 0.01)) * d * relstr; //Quasi-normalization for large vectors, avoids divide by zero
229 pos -= dd;
230 }
231
232 return HOOKED_tex(pos);
233
234}
1// MIT License
2
3// Copyright (c) 2019-2021 bloc97
4// All rights reserved.
5
6// Permission is hereby granted, free of charge, to any person obtaining a copy
7// of this software and associated documentation files (the "Software"), to deal
8// in the Software without restriction, including without limitation the rights
9// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10// copies of the Software, and to permit persons to whom the Software is
11// furnished to do so, subject to the following conditions:
13// The above copyright notice and this permission notice shall be included in all
14// copies or substantial portions of the Software.
16// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22// SOFTWARE.
24//!DESC Anime4K-v3.2-Thin-(Fast)-Luma
25//!HOOK MAIN
26//!BIND HOOKED
27//!SAVE LINELUMA
28//!COMPONENTS 1
30float get_luma(vec4 rgba) {
31 return dot(vec4(0.299, 0.587, 0.114, 0.0), rgba);
32}
34vec4 hook() {
35 return vec4(get_luma(HOOKED_tex(HOOKED_pos)), 0.0, 0.0, 0.0);
36}
38//!DESC Anime4K-v3.2-Thin-(Fast)-Sobel-X
39//!HOOK MAIN
40//!BIND LINELUMA
41//!SAVE LINESOBEL
42//!WIDTH HOOKED.w 2 /
43//!HEIGHT HOOKED.h 2 /
44//!COMPONENTS 2
46vec4 hook() {
47 float l = LINELUMA_texOff(vec2(-1.0, 0.0)).x;
48 float c = LINELUMA_tex(LINELUMA_pos).x;
49 float r = LINELUMA_texOff(vec2(1.0, 0.0)).x;
50
51 float xgrad = (-l + r);
52 float ygrad = (l + c + c + r);
53
54 return vec4(xgrad, ygrad, 0.0, 0.0);
55}
58//!DESC Anime4K-v3.2-Thin-(Fast)-Sobel-Y
59//!HOOK MAIN
60//!BIND LINESOBEL
61//!SAVE LINESOBEL
62//!WIDTH HOOKED.w 2 /
63//!HEIGHT HOOKED.h 2 /
64//!COMPONENTS 1
66vec4 hook() {
67 float tx = LINESOBEL_texOff(vec2(0.0, -0.5)).x;
68 float cx = LINESOBEL_tex(LINESOBEL_pos).x;
69 float bx = LINESOBEL_texOff(vec2(0.0, 0.5)).x;
70
71 float ty = LINESOBEL_texOff(vec2(0.0, -0.5)).y;
72 float by = LINESOBEL_texOff(vec2(0.0, 0.5)).y;
73
74 float xgrad = (tx + cx + cx + bx) / 8.0;
75
76 float ygrad = (-ty + by) / 8.0;
77
78 //Computes the luminance's gradient
79 float norm = sqrt(xgrad * xgrad + ygrad * ygrad);
80 return vec4(pow(norm, 0.7));
81}
84//!DESC Anime4K-v3.2-Thin-(Fast)-Gaussian-X
85//!HOOK MAIN
86//!BIND HOOKED
87//!BIND LINESOBEL
88//!SAVE LINESOBEL
89//!WIDTH HOOKED.w 2 /
90//!HEIGHT HOOKED.h 2 /
91//!COMPONENTS 1
93#define SPATIAL_SIGMA (1.0 * float(HOOKED_size.y) / 1080.0) //Spatial window size, must be a positive real number.
95#define KERNELSIZE (max(int(ceil(SPATIAL_SIGMA * 2.0)), 1) * 2 + 1) //Kernel size, must be an positive odd integer.
96#define KERNELHALFSIZE (int(KERNELSIZE/2)) //Half of the kernel size without remainder. Must be equal to trunc(KERNELSIZE/2).
97#define KERNELLEN (KERNELSIZE * KERNELSIZE) //Total area of kernel. Must be equal to KERNELSIZE * KERNELSIZE.
99float gaussian(float x, float s, float m) {
100 float scaled = (x - m) / s;
101 return exp(-0.5 * scaled * scaled);
102}
104float comp_gaussian_x() {
106 float g = 0.0;
107 float gn = 0.0;
108
109 for (int i=0; i<KERNELSIZE; i++) {
110 float di = float(i - KERNELHALFSIZE);
111 float gf = gaussian(di, SPATIAL_SIGMA, 0.0);
112
113 g = g + LINESOBEL_texOff(vec2(di, 0.0)).x * gf;
114 gn = gn + gf;
115
116 }
117
118 return g / gn;
119}
121vec4 hook() {
122 return vec4(comp_gaussian_x(), 0.0, 0.0, 0.0);
123}
126//!DESC Anime4K-v3.2-Thin-(Fast)-Gaussian-Y
127//!HOOK MAIN
128//!BIND HOOKED
129//!BIND LINESOBEL
130//!SAVE LINESOBEL
131//!WIDTH HOOKED.w 2 /
132//!HEIGHT HOOKED.h 2 /
133//!COMPONENTS 1
135#define SPATIAL_SIGMA (1.0 * float(HOOKED_size.y) / 1080.0) //Spatial window size, must be a positive real number.
137#define KERNELSIZE (max(int(ceil(SPATIAL_SIGMA * 2.0)), 1) * 2 + 1) //Kernel size, must be an positive odd integer.
138#define KERNELHALFSIZE (int(KERNELSIZE/2)) //Half of the kernel size without remainder. Must be equal to trunc(KERNELSIZE/2).
139#define KERNELLEN (KERNELSIZE * KERNELSIZE) //Total area of kernel. Must be equal to KERNELSIZE * KERNELSIZE.
141float gaussian(float x, float s, float m) {
142 float scaled = (x - m) / s;
143 return exp(-0.5 * scaled * scaled);
144}
146float comp_gaussian_y() {
148 float g = 0.0;
149 float gn = 0.0;
150
151 for (int i=0; i<KERNELSIZE; i++) {
152 float di = float(i - KERNELHALFSIZE);
153 float gf = gaussian(di, SPATIAL_SIGMA, 0.0);
154
155 g = g + LINESOBEL_texOff(vec2(0.0, di)).x * gf;
156 gn = gn + gf;
157
158 }
159
160 return g / gn;
161}
163vec4 hook() {
164 return vec4(comp_gaussian_y(), 0.0, 0.0, 0.0);
165}
167//!DESC Anime4K-v3.2-Thin-(Fast)-Kernel-X
168//!HOOK MAIN
169//!BIND LINESOBEL
170//!SAVE LINESOBEL
171//!WIDTH HOOKED.w 2 /
172//!HEIGHT HOOKED.h 2 /
173//!COMPONENTS 2
175vec4 hook() {
176 float l = LINESOBEL_texOff(vec2(-0.5, 0.0)).x;
177 float c = LINESOBEL_tex(LINESOBEL_pos).x;
178 float r = LINESOBEL_texOff(vec2(0.5, 0.0)).x;
179
180 float xgrad = (-l + r);
181 float ygrad = (l + c + c + r);
182
183 return vec4(xgrad, ygrad, 0.0, 0.0);
184}
187//!DESC Anime4K-v3.2-Thin-(Fast)-Kernel-Y
188//!HOOK MAIN
189//!BIND LINESOBEL
190//!SAVE LINESOBEL
191//!WIDTH HOOKED.w 2 /
192//!HEIGHT HOOKED.h 2 /
193//!COMPONENTS 2
195vec4 hook() {
196 float tx = LINESOBEL_texOff(vec2(0.0, -0.5)).x;
197 float cx = LINESOBEL_tex(LINESOBEL_pos).x;
198 float bx = LINESOBEL_texOff(vec2(0.0, 0.5)).x;
199
200 float ty = LINESOBEL_texOff(vec2(0.0, -0.5)).y;
201 float by = LINESOBEL_texOff(vec2(0.0, 0.5)).y;
202
203 float xgrad = (tx + cx + cx + bx) / 8.0;
204
205 float ygrad = (-ty + by) / 8.0;
206
207 //Computes the luminance's gradient
208 return vec4(xgrad, ygrad, 0.0, 0.0);
209}
212//!DESC Anime4K-v3.2-Thin-(Fast)-Warp
213//!HOOK MAIN
214//!BIND HOOKED
215//!BIND LINESOBEL
217#define STRENGTH 0.6 //Strength of warping for each iteration
218#define ITERATIONS 1 //Number of iterations for the forwards solver, decreasing strength and increasing iterations improves quality at the cost of speed.
220vec4 hook() {
221 vec2 d = HOOKED_pt;
222
223 float relstr = HOOKED_size.y / 1080.0 * STRENGTH;
224
225 vec2 pos = HOOKED_pos;
226 for (int i=0; i<ITERATIONS; i++) {
227 vec2 dn = LINESOBEL_tex(pos).xy;
228 vec2 dd = (dn / (length(dn) + 0.01)) * d * relstr; //Quasi-normalization for large vectors, avoids divide by zero
229 pos -= dd;
230 }
231
232 return HOOKED_tex(pos);
233
234}

mpv/shaders/Anime4K_Thin_HQ.glsl

Modified

+222 / −222 text lines

1// MIT License
2
3// Copyright (c) 2019-2021 bloc97
4// All rights reserved.
5
6// Permission is hereby granted, free of charge, to any person obtaining a copy
7// of this software and associated documentation files (the "Software"), to deal
8// in the Software without restriction, including without limitation the rights
9// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10// copies of the Software, and to permit persons to whom the Software is
11// furnished to do so, subject to the following conditions:
12
13// The above copyright notice and this permission notice shall be included in all
14// copies or substantial portions of the Software.
15
16// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22// SOFTWARE.
23
24//!DESC Anime4K-v3.2-Thin-(HQ)-Luma
25//!HOOK MAIN
26//!BIND HOOKED
27//!SAVE LINELUMA
28//!COMPONENTS 1
29
30float get_luma(vec4 rgba) {
31 return dot(vec4(0.299, 0.587, 0.114, 0.0), rgba);
32}
33
34vec4 hook() {
35 return vec4(get_luma(HOOKED_tex(HOOKED_pos)), 0.0, 0.0, 0.0);
36}
37
38//!DESC Anime4K-v3.2-Thin-(HQ)-Sobel-X
39//!HOOK MAIN
40//!BIND LINELUMA
41//!SAVE LINESOBEL
42//!COMPONENTS 2
43
44vec4 hook() {
45 float l = LINELUMA_texOff(vec2(-1.0, 0.0)).x;
46 float c = LINELUMA_tex(LINELUMA_pos).x;
47 float r = LINELUMA_texOff(vec2(1.0, 0.0)).x;
48
49 float xgrad = (-l + r);
50 float ygrad = (l + c + c + r);
51
52 return vec4(xgrad, ygrad, 0.0, 0.0);
53}
54
55
56//!DESC Anime4K-v3.2-Thin-(HQ)-Sobel-Y
57//!HOOK MAIN
58//!BIND LINESOBEL
59//!SAVE LINESOBEL
60//!COMPONENTS 1
61
62vec4 hook() {
63 float tx = LINESOBEL_texOff(vec2(0.0, -1.0)).x;
64 float cx = LINESOBEL_tex(LINESOBEL_pos).x;
65 float bx = LINESOBEL_texOff(vec2(0.0, 1.0)).x;
66
67 float ty = LINESOBEL_texOff(vec2(0.0, -1.0)).y;
68 float by = LINESOBEL_texOff(vec2(0.0, 1.0)).y;
69
70 float xgrad = (tx + cx + cx + bx) / 8.0;
71
72 float ygrad = (-ty + by) / 8.0;
73
74 //Computes the luminance's gradient
75 float norm = sqrt(xgrad * xgrad + ygrad * ygrad);
76 return vec4(pow(norm, 0.7));
77}
78
79
80//!DESC Anime4K-v3.2-Thin-(HQ)-Gaussian-X
81//!HOOK MAIN
82//!BIND HOOKED
83//!BIND LINESOBEL
84//!SAVE LINESOBEL
85//!COMPONENTS 1
86
87#define SPATIAL_SIGMA (2.0 * float(HOOKED_size.y) / 1080.0) //Spatial window size, must be a positive real number.
88
89#define KERNELSIZE (max(int(ceil(SPATIAL_SIGMA * 2.0)), 1) * 2 + 1) //Kernel size, must be an positive odd integer.
90#define KERNELHALFSIZE (int(KERNELSIZE/2)) //Half of the kernel size without remainder. Must be equal to trunc(KERNELSIZE/2).
91#define KERNELLEN (KERNELSIZE * KERNELSIZE) //Total area of kernel. Must be equal to KERNELSIZE * KERNELSIZE.
92
93float gaussian(float x, float s, float m) {
94 float scaled = (x - m) / s;
95 return exp(-0.5 * scaled * scaled);
96}
97
98float comp_gaussian_x() {
99
100 float g = 0.0;
101 float gn = 0.0;
102
103 for (int i=0; i<KERNELSIZE; i++) {
104 float di = float(i - KERNELHALFSIZE);
105 float gf = gaussian(di, SPATIAL_SIGMA, 0.0);
106
107 g = g + LINESOBEL_texOff(vec2(di, 0.0)).x * gf;
108 gn = gn + gf;
109
110 }
111
112 return g / gn;
113}
114
115vec4 hook() {
116 return vec4(comp_gaussian_x(), 0.0, 0.0, 0.0);
117}
118
119
120//!DESC Anime4K-v3.2-Thin-(HQ)-Gaussian-Y
121//!HOOK MAIN
122//!BIND HOOKED
123//!BIND LINESOBEL
124//!SAVE LINESOBEL
125//!COMPONENTS 1
126
127#define SPATIAL_SIGMA (2.0 * float(HOOKED_size.y) / 1080.0) //Spatial window size, must be a positive real number.
128
129#define KERNELSIZE (max(int(ceil(SPATIAL_SIGMA * 2.0)), 1) * 2 + 1) //Kernel size, must be an positive odd integer.
130#define KERNELHALFSIZE (int(KERNELSIZE/2)) //Half of the kernel size without remainder. Must be equal to trunc(KERNELSIZE/2).
131#define KERNELLEN (KERNELSIZE * KERNELSIZE) //Total area of kernel. Must be equal to KERNELSIZE * KERNELSIZE.
132
133float gaussian(float x, float s, float m) {
134 float scaled = (x - m) / s;
135 return exp(-0.5 * scaled * scaled);
136}
137
138float comp_gaussian_y() {
139
140 float g = 0.0;
141 float gn = 0.0;
142
143 for (int i=0; i<KERNELSIZE; i++) {
144 float di = float(i - KERNELHALFSIZE);
145 float gf = gaussian(di, SPATIAL_SIGMA, 0.0);
146
147 g = g + LINESOBEL_texOff(vec2(0.0, di)).x * gf;
148 gn = gn + gf;
149
150 }
151
152 return g / gn;
153}
154
155vec4 hook() {
156 return vec4(comp_gaussian_y(), 0.0, 0.0, 0.0);
157}
158
159//!DESC Anime4K-v3.2-Thin-(HQ)-Kernel-X
160//!HOOK MAIN
161//!BIND LINESOBEL
162//!SAVE LINESOBEL
163//!COMPONENTS 2
164
165vec4 hook() {
166 float l = LINESOBEL_texOff(vec2(-1.0, 0.0)).x;
167 float c = LINESOBEL_tex(LINESOBEL_pos).x;
168 float r = LINESOBEL_texOff(vec2(1.0, 0.0)).x;
169
170 float xgrad = (-l + r);
171 float ygrad = (l + c + c + r);
172
173 return vec4(xgrad, ygrad, 0.0, 0.0);
174}
175
176
177//!DESC Anime4K-v3.2-Thin-(HQ)-Kernel-Y
178//!HOOK MAIN
179//!BIND LINESOBEL
180//!SAVE LINESOBEL
181//!COMPONENTS 2
182
183vec4 hook() {
184 float tx = LINESOBEL_texOff(vec2(0.0, -1.0)).x;
185 float cx = LINESOBEL_tex(LINESOBEL_pos).x;
186 float bx = LINESOBEL_texOff(vec2(0.0, 1.0)).x;
187
188 float ty = LINESOBEL_texOff(vec2(0.0, -1.0)).y;
189 float by = LINESOBEL_texOff(vec2(0.0, 1.0)).y;
190
191 float xgrad = (tx + cx + cx + bx) / 8.0;
192
193 float ygrad = (-ty + by) / 8.0;
194
195 //Computes the luminance's gradient
196 return vec4(xgrad, ygrad, 0.0, 0.0);
197}
198
199
200//!DESC Anime4K-v3.2-Thin-(HQ)-Warp
201//!HOOK MAIN
202//!BIND HOOKED
203//!BIND LINESOBEL
204
205#define STRENGTH 0.6 //Strength of warping for each iteration
206#define ITERATIONS 1 //Number of iterations for the forwards solver, decreasing strength and increasing iterations improves quality at the cost of speed.
207
208vec4 hook() {
209 vec2 d = HOOKED_pt;
210
211 float relstr = HOOKED_size.y / 1080.0 * STRENGTH;
212
213 vec2 pos = HOOKED_pos;
214 for (int i=0; i<ITERATIONS; i++) {
215 vec2 dn = LINESOBEL_tex(pos).xy;
216 vec2 dd = (dn / (length(dn) + 0.01)) * d * relstr; //Quasi-normalization for large vectors, avoids divide by zero
217 pos -= dd;
218 }
219
220 return HOOKED_tex(pos);
221
222}
1// MIT License
2
3// Copyright (c) 2019-2021 bloc97
4// All rights reserved.
5
6// Permission is hereby granted, free of charge, to any person obtaining a copy
7// of this software and associated documentation files (the "Software"), to deal
8// in the Software without restriction, including without limitation the rights
9// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10// copies of the Software, and to permit persons to whom the Software is
11// furnished to do so, subject to the following conditions:
13// The above copyright notice and this permission notice shall be included in all
14// copies or substantial portions of the Software.
16// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22// SOFTWARE.
24//!DESC Anime4K-v3.2-Thin-(HQ)-Luma
25//!HOOK MAIN
26//!BIND HOOKED
27//!SAVE LINELUMA
28//!COMPONENTS 1
30float get_luma(vec4 rgba) {
31 return dot(vec4(0.299, 0.587, 0.114, 0.0), rgba);
32}
34vec4 hook() {
35 return vec4(get_luma(HOOKED_tex(HOOKED_pos)), 0.0, 0.0, 0.0);
36}
38//!DESC Anime4K-v3.2-Thin-(HQ)-Sobel-X
39//!HOOK MAIN
40//!BIND LINELUMA
41//!SAVE LINESOBEL
42//!COMPONENTS 2
44vec4 hook() {
45 float l = LINELUMA_texOff(vec2(-1.0, 0.0)).x;
46 float c = LINELUMA_tex(LINELUMA_pos).x;
47 float r = LINELUMA_texOff(vec2(1.0, 0.0)).x;
48
49 float xgrad = (-l + r);
50 float ygrad = (l + c + c + r);
51
52 return vec4(xgrad, ygrad, 0.0, 0.0);
53}
56//!DESC Anime4K-v3.2-Thin-(HQ)-Sobel-Y
57//!HOOK MAIN
58//!BIND LINESOBEL
59//!SAVE LINESOBEL
60//!COMPONENTS 1
62vec4 hook() {
63 float tx = LINESOBEL_texOff(vec2(0.0, -1.0)).x;
64 float cx = LINESOBEL_tex(LINESOBEL_pos).x;
65 float bx = LINESOBEL_texOff(vec2(0.0, 1.0)).x;
66
67 float ty = LINESOBEL_texOff(vec2(0.0, -1.0)).y;
68 float by = LINESOBEL_texOff(vec2(0.0, 1.0)).y;
69
70 float xgrad = (tx + cx + cx + bx) / 8.0;
71
72 float ygrad = (-ty + by) / 8.0;
73
74 //Computes the luminance's gradient
75 float norm = sqrt(xgrad * xgrad + ygrad * ygrad);
76 return vec4(pow(norm, 0.7));
77}
80//!DESC Anime4K-v3.2-Thin-(HQ)-Gaussian-X
81//!HOOK MAIN
82//!BIND HOOKED
83//!BIND LINESOBEL
84//!SAVE LINESOBEL
85//!COMPONENTS 1
87#define SPATIAL_SIGMA (2.0 * float(HOOKED_size.y) / 1080.0) //Spatial window size, must be a positive real number.
89#define KERNELSIZE (max(int(ceil(SPATIAL_SIGMA * 2.0)), 1) * 2 + 1) //Kernel size, must be an positive odd integer.
90#define KERNELHALFSIZE (int(KERNELSIZE/2)) //Half of the kernel size without remainder. Must be equal to trunc(KERNELSIZE/2).
91#define KERNELLEN (KERNELSIZE * KERNELSIZE) //Total area of kernel. Must be equal to KERNELSIZE * KERNELSIZE.
93float gaussian(float x, float s, float m) {
94 float scaled = (x - m) / s;
95 return exp(-0.5 * scaled * scaled);
96}
98float comp_gaussian_x() {
100 float g = 0.0;
101 float gn = 0.0;
102
103 for (int i=0; i<KERNELSIZE; i++) {
104 float di = float(i - KERNELHALFSIZE);
105 float gf = gaussian(di, SPATIAL_SIGMA, 0.0);
106
107 g = g + LINESOBEL_texOff(vec2(di, 0.0)).x * gf;
108 gn = gn + gf;
109
110 }
111
112 return g / gn;
113}
115vec4 hook() {
116 return vec4(comp_gaussian_x(), 0.0, 0.0, 0.0);
117}
120//!DESC Anime4K-v3.2-Thin-(HQ)-Gaussian-Y
121//!HOOK MAIN
122//!BIND HOOKED
123//!BIND LINESOBEL
124//!SAVE LINESOBEL
125//!COMPONENTS 1
127#define SPATIAL_SIGMA (2.0 * float(HOOKED_size.y) / 1080.0) //Spatial window size, must be a positive real number.
129#define KERNELSIZE (max(int(ceil(SPATIAL_SIGMA * 2.0)), 1) * 2 + 1) //Kernel size, must be an positive odd integer.
130#define KERNELHALFSIZE (int(KERNELSIZE/2)) //Half of the kernel size without remainder. Must be equal to trunc(KERNELSIZE/2).
131#define KERNELLEN (KERNELSIZE * KERNELSIZE) //Total area of kernel. Must be equal to KERNELSIZE * KERNELSIZE.
133float gaussian(float x, float s, float m) {
134 float scaled = (x - m) / s;
135 return exp(-0.5 * scaled * scaled);
136}
138float comp_gaussian_y() {
140 float g = 0.0;
141 float gn = 0.0;
142
143 for (int i=0; i<KERNELSIZE; i++) {
144 float di = float(i - KERNELHALFSIZE);
145 float gf = gaussian(di, SPATIAL_SIGMA, 0.0);
146
147 g = g + LINESOBEL_texOff(vec2(0.0, di)).x * gf;
148 gn = gn + gf;
149
150 }
151
152 return g / gn;
153}
155vec4 hook() {
156 return vec4(comp_gaussian_y(), 0.0, 0.0, 0.0);
157}
159//!DESC Anime4K-v3.2-Thin-(HQ)-Kernel-X
160//!HOOK MAIN
161//!BIND LINESOBEL
162//!SAVE LINESOBEL
163//!COMPONENTS 2
165vec4 hook() {
166 float l = LINESOBEL_texOff(vec2(-1.0, 0.0)).x;
167 float c = LINESOBEL_tex(LINESOBEL_pos).x;
168 float r = LINESOBEL_texOff(vec2(1.0, 0.0)).x;
169
170 float xgrad = (-l + r);
171 float ygrad = (l + c + c + r);
172
173 return vec4(xgrad, ygrad, 0.0, 0.0);
174}
177//!DESC Anime4K-v3.2-Thin-(HQ)-Kernel-Y
178//!HOOK MAIN
179//!BIND LINESOBEL
180//!SAVE LINESOBEL
181//!COMPONENTS 2
183vec4 hook() {
184 float tx = LINESOBEL_texOff(vec2(0.0, -1.0)).x;
185 float cx = LINESOBEL_tex(LINESOBEL_pos).x;
186 float bx = LINESOBEL_texOff(vec2(0.0, 1.0)).x;
187
188 float ty = LINESOBEL_texOff(vec2(0.0, -1.0)).y;
189 float by = LINESOBEL_texOff(vec2(0.0, 1.0)).y;
190
191 float xgrad = (tx + cx + cx + bx) / 8.0;
192
193 float ygrad = (-ty + by) / 8.0;
194
195 //Computes the luminance's gradient
196 return vec4(xgrad, ygrad, 0.0, 0.0);
197}
200//!DESC Anime4K-v3.2-Thin-(HQ)-Warp
201//!HOOK MAIN
202//!BIND HOOKED
203//!BIND LINESOBEL
205#define STRENGTH 0.6 //Strength of warping for each iteration
206#define ITERATIONS 1 //Number of iterations for the forwards solver, decreasing strength and increasing iterations improves quality at the cost of speed.
208vec4 hook() {
209 vec2 d = HOOKED_pt;
210
211 float relstr = HOOKED_size.y / 1080.0 * STRENGTH;
212
213 vec2 pos = HOOKED_pos;
214 for (int i=0; i<ITERATIONS; i++) {
215 vec2 dn = LINESOBEL_tex(pos).xy;
216 vec2 dd = (dn / (length(dn) + 0.01)) * d * relstr; //Quasi-normalization for large vectors, avoids divide by zero
217 pos -= dd;
218 }
219
220 return HOOKED_tex(pos);
221
222}

mpv/shaders/Anime4K_Thin_VeryFast.glsl

Modified

+236 / −236 text lines

1// MIT License
2
3// Copyright (c) 2019-2021 bloc97
4// All rights reserved.
5
6// Permission is hereby granted, free of charge, to any person obtaining a copy
7// of this software and associated documentation files (the "Software"), to deal
8// in the Software without restriction, including without limitation the rights
9// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10// copies of the Software, and to permit persons to whom the Software is
11// furnished to do so, subject to the following conditions:
12
13// The above copyright notice and this permission notice shall be included in all
14// copies or substantial portions of the Software.
15
16// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22// SOFTWARE.
23
24//!DESC Anime4K-v3.2-Thin-(VeryFast)-Luma
25//!HOOK MAIN
26//!BIND HOOKED
27//!SAVE LINELUMA
28//!WIDTH HOOKED.w 2 /
29//!HEIGHT HOOKED.h 2 /
30//!COMPONENTS 1
31
32float get_luma(vec4 rgba) {
33 return dot(vec4(0.299, 0.587, 0.114, 0.0), rgba);
34}
35
36vec4 hook() {
37 return vec4(get_luma(HOOKED_tex(HOOKED_pos)), 0.0, 0.0, 0.0);
38}
39
40//!DESC Anime4K-v3.2-Thin-(VeryFast)-Sobel-X
41//!HOOK MAIN
42//!BIND LINELUMA
43//!SAVE LINESOBEL
44//!WIDTH HOOKED.w 4 /
45//!HEIGHT HOOKED.h 4 /
46//!COMPONENTS 2
47
48vec4 hook() {
49 float l = LINELUMA_texOff(vec2(-0.5, 0.0)).x;
50 float c = LINELUMA_tex(LINELUMA_pos).x;
51 float r = LINELUMA_texOff(vec2(0.5, 0.0)).x;
52
53 float xgrad = (-l + r);
54 float ygrad = (l + c + c + r);
55
56 return vec4(xgrad, ygrad, 0.0, 0.0);
57}
58
59
60//!DESC Anime4K-v3.2-Thin-(VeryFast)-Sobel-Y
61//!HOOK MAIN
62//!BIND LINESOBEL
63//!SAVE LINESOBEL
64//!WIDTH HOOKED.w 4 /
65//!HEIGHT HOOKED.h 4 /
66//!COMPONENTS 1
67
68vec4 hook() {
69 float tx = LINESOBEL_texOff(vec2(0.0, -0.25)).x;
70 float cx = LINESOBEL_tex(LINESOBEL_pos).x;
71 float bx = LINESOBEL_texOff(vec2(0.0, 0.25)).x;
72
73 float ty = LINESOBEL_texOff(vec2(0.0, -0.25)).y;
74 float by = LINESOBEL_texOff(vec2(0.0, 0.25)).y;
75
76 float xgrad = (tx + cx + cx + bx) / 8.0;
77
78 float ygrad = (-ty + by) / 8.0;
79
80 //Computes the luminance's gradient
81 float norm = sqrt(xgrad * xgrad + ygrad * ygrad);
82 return vec4(pow(norm, 0.7));
83}
84
85
86//!DESC Anime4K-v3.2-Thin-(VeryFast)-Gaussian-X
87//!HOOK MAIN
88//!BIND HOOKED
89//!BIND LINESOBEL
90//!SAVE LINESOBEL
91//!WIDTH HOOKED.w 4 /
92//!HEIGHT HOOKED.h 4 /
93//!COMPONENTS 1
94
95#define SPATIAL_SIGMA (0.5 * float(HOOKED_size.y) / 1080.0) //Spatial window size, must be a positive real number.
96
97#define KERNELSIZE (max(int(ceil(SPATIAL_SIGMA * 2.0)), 1) * 2 + 1) //Kernel size, must be an positive odd integer.
98#define KERNELHALFSIZE (int(KERNELSIZE/2)) //Half of the kernel size without remainder. Must be equal to trunc(KERNELSIZE/2).
99#define KERNELLEN (KERNELSIZE * KERNELSIZE) //Total area of kernel. Must be equal to KERNELSIZE * KERNELSIZE.
100
101float gaussian(float x, float s, float m) {
102 float scaled = (x - m) / s;
103 return exp(-0.5 * scaled * scaled);
104}
105
106float comp_gaussian_x() {
107
108 float g = 0.0;
109 float gn = 0.0;
110
111 for (int i=0; i<KERNELSIZE; i++) {
112 float di = float(i - KERNELHALFSIZE);
113 float gf = gaussian(di, SPATIAL_SIGMA, 0.0);
114
115 g = g + LINESOBEL_texOff(vec2(di, 0.0)).x * gf;
116 gn = gn + gf;
117
118 }
119
120 return g / gn;
121}
122
123vec4 hook() {
124 return vec4(comp_gaussian_x(), 0.0, 0.0, 0.0);
125}
126
127
128//!DESC Anime4K-v3.2-Thin-(VeryFast)-Gaussian-Y
129//!HOOK MAIN
130//!BIND HOOKED
131//!BIND LINESOBEL
132//!SAVE LINESOBEL
133//!WIDTH HOOKED.w 4 /
134//!HEIGHT HOOKED.h 4 /
135//!COMPONENTS 1
136
137#define SPATIAL_SIGMA (0.5 * float(HOOKED_size.y) / 1080.0) //Spatial window size, must be a positive real number.
138
139#define KERNELSIZE (max(int(ceil(SPATIAL_SIGMA * 2.0)), 1) * 2 + 1) //Kernel size, must be an positive odd integer.
140#define KERNELHALFSIZE (int(KERNELSIZE/2)) //Half of the kernel size without remainder. Must be equal to trunc(KERNELSIZE/2).
141#define KERNELLEN (KERNELSIZE * KERNELSIZE) //Total area of kernel. Must be equal to KERNELSIZE * KERNELSIZE.
142
143float gaussian(float x, float s, float m) {
144 float scaled = (x - m) / s;
145 return exp(-0.5 * scaled * scaled);
146}
147
148float comp_gaussian_y() {
149
150 float g = 0.0;
151 float gn = 0.0;
152
153 for (int i=0; i<KERNELSIZE; i++) {
154 float di = float(i - KERNELHALFSIZE);
155 float gf = gaussian(di, SPATIAL_SIGMA, 0.0);
156
157 g = g + LINESOBEL_texOff(vec2(0.0, di)).x * gf;
158 gn = gn + gf;
159
160 }
161
162 return g / gn;
163}
164
165vec4 hook() {
166 return vec4(comp_gaussian_y(), 0.0, 0.0, 0.0);
167}
168
169//!DESC Anime4K-v3.2-Thin-(VeryFast)-Kernel-X
170//!HOOK MAIN
171//!BIND LINESOBEL
172//!SAVE LINESOBEL
173//!WIDTH HOOKED.w 4 /
174//!HEIGHT HOOKED.h 4 /
175//!COMPONENTS 2
176
177vec4 hook() {
178 float l = LINESOBEL_texOff(vec2(-0.25, 0.0)).x;
179 float c = LINESOBEL_tex(LINESOBEL_pos).x;
180 float r = LINESOBEL_texOff(vec2(0.25, 0.0)).x;
181
182 float xgrad = (-l + r);
183 float ygrad = (l + c + c + r);
184
185 return vec4(xgrad, ygrad, 0.0, 0.0);
186}
187
188
189//!DESC Anime4K-v3.2-Thin-(VeryFast)-Kernel-Y
190//!HOOK MAIN
191//!BIND LINESOBEL
192//!SAVE LINESOBEL
193//!WIDTH HOOKED.w 4 /
194//!HEIGHT HOOKED.h 4 /
195//!COMPONENTS 2
196
197vec4 hook() {
198 float tx = LINESOBEL_texOff(vec2(0.0, -0.25)).x;
199 float cx = LINESOBEL_tex(LINESOBEL_pos).x;
200 float bx = LINESOBEL_texOff(vec2(0.0, 0.25)).x;
201
202 float ty = LINESOBEL_texOff(vec2(0.0, -0.25)).y;
203 float by = LINESOBEL_texOff(vec2(0.0, 0.25)).y;
204
205 float xgrad = (tx + cx + cx + bx) / 8.0;
206
207 float ygrad = (-ty + by) / 8.0;
208
209 //Computes the luminance's gradient
210 return vec4(xgrad, ygrad, 0.0, 0.0);
211}
212
213
214//!DESC Anime4K-v3.2-Thin-(VeryFast)-Warp
215//!HOOK MAIN
216//!BIND HOOKED
217//!BIND LINESOBEL
218
219#define STRENGTH 0.6 //Strength of warping for each iteration
220#define ITERATIONS 1 //Number of iterations for the forwards solver, decreasing strength and increasing iterations improves quality at the cost of speed.
221
222vec4 hook() {
223 vec2 d = HOOKED_pt;
224
225 float relstr = HOOKED_size.y / 1080.0 * STRENGTH;
226
227 vec2 pos = HOOKED_pos;
228 for (int i=0; i<ITERATIONS; i++) {
229 vec2 dn = LINESOBEL_tex(pos).xy;
230 vec2 dd = (dn / (length(dn) + 0.01)) * d * relstr; //Quasi-normalization for large vectors, avoids divide by zero
231 pos -= dd;
232 }
233
234 return HOOKED_tex(pos);
235
236}
1// MIT License
2
3// Copyright (c) 2019-2021 bloc97
4// All rights reserved.
5
6// Permission is hereby granted, free of charge, to any person obtaining a copy
7// of this software and associated documentation files (the "Software"), to deal
8// in the Software without restriction, including without limitation the rights
9// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10// copies of the Software, and to permit persons to whom the Software is
11// furnished to do so, subject to the following conditions:
13// The above copyright notice and this permission notice shall be included in all
14// copies or substantial portions of the Software.
16// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22// SOFTWARE.
24//!DESC Anime4K-v3.2-Thin-(VeryFast)-Luma
25//!HOOK MAIN
26//!BIND HOOKED
27//!SAVE LINELUMA
28//!WIDTH HOOKED.w 2 /
29//!HEIGHT HOOKED.h 2 /
30//!COMPONENTS 1
32float get_luma(vec4 rgba) {
33 return dot(vec4(0.299, 0.587, 0.114, 0.0), rgba);
34}
36vec4 hook() {
37 return vec4(get_luma(HOOKED_tex(HOOKED_pos)), 0.0, 0.0, 0.0);
38}
40//!DESC Anime4K-v3.2-Thin-(VeryFast)-Sobel-X
41//!HOOK MAIN
42//!BIND LINELUMA
43//!SAVE LINESOBEL
44//!WIDTH HOOKED.w 4 /
45//!HEIGHT HOOKED.h 4 /
46//!COMPONENTS 2
48vec4 hook() {
49 float l = LINELUMA_texOff(vec2(-0.5, 0.0)).x;
50 float c = LINELUMA_tex(LINELUMA_pos).x;
51 float r = LINELUMA_texOff(vec2(0.5, 0.0)).x;
52
53 float xgrad = (-l + r);
54 float ygrad = (l + c + c + r);
55
56 return vec4(xgrad, ygrad, 0.0, 0.0);
57}
60//!DESC Anime4K-v3.2-Thin-(VeryFast)-Sobel-Y
61//!HOOK MAIN
62//!BIND LINESOBEL
63//!SAVE LINESOBEL
64//!WIDTH HOOKED.w 4 /
65//!HEIGHT HOOKED.h 4 /
66//!COMPONENTS 1
68vec4 hook() {
69 float tx = LINESOBEL_texOff(vec2(0.0, -0.25)).x;
70 float cx = LINESOBEL_tex(LINESOBEL_pos).x;
71 float bx = LINESOBEL_texOff(vec2(0.0, 0.25)).x;
72
73 float ty = LINESOBEL_texOff(vec2(0.0, -0.25)).y;
74 float by = LINESOBEL_texOff(vec2(0.0, 0.25)).y;
75
76 float xgrad = (tx + cx + cx + bx) / 8.0;
77
78 float ygrad = (-ty + by) / 8.0;
79
80 //Computes the luminance's gradient
81 float norm = sqrt(xgrad * xgrad + ygrad * ygrad);
82 return vec4(pow(norm, 0.7));
83}
86//!DESC Anime4K-v3.2-Thin-(VeryFast)-Gaussian-X
87//!HOOK MAIN
88//!BIND HOOKED
89//!BIND LINESOBEL
90//!SAVE LINESOBEL
91//!WIDTH HOOKED.w 4 /
92//!HEIGHT HOOKED.h 4 /
93//!COMPONENTS 1
95#define SPATIAL_SIGMA (0.5 * float(HOOKED_size.y) / 1080.0) //Spatial window size, must be a positive real number.
97#define KERNELSIZE (max(int(ceil(SPATIAL_SIGMA * 2.0)), 1) * 2 + 1) //Kernel size, must be an positive odd integer.
98#define KERNELHALFSIZE (int(KERNELSIZE/2)) //Half of the kernel size without remainder. Must be equal to trunc(KERNELSIZE/2).
99#define KERNELLEN (KERNELSIZE * KERNELSIZE) //Total area of kernel. Must be equal to KERNELSIZE * KERNELSIZE.
101float gaussian(float x, float s, float m) {
102 float scaled = (x - m) / s;
103 return exp(-0.5 * scaled * scaled);
104}
106float comp_gaussian_x() {
108 float g = 0.0;
109 float gn = 0.0;
110
111 for (int i=0; i<KERNELSIZE; i++) {
112 float di = float(i - KERNELHALFSIZE);
113 float gf = gaussian(di, SPATIAL_SIGMA, 0.0);
114
115 g = g + LINESOBEL_texOff(vec2(di, 0.0)).x * gf;
116 gn = gn + gf;
117
118 }
119
120 return g / gn;
121}
123vec4 hook() {
124 return vec4(comp_gaussian_x(), 0.0, 0.0, 0.0);
125}
128//!DESC Anime4K-v3.2-Thin-(VeryFast)-Gaussian-Y
129//!HOOK MAIN
130//!BIND HOOKED
131//!BIND LINESOBEL
132//!SAVE LINESOBEL
133//!WIDTH HOOKED.w 4 /
134//!HEIGHT HOOKED.h 4 /
135//!COMPONENTS 1
137#define SPATIAL_SIGMA (0.5 * float(HOOKED_size.y) / 1080.0) //Spatial window size, must be a positive real number.
139#define KERNELSIZE (max(int(ceil(SPATIAL_SIGMA * 2.0)), 1) * 2 + 1) //Kernel size, must be an positive odd integer.
140#define KERNELHALFSIZE (int(KERNELSIZE/2)) //Half of the kernel size without remainder. Must be equal to trunc(KERNELSIZE/2).
141#define KERNELLEN (KERNELSIZE * KERNELSIZE) //Total area of kernel. Must be equal to KERNELSIZE * KERNELSIZE.
143float gaussian(float x, float s, float m) {
144 float scaled = (x - m) / s;
145 return exp(-0.5 * scaled * scaled);
146}
148float comp_gaussian_y() {
150 float g = 0.0;
151 float gn = 0.0;
152
153 for (int i=0; i<KERNELSIZE; i++) {
154 float di = float(i - KERNELHALFSIZE);
155 float gf = gaussian(di, SPATIAL_SIGMA, 0.0);
156
157 g = g + LINESOBEL_texOff(vec2(0.0, di)).x * gf;
158 gn = gn + gf;
159
160 }
161
162 return g / gn;
163}
165vec4 hook() {
166 return vec4(comp_gaussian_y(), 0.0, 0.0, 0.0);
167}
169//!DESC Anime4K-v3.2-Thin-(VeryFast)-Kernel-X
170//!HOOK MAIN
171//!BIND LINESOBEL
172//!SAVE LINESOBEL
173//!WIDTH HOOKED.w 4 /
174//!HEIGHT HOOKED.h 4 /
175//!COMPONENTS 2
177vec4 hook() {
178 float l = LINESOBEL_texOff(vec2(-0.25, 0.0)).x;
179 float c = LINESOBEL_tex(LINESOBEL_pos).x;
180 float r = LINESOBEL_texOff(vec2(0.25, 0.0)).x;
181
182 float xgrad = (-l + r);
183 float ygrad = (l + c + c + r);
184
185 return vec4(xgrad, ygrad, 0.0, 0.0);
186}
189//!DESC Anime4K-v3.2-Thin-(VeryFast)-Kernel-Y
190//!HOOK MAIN
191//!BIND LINESOBEL
192//!SAVE LINESOBEL
193//!WIDTH HOOKED.w 4 /
194//!HEIGHT HOOKED.h 4 /
195//!COMPONENTS 2
197vec4 hook() {
198 float tx = LINESOBEL_texOff(vec2(0.0, -0.25)).x;
199 float cx = LINESOBEL_tex(LINESOBEL_pos).x;
200 float bx = LINESOBEL_texOff(vec2(0.0, 0.25)).x;
201
202 float ty = LINESOBEL_texOff(vec2(0.0, -0.25)).y;
203 float by = LINESOBEL_texOff(vec2(0.0, 0.25)).y;
204
205 float xgrad = (tx + cx + cx + bx) / 8.0;
206
207 float ygrad = (-ty + by) / 8.0;
208
209 //Computes the luminance's gradient
210 return vec4(xgrad, ygrad, 0.0, 0.0);
211}
214//!DESC Anime4K-v3.2-Thin-(VeryFast)-Warp
215//!HOOK MAIN
216//!BIND HOOKED
217//!BIND LINESOBEL
219#define STRENGTH 0.6 //Strength of warping for each iteration
220#define ITERATIONS 1 //Number of iterations for the forwards solver, decreasing strength and increasing iterations improves quality at the cost of speed.
222vec4 hook() {
223 vec2 d = HOOKED_pt;
224
225 float relstr = HOOKED_size.y / 1080.0 * STRENGTH;
226
227 vec2 pos = HOOKED_pos;
228 for (int i=0; i<ITERATIONS; i++) {
229 vec2 dn = LINESOBEL_tex(pos).xy;
230 vec2 dd = (dn / (length(dn) + 0.01)) * d * relstr; //Quasi-normalization for large vectors, avoids divide by zero
231 pos -= dd;
232 }
233
234 return HOOKED_tex(pos);
235
236}

mpv/shaders/Anime4K_Upscale_DTD_x2.glsl

Modified

+613 / −613 text lines

1// MIT License
2
3// Copyright (c) 2019-2021 bloc97
4// All rights reserved.
5
6// Permission is hereby granted, free of charge, to any person obtaining a copy
7// of this software and associated documentation files (the "Software"), to deal
8// in the Software without restriction, including without limitation the rights
9// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10// copies of the Software, and to permit persons to whom the Software is
11// furnished to do so, subject to the following conditions:
12
13// The above copyright notice and this permission notice shall be included in all
14// copies or substantial portions of the Software.
15
16// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22// SOFTWARE.
23
24//!DESC Anime4K-v3.2-Upscale-DTD-x2-Luma
25//!HOOK MAIN
26//!BIND HOOKED
27//!SAVE LINELUMA
28//!COMPONENTS 1
29
30float get_luma(vec4 rgba) {
31 return dot(vec4(0.299, 0.587, 0.114, 0.0), rgba);
32}
33
34vec4 hook() {
35 return vec4(get_luma(HOOKED_tex(HOOKED_pos)), 0.0, 0.0, 0.0);
36}
37
38//!DESC Anime4K-v3.2-Upscale-DTD-x2-Kernel-X
39//!WHEN OUTPUT.w MAIN.w / 1.200 > OUTPUT.h MAIN.h / 1.200 > *
40//!HOOK MAIN
41//!BIND HOOKED
42//!BIND LINELUMA
43//!SAVE MMKERNEL
44//!COMPONENTS 1
45
46#define L_tex LINELUMA_tex
47
48#define SIGMA 1.0
49
50float gaussian(float x, float s, float m) {
51 return (1.0 / (s * sqrt(2.0 * 3.14159))) * exp(-0.5 * pow(abs(x - m) / s, 2.0));
52}
53
54float lumGaussian(vec2 pos, vec2 d) {
55 float s = SIGMA * HOOKED_size.y / 1080.0;
56 float kernel_size = s * 2.0 + 1.0;
57
58 float g = (L_tex(pos).x) * gaussian(0.0, s, 0.0);
59 float gn = gaussian(0.0, s, 0.0);
60
61 g += (L_tex(pos - d).x + L_tex(pos + d).x) * gaussian(1.0, s, 0.0);
62 gn += gaussian(1.0, s, 0.0) * 2.0;
63
64 for (int i=2; float(i)<kernel_size; i++) {
65 g += (L_tex(pos - (d * float(i))).x + L_tex(pos + (d * float(i))).x) * gaussian(float(i), s, 0.0);
66 gn += gaussian(float(i), s, 0.0) * 2.0;
67 }
68
69 return g / gn;
70}
71
72vec4 hook() {
73 return vec4(lumGaussian(HOOKED_pos, vec2(HOOKED_pt.x, 0)));
74}
75
76//!DESC Anime4K-v3.2-Upscale-DTD-x2-Kernel-Y
77//!WHEN OUTPUT.w MAIN.w / 1.200 > OUTPUT.h MAIN.h / 1.200 > *
78//!HOOK MAIN
79//!BIND HOOKED
80//!BIND LINELUMA
81//!BIND MMKERNEL
82//!SAVE MMKERNEL
83//!COMPONENTS 1
84
85#define L_tex MMKERNEL_tex
86
87#define SIGMA 1.0
88
89float gaussian(float x, float s, float m) {
90 return (1.0 / (s * sqrt(2.0 * 3.14159))) * exp(-0.5 * pow(abs(x - m) / s, 2.0));
91}
92
93float lumGaussian(vec2 pos, vec2 d) {
94 float s = SIGMA * HOOKED_size.y / 1080.0;
95 float kernel_size = s * 2.0 + 1.0;
96
97 float g = (L_tex(pos).x) * gaussian(0.0, s, 0.0);
98 float gn = gaussian(0.0, s, 0.0);
99
100 g += (L_tex(pos - d).x + L_tex(pos + d).x) * gaussian(1.0, s, 0.0);
101 gn += gaussian(1.0, s, 0.0) * 2.0;
102
103 for (int i=2; float(i)<kernel_size; i++) {
104 g += (L_tex(pos - (d * float(i))).x + L_tex(pos + (d * float(i))).x) * gaussian(float(i), s, 0.0);
105 gn += gaussian(float(i), s, 0.0) * 2.0;
106 }
107
108 return g / gn;
109}
110
111vec4 hook() {
112 return vec4(min(LINELUMA_tex(HOOKED_pos).x - lumGaussian(HOOKED_pos, vec2(0, HOOKED_pt.y)), 0.0));
113}
114
115//!DESC Anime4K-v3.2-Upscale-DTD-x2-Kernel-X
116//!WHEN OUTPUT.w MAIN.w / 1.200 > OUTPUT.h MAIN.h / 1.200 > *
117//!HOOK MAIN
118//!BIND HOOKED
119//!BIND MMKERNEL
120//!SAVE MMKERNEL
121//!COMPONENTS 1
122
123#define L_tex MMKERNEL_tex
124
125#define SIGMA 0.4
126
127float gaussian(float x, float s, float m) {
128 return (1.0 / (s * sqrt(2.0 * 3.14159))) * exp(-0.5 * pow(abs(x - m) / s, 2.0));
129}
130
131float lumGaussian(vec2 pos, vec2 d) {
132 float s = SIGMA * HOOKED_size.y / 1080.0;
133 float kernel_size = s * 2.0 + 1.0;
134
135 float g = (L_tex(pos).x) * gaussian(0.0, s, 0.0);
136 float gn = gaussian(0.0, s, 0.0);
137
138 g += (L_tex(pos - d).x + L_tex(pos + d).x) * gaussian(1.0, s, 0.0);
139 gn += gaussian(1.0, s, 0.0) * 2.0;
140
141 for (int i=2; float(i)<kernel_size; i++) {
142 g += (L_tex(pos - (d * float(i))).x + L_tex(pos + (d * float(i))).x) * gaussian(float(i), s, 0.0);
143 gn += gaussian(float(i), s, 0.0) * 2.0;
144 }
145
146 return g / gn;
147}
148
149vec4 hook() {
150 return vec4(lumGaussian(HOOKED_pos, vec2(HOOKED_pt.x, 0)));
151}
152
153//!DESC Anime4K-v3.2-Upscale-DTD-x2-Kernel-Y
154//!WHEN OUTPUT.w MAIN.w / 1.200 > OUTPUT.h MAIN.h / 1.200 > *
155//!HOOK MAIN
156//!BIND HOOKED
157//!BIND MMKERNEL
158//!SAVE MMKERNEL
159//!COMPONENTS 1
160
161#define L_tex MMKERNEL_tex
162
163#define SIGMA 0.4
164
165float gaussian(float x, float s, float m) {
166 return (1.0 / (s * sqrt(2.0 * 3.14159))) * exp(-0.5 * pow(abs(x - m) / s, 2.0));
167}
168
169float lumGaussian(vec2 pos, vec2 d) {
170 float s = SIGMA * HOOKED_size.y / 1080.0;
171 float kernel_size = s * 2.0 + 1.0;
172
173 float g = (L_tex(pos).x) * gaussian(0.0, s, 0.0);
174 float gn = gaussian(0.0, s, 0.0);
175
176 g += (L_tex(pos - d).x + L_tex(pos + d).x) * gaussian(1.0, s, 0.0);
177 gn += gaussian(1.0, s, 0.0) * 2.0;
178
179 for (int i=2; float(i)<kernel_size; i++) {
180 g += (L_tex(pos - (d * float(i))).x + L_tex(pos + (d * float(i))).x) * gaussian(float(i), s, 0.0);
181 gn += gaussian(float(i), s, 0.0) * 2.0;
182 }
183
184 return g / gn;
185}
186
187vec4 hook() {
188 return vec4(lumGaussian(HOOKED_pos, vec2(0, HOOKED_pt.y)));
189}
190
191//!DESC Anime4K-v3.2-Upscale-DTD-x2
192//!WHEN OUTPUT.w MAIN.w / 1.200 > OUTPUT.h MAIN.h / 1.200 > *
193//!HOOK MAIN
194//!BIND HOOKED
195//!BIND MMKERNEL
196
197#define STRENGTH 1.8 //Line darken proportional strength, higher is darker.
198
199vec4 hook() {
200 float c = (MMKERNEL_tex(HOOKED_pos).x) * STRENGTH;
201 //This trick is only possible if the inverse Y->RGB matrix has 1 for every row... (which is the case for BT.709)
202 //Otherwise we would need to convert RGB to YUV, modify Y then convert back to RGB.
203 return HOOKED_tex(HOOKED_pos) + c;
204}
205
206//!DESC Anime4K-v3.2-Upscale-DTD-x2-Luma
207//!HOOK MAIN
208//!BIND HOOKED
209//!SAVE LINELUMA
210//!COMPONENTS 1
211
212float get_luma(vec4 rgba) {
213 return dot(vec4(0.299, 0.587, 0.114, 0.0), rgba);
214}
215
216vec4 hook() {
217 return vec4(get_luma(HOOKED_tex(HOOKED_pos)), 0.0, 0.0, 0.0);
218}
219
220//!DESC Anime4K-v3.2-Upscale-DTD-x2-Kernel-X
221//!WHEN OUTPUT.w MAIN.w / 1.200 > OUTPUT.h MAIN.h / 1.200 > *
222//!HOOK MAIN
223//!BIND HOOKED
224//!BIND LINELUMA
225//!SAVE LUMAD
226//!COMPONENTS 2
227
228#define L_tex LINELUMA_tex
229
230vec4 hook() {
231 vec2 d = HOOKED_pt;
232
233 //[tl t tr]
234 //[ l c r]
235 //[bl b br]
236 float l = L_tex(HOOKED_pos + vec2(-d.x, 0)).x;
237 float c = L_tex(HOOKED_pos).x;
238 float r = L_tex(HOOKED_pos + vec2(d.x, 0)).x;
239
240
241 //Horizontal Gradient
242 //[-1 0 1]
243 //[-2 0 2]
244 //[-1 0 1]
245 float xgrad = (-l + r);
246
247 //Vertical Gradient
248 //[-1 -2 -1]
249 //[ 0 0 0]
250 //[ 1 2 1]
251 float ygrad = (l + c + c + r);
252
253 //Computes the luminance's gradient
254 return vec4(xgrad, ygrad, 0, 0);
255}
256
257
258//!DESC Anime4K-v3.2-Upscale-DTD-x2-Kernel-Y
259//!WHEN OUTPUT.w MAIN.w / 1.200 > OUTPUT.h MAIN.h / 1.200 > *
260//!HOOK MAIN
261//!BIND HOOKED
262//!BIND LUMAD
263//!SAVE LUMAD
264//!COMPONENTS 1
265
266vec4 hook() {
267 vec2 d = HOOKED_pt;
268
269 //[tl t tr]
270 //[ l cc r]
271 //[bl b br]
272 float tx = LUMAD_tex(HOOKED_pos + vec2(0, -d.y)).x;
273 float cx = LUMAD_tex(HOOKED_pos).x;
274 float bx = LUMAD_tex(HOOKED_pos + vec2(0, d.y)).x;
275
276
277 float ty = LUMAD_tex(HOOKED_pos + vec2(0, -d.y)).y;
278 //float cy = LUMAD_tex(HOOKED_pos).y;
279 float by = LUMAD_tex(HOOKED_pos + vec2(0, d.y)).y;
280
281
282 //Horizontal Gradient
283 //[-1 0 1]
284 //[-2 0 2]
285 //[-1 0 1]
286 float xgrad = (tx + cx + cx + bx) / 8.0;
287
288 //Vertical Gradient
289 //[-1 -2 -1]
290 //[ 0 0 0]
291 //[ 1 2 1]
292 float ygrad = (-ty + by) / 8.0;
293
294 //Computes the luminance's gradient
295 float norm = sqrt(xgrad * xgrad + ygrad * ygrad);
296 return vec4(pow(norm, 0.7));
297}
298
299
300//!DESC Anime4K-v3.2-Upscale-DTD-x2-Kernel-X
301//!WHEN OUTPUT.w MAIN.w / 1.200 > OUTPUT.h MAIN.h / 1.200 > *
302//!HOOK MAIN
303//!BIND HOOKED
304//!BIND LUMAD
305//!SAVE LUMADG
306//!COMPONENTS 1
307
308#define L_tex LUMAD_tex
309
310#define SIGMA (HOOKED_size.y / 1080.0) * 2.0
311#define KERNELSIZE (SIGMA * 2.0 + 1.0)
312
313float gaussian(float x, float s, float m) {
314 return (1.0 / (s * sqrt(2.0 * 3.14159))) * exp(-0.5 * pow(abs(x - m) / s, 2.0));
315}
316
317float lumGaussian(vec2 pos, vec2 d) {
318 float g = (L_tex(pos).x) * gaussian(0.0, SIGMA, 0.0);
319 g = g + (L_tex(pos - d).x + L_tex(pos + d).x) * gaussian(1.0, SIGMA, 0.0);
320 for (int i=2; float(i)<KERNELSIZE; i++) {
321 g = g + (L_tex(pos - (d * float(i))).x + L_tex(pos + (d * float(i))).x) * gaussian(float(i), SIGMA, 0.0);
322 }
323
324 return g;
325}
326
327vec4 hook() {
328 return vec4(lumGaussian(HOOKED_pos, vec2(HOOKED_pt.x, 0)));
329}
330
331
332//!DESC Anime4K-v3.2-Upscale-DTD-x2-Kernel-Y
333//!WHEN OUTPUT.w MAIN.w / 1.200 > OUTPUT.h MAIN.h / 1.200 > *
334//!HOOK MAIN
335//!BIND HOOKED
336//!BIND LUMAD
337//!BIND LUMADG
338//!SAVE LUMAD
339//!COMPONENTS 1
340
341#define L_tex LUMADG_tex
342
343#define SIGMA (HOOKED_size.y / 1080.0) * 2.0
344#define KERNELSIZE (SIGMA * 2.0 + 1.0)
345
346float gaussian(float x, float s, float m) {
347 return (1.0 / (s * sqrt(2.0 * 3.14159))) * exp(-0.5 * pow(abs(x - m) / s, 2.0));
348}
349
350float lumGaussian(vec2 pos, vec2 d) {
351 float g = (L_tex(pos).x) * gaussian(0.0, SIGMA, 0.0);
352 g = g + (L_tex(pos - d).x + L_tex(pos + d).x) * gaussian(1.0, SIGMA, 0.0);
353 for (int i=2; float(i)<KERNELSIZE; i++) {
354 g = g + (L_tex(pos - (d * float(i))).x + L_tex(pos + (d * float(i))).x) * gaussian(float(i), SIGMA, 0.0);
355 }
356
357 return g;
358}
359
360vec4 hook() {
361 float g = lumGaussian(HOOKED_pos, vec2(0, HOOKED_pt.y));
362 return vec4(g);
363}
364
365
366
367
368//!DESC Anime4K-v3.2-Upscale-DTD-x2-Kernel-X
369//!WHEN OUTPUT.w MAIN.w / 1.200 > OUTPUT.h MAIN.h / 1.200 > *
370//!HOOK MAIN
371//!BIND HOOKED
372//!BIND LUMAD
373//!SAVE LUMAD2
374//!COMPONENTS 2
375
376vec4 hook() {
377 vec2 d = HOOKED_pt;
378
379 //[tl t tr]
380 //[ l c r]
381 //[bl b br]
382 float l = LUMAD_tex(HOOKED_pos + vec2(-d.x, 0)).x;
383 float c = LUMAD_tex(HOOKED_pos).x;
384 float r = LUMAD_tex(HOOKED_pos + vec2(d.x, 0)).x;
385
386
387 //Horizontal Gradient
388 //[-1 0 1]
389 //[-2 0 2]
390 //[-1 0 1]
391 float xgrad = (-l + r);
392
393 //Vertical Gradient
394 //[-1 -2 -1]
395 //[ 0 0 0]
396 //[ 1 2 1]
397 float ygrad = (l + c + c + r);
398
399 //Computes the luminance's gradient
400 return vec4(xgrad, ygrad, 0, 0);
401}
402
403
404//!DESC Anime4K-v3.2-Upscale-DTD-x2-Kernel-Y
405//!WHEN OUTPUT.w MAIN.w / 1.200 > OUTPUT.h MAIN.h / 1.200 > *
406//!HOOK MAIN
407//!BIND HOOKED
408//!BIND LUMAD2
409//!SAVE LUMAD2
410//!COMPONENTS 2
411
412vec4 hook() {
413 vec2 d = HOOKED_pt;
414
415 //[tl t tr]
416 //[ l cc r]
417 //[bl b br]
418 float tx = LUMAD2_tex(HOOKED_pos + vec2(0, -d.y)).x;
419 float cx = LUMAD2_tex(HOOKED_pos).x;
420 float bx = LUMAD2_tex(HOOKED_pos + vec2(0, d.y)).x;
421
422
423 float ty = LUMAD2_tex(HOOKED_pos + vec2(0, -d.y)).y;
424 //float cy = LUMAD2_tex(HOOKED_pos).y;
425 float by = LUMAD2_tex(HOOKED_pos + vec2(0, d.y)).y;
426
427
428 //Horizontal Gradient
429 //[-1 0 1]
430 //[-2 0 2]
431 //[-1 0 1]
432 float xgrad = (tx + cx + cx + bx) / 8.0;
433
434 //Vertical Gradient
435 //[-1 -2 -1]
436 //[ 0 0 0]
437 //[ 1 2 1]
438 float ygrad = (-ty + by) / 8.0;
439
440 //Computes the luminance's gradient
441 return vec4(xgrad, ygrad, 0, 0);
442}
443
444//!DESC Anime4K-v3.2-Upscale-DTD-x2
445//!WHEN OUTPUT.w MAIN.w / 1.200 > OUTPUT.h MAIN.h / 1.200 > *
446//!HOOK MAIN
447//!BIND HOOKED
448//!BIND LUMAD
449//!BIND LUMAD2
450//!SAVE MAINTEMPTHIN
451//!WIDTH MAIN.w 2 *
452//!HEIGHT MAIN.h 2 *
453
454#define STRENGTH 0.4 //Strength of warping for each iteration
455#define ITERATIONS 1 //Number of iterations for the forwards solver, decreasing strength and increasing iterations improves quality at the cost of speed.
456
457#define L_tex HOOKED_tex
458
459vec4 hook() {
460 vec2 d = HOOKED_pt;
461
462 float relstr = HOOKED_size.y / 1080.0 * STRENGTH;
463
464 vec2 pos = HOOKED_pos;
465 for (int i=0; i<ITERATIONS; i++) {
466 vec2 dn = LUMAD2_tex(pos).xy;
467 vec2 dd = (dn / (length(dn) + 0.01)) * d * relstr; //Quasi-normalization for large vectors, avoids divide by zero
468 pos -= dd;
469 }
470
471 return L_tex(pos);
472
473}
474
475//!DESC Anime4K-v3.2-Upscale-DTD-x2-Luma
476//!HOOK MAIN
477//!BIND HOOKED
478//!BIND MAINTEMPTHIN
479//!COMPONENTS 1
480//!SAVE MAINTEMP
481//!WIDTH MAIN.w 2 *
482//!HEIGHT MAIN.h 2 *
483
484float get_luma(vec4 rgba) {
485 return dot(vec4(0.299, 0.587, 0.114, 0.0), rgba);
486}
487
488vec4 hook() {
489 return vec4(get_luma(MAINTEMPTHIN_tex(HOOKED_pos)), 0.0, 0.0, 0.0);
490}
491
492//!DESC Anime4K-v3.2-Upscale-DTD-x2-Kernel-X
493//!WHEN OUTPUT.w MAIN.w / 1.200 > OUTPUT.h MAIN.h / 1.200 > *
494//!HOOK MAIN
495//!BIND HOOKED
496//!BIND MAINTEMP
497//!SAVE MMKERNEL
498//!COMPONENTS 3
499
500#define L_tex MAINTEMP_tex
501
502float max3v(float a, float b, float c) {
503 return max(max(a, b), c);
504}
505float min3v(float a, float b, float c) {
506 return min(min(a, b), c);
507}
508
509vec2 minmax3(vec2 pos, vec2 d) {
510 float a = L_tex(pos - d).x;
511 float b = L_tex(pos).x;
512 float c = L_tex(pos + d).x;
513
514 return vec2(min3v(a, b, c), max3v(a, b, c));
515}
516
517float lumGaussian7(vec2 pos, vec2 d) {
518 float g = (L_tex(pos - (d + d)).x + L_tex(pos + (d + d)).x) * 0.06136;
519 g = g + (L_tex(pos - d).x + L_tex(pos + d).x) * 0.24477;
520 g = g + (L_tex(pos).x) * 0.38774;
521
522 return g;
523}
524
525
526vec4 hook() {
527 return vec4(lumGaussian7(HOOKED_pos, vec2(HOOKED_pt.x, 0)), minmax3(HOOKED_pos, vec2(HOOKED_pt.x, 0)), 0);
528}
529
530
531//!DESC Anime4K-v3.2-Upscale-DTD-x2-Kernel-Y
532//!WHEN OUTPUT.w MAIN.w / 1.200 > OUTPUT.h MAIN.h / 1.200 > *
533//!HOOK MAIN
534//!BIND HOOKED
535//!BIND MMKERNEL
536//!SAVE MMKERNEL
537//!COMPONENTS 3
538
539#define L_tex MMKERNEL_tex
540
541float max3v(float a, float b, float c) {
542 return max(max(a, b), c);
543}
544float min3v(float a, float b, float c) {
545 return min(min(a, b), c);
546}
547
548vec2 minmax3(vec2 pos, vec2 d) {
549 float a0 = L_tex(pos - d).y;
550 float b0 = L_tex(pos).y;
551 float c0 = L_tex(pos + d).y;
552
553 float a1 = L_tex(pos - d).z;
554 float b1 = L_tex(pos).z;
555 float c1 = L_tex(pos + d).z;
556
557 return vec2(min3v(a0, b0, c0), max3v(a1, b1, c1));
558}
559
560float lumGaussian7(vec2 pos, vec2 d) {
561 float g = (L_tex(pos - (d + d)).x + L_tex(pos + (d + d)).x) * 0.06136;
562 g = g + (L_tex(pos - d).x + L_tex(pos + d).x) * 0.24477;
563 g = g + (L_tex(pos).x) * 0.38774;
564
565 return g;
566}
567
568
569vec4 hook() {
570 return vec4(lumGaussian7(HOOKED_pos, vec2(0, HOOKED_pt.y)), minmax3(HOOKED_pos, vec2(0, HOOKED_pt.y)), 0);
571}
572
573//!DESC Anime4K-v3.2-Upscale-DTD-x2
574//!WHEN OUTPUT.w MAIN.w / 1.200 > OUTPUT.h MAIN.h / 1.200 > *
575//!HOOK MAIN
576//!BIND HOOKED
577//!BIND MAINTEMPTHIN
578//!BIND MAINTEMP
579//!BIND MMKERNEL
580//!WIDTH MAIN.w 2 *
581//!HEIGHT MAIN.h 2 *
582
583#define STRENGTH 0.5 //De-blur proportional strength, higher is sharper. However, it is better to tweak BLUR_CURVE instead to avoid ringing.
584#define BLUR_CURVE 0.8 //De-blur power curve, lower is sharper. Good values are between 0.3 - 1. Values greater than 1 softens the image;
585#define BLUR_THRESHOLD 0.1 //Value where curve kicks in, used to not de-blur already sharp edges. Only de-blur values that fall below this threshold.
586#define NOISE_THRESHOLD 0.004 //Value where curve stops, used to not sharpen noise. Only de-blur values that fall above this threshold.
587
588#define L_tex MAINTEMP_tex
589
590vec4 hook() {
591 float c = (L_tex(HOOKED_pos).x - MMKERNEL_tex(HOOKED_pos).x) * STRENGTH;
592
593 float t_range = BLUR_THRESHOLD - NOISE_THRESHOLD;
594
595 float c_t = abs(c);
596 if (c_t > NOISE_THRESHOLD) {
597 c_t = (c_t - NOISE_THRESHOLD) / t_range;
598 c_t = pow(c_t, BLUR_CURVE);
599 c_t = c_t * t_range + NOISE_THRESHOLD;
600 c_t = c_t * sign(c);
601 } else {
602 c_t = c;
603 }
604
605 float cc = clamp(c_t + L_tex(HOOKED_pos).x, MMKERNEL_tex(HOOKED_pos).y, MMKERNEL_tex(HOOKED_pos).z) - L_tex(HOOKED_pos).x;
606
607 //This trick is only possible if the inverse Y->RGB matrix has 1 for every row... (which is the case for BT.709)
608 //Otherwise we would need to convert RGB to YUV, modify Y then convert back to RGB.
609 return MAINTEMPTHIN_tex(HOOKED_pos) + cc;
610}
611
612
613
1// MIT License
2
3// Copyright (c) 2019-2021 bloc97
4// All rights reserved.
5
6// Permission is hereby granted, free of charge, to any person obtaining a copy
7// of this software and associated documentation files (the "Software"), to deal
8// in the Software without restriction, including without limitation the rights
9// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10// copies of the Software, and to permit persons to whom the Software is
11// furnished to do so, subject to the following conditions:
13// The above copyright notice and this permission notice shall be included in all
14// copies or substantial portions of the Software.
16// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22// SOFTWARE.
24//!DESC Anime4K-v3.2-Upscale-DTD-x2-Luma
25//!HOOK MAIN
26//!BIND HOOKED
27//!SAVE LINELUMA
28//!COMPONENTS 1
30float get_luma(vec4 rgba) {
31 return dot(vec4(0.299, 0.587, 0.114, 0.0), rgba);
32}
34vec4 hook() {
35 return vec4(get_luma(HOOKED_tex(HOOKED_pos)), 0.0, 0.0, 0.0);
36}
38//!DESC Anime4K-v3.2-Upscale-DTD-x2-Kernel-X
39//!WHEN OUTPUT.w MAIN.w / 1.200 > OUTPUT.h MAIN.h / 1.200 > *
40//!HOOK MAIN
41//!BIND HOOKED
42//!BIND LINELUMA
43//!SAVE MMKERNEL
44//!COMPONENTS 1
46#define L_tex LINELUMA_tex
48#define SIGMA 1.0
50float gaussian(float x, float s, float m) {
51 return (1.0 / (s * sqrt(2.0 * 3.14159))) * exp(-0.5 * pow(abs(x - m) / s, 2.0));
52}
54float lumGaussian(vec2 pos, vec2 d) {
55 float s = SIGMA * HOOKED_size.y / 1080.0;
56 float kernel_size = s * 2.0 + 1.0;
57
58 float g = (L_tex(pos).x) * gaussian(0.0, s, 0.0);
59 float gn = gaussian(0.0, s, 0.0);
60
61 g += (L_tex(pos - d).x + L_tex(pos + d).x) * gaussian(1.0, s, 0.0);
62 gn += gaussian(1.0, s, 0.0) * 2.0;
63
64 for (int i=2; float(i)<kernel_size; i++) {
65 g += (L_tex(pos - (d * float(i))).x + L_tex(pos + (d * float(i))).x) * gaussian(float(i), s, 0.0);
66 gn += gaussian(float(i), s, 0.0) * 2.0;
67 }
68
69 return g / gn;
70}
72vec4 hook() {
73 return vec4(lumGaussian(HOOKED_pos, vec2(HOOKED_pt.x, 0)));
74}
76//!DESC Anime4K-v3.2-Upscale-DTD-x2-Kernel-Y
77//!WHEN OUTPUT.w MAIN.w / 1.200 > OUTPUT.h MAIN.h / 1.200 > *
78//!HOOK MAIN
79//!BIND HOOKED
80//!BIND LINELUMA
81//!BIND MMKERNEL
82//!SAVE MMKERNEL
83//!COMPONENTS 1
85#define L_tex MMKERNEL_tex
87#define SIGMA 1.0
89float gaussian(float x, float s, float m) {
90 return (1.0 / (s * sqrt(2.0 * 3.14159))) * exp(-0.5 * pow(abs(x - m) / s, 2.0));
91}
93float lumGaussian(vec2 pos, vec2 d) {
94 float s = SIGMA * HOOKED_size.y / 1080.0;
95 float kernel_size = s * 2.0 + 1.0;
96
97 float g = (L_tex(pos).x) * gaussian(0.0, s, 0.0);
98 float gn = gaussian(0.0, s, 0.0);
99
100 g += (L_tex(pos - d).x + L_tex(pos + d).x) * gaussian(1.0, s, 0.0);
101 gn += gaussian(1.0, s, 0.0) * 2.0;
102
103 for (int i=2; float(i)<kernel_size; i++) {
104 g += (L_tex(pos - (d * float(i))).x + L_tex(pos + (d * float(i))).x) * gaussian(float(i), s, 0.0);
105 gn += gaussian(float(i), s, 0.0) * 2.0;
106 }
107
108 return g / gn;
109}
111vec4 hook() {
112 return vec4(min(LINELUMA_tex(HOOKED_pos).x - lumGaussian(HOOKED_pos, vec2(0, HOOKED_pt.y)), 0.0));
113}
115//!DESC Anime4K-v3.2-Upscale-DTD-x2-Kernel-X
116//!WHEN OUTPUT.w MAIN.w / 1.200 > OUTPUT.h MAIN.h / 1.200 > *
117//!HOOK MAIN
118//!BIND HOOKED
119//!BIND MMKERNEL
120//!SAVE MMKERNEL
121//!COMPONENTS 1
123#define L_tex MMKERNEL_tex
125#define SIGMA 0.4
127float gaussian(float x, float s, float m) {
128 return (1.0 / (s * sqrt(2.0 * 3.14159))) * exp(-0.5 * pow(abs(x - m) / s, 2.0));
129}
131float lumGaussian(vec2 pos, vec2 d) {
132 float s = SIGMA * HOOKED_size.y / 1080.0;
133 float kernel_size = s * 2.0 + 1.0;
134
135 float g = (L_tex(pos).x) * gaussian(0.0, s, 0.0);
136 float gn = gaussian(0.0, s, 0.0);
137
138 g += (L_tex(pos - d).x + L_tex(pos + d).x) * gaussian(1.0, s, 0.0);
139 gn += gaussian(1.0, s, 0.0) * 2.0;
140
141 for (int i=2; float(i)<kernel_size; i++) {
142 g += (L_tex(pos - (d * float(i))).x + L_tex(pos + (d * float(i))).x) * gaussian(float(i), s, 0.0);
143 gn += gaussian(float(i), s, 0.0) * 2.0;
144 }
145
146 return g / gn;
147}
149vec4 hook() {
150 return vec4(lumGaussian(HOOKED_pos, vec2(HOOKED_pt.x, 0)));
151}
153//!DESC Anime4K-v3.2-Upscale-DTD-x2-Kernel-Y
154//!WHEN OUTPUT.w MAIN.w / 1.200 > OUTPUT.h MAIN.h / 1.200 > *
155//!HOOK MAIN
156//!BIND HOOKED
157//!BIND MMKERNEL
158//!SAVE MMKERNEL
159//!COMPONENTS 1
161#define L_tex MMKERNEL_tex
163#define SIGMA 0.4
165float gaussian(float x, float s, float m) {
166 return (1.0 / (s * sqrt(2.0 * 3.14159))) * exp(-0.5 * pow(abs(x - m) / s, 2.0));
167}
169float lumGaussian(vec2 pos, vec2 d) {
170 float s = SIGMA * HOOKED_size.y / 1080.0;
171 float kernel_size = s * 2.0 + 1.0;
172
173 float g = (L_tex(pos).x) * gaussian(0.0, s, 0.0);
174 float gn = gaussian(0.0, s, 0.0);
175
176 g += (L_tex(pos - d).x + L_tex(pos + d).x) * gaussian(1.0, s, 0.0);
177 gn += gaussian(1.0, s, 0.0) * 2.0;
178
179 for (int i=2; float(i)<kernel_size; i++) {
180 g += (L_tex(pos - (d * float(i))).x + L_tex(pos + (d * float(i))).x) * gaussian(float(i), s, 0.0);
181 gn += gaussian(float(i), s, 0.0) * 2.0;
182 }
183
184 return g / gn;
185}
187vec4 hook() {
188 return vec4(lumGaussian(HOOKED_pos, vec2(0, HOOKED_pt.y)));
189}
191//!DESC Anime4K-v3.2-Upscale-DTD-x2
192//!WHEN OUTPUT.w MAIN.w / 1.200 > OUTPUT.h MAIN.h / 1.200 > *
193//!HOOK MAIN
194//!BIND HOOKED
195//!BIND MMKERNEL
197#define STRENGTH 1.8 //Line darken proportional strength, higher is darker.
199vec4 hook() {
200 float c = (MMKERNEL_tex(HOOKED_pos).x) * STRENGTH;
201 //This trick is only possible if the inverse Y->RGB matrix has 1 for every row... (which is the case for BT.709)
202 //Otherwise we would need to convert RGB to YUV, modify Y then convert back to RGB.
203 return HOOKED_tex(HOOKED_pos) + c;
204}
206//!DESC Anime4K-v3.2-Upscale-DTD-x2-Luma
207//!HOOK MAIN
208//!BIND HOOKED
209//!SAVE LINELUMA
210//!COMPONENTS 1
212float get_luma(vec4 rgba) {
213 return dot(vec4(0.299, 0.587, 0.114, 0.0), rgba);
214}
216vec4 hook() {
217 return vec4(get_luma(HOOKED_tex(HOOKED_pos)), 0.0, 0.0, 0.0);
218}
220//!DESC Anime4K-v3.2-Upscale-DTD-x2-Kernel-X
221//!WHEN OUTPUT.w MAIN.w / 1.200 > OUTPUT.h MAIN.h / 1.200 > *
222//!HOOK MAIN
223//!BIND HOOKED
224//!BIND LINELUMA
225//!SAVE LUMAD
226//!COMPONENTS 2
228#define L_tex LINELUMA_tex
230vec4 hook() {
231 vec2 d = HOOKED_pt;
232
233 //[tl t tr]
234 //[ l c r]
235 //[bl b br]
236 float l = L_tex(HOOKED_pos + vec2(-d.x, 0)).x;
237 float c = L_tex(HOOKED_pos).x;
238 float r = L_tex(HOOKED_pos + vec2(d.x, 0)).x;
239
240
241 //Horizontal Gradient
242 //[-1 0 1]
243 //[-2 0 2]
244 //[-1 0 1]
245 float xgrad = (-l + r);
246
247 //Vertical Gradient
248 //[-1 -2 -1]
249 //[ 0 0 0]
250 //[ 1 2 1]
251 float ygrad = (l + c + c + r);
252
253 //Computes the luminance's gradient
254 return vec4(xgrad, ygrad, 0, 0);
255}
258//!DESC Anime4K-v3.2-Upscale-DTD-x2-Kernel-Y
259//!WHEN OUTPUT.w MAIN.w / 1.200 > OUTPUT.h MAIN.h / 1.200 > *
260//!HOOK MAIN
261//!BIND HOOKED
262//!BIND LUMAD
263//!SAVE LUMAD
264//!COMPONENTS 1
266vec4 hook() {
267 vec2 d = HOOKED_pt;
268
269 //[tl t tr]
270 //[ l cc r]
271 //[bl b br]
272 float tx = LUMAD_tex(HOOKED_pos + vec2(0, -d.y)).x;
273 float cx = LUMAD_tex(HOOKED_pos).x;
274 float bx = LUMAD_tex(HOOKED_pos + vec2(0, d.y)).x;
275
276
277 float ty = LUMAD_tex(HOOKED_pos + vec2(0, -d.y)).y;
278 //float cy = LUMAD_tex(HOOKED_pos).y;
279 float by = LUMAD_tex(HOOKED_pos + vec2(0, d.y)).y;
280
281
282 //Horizontal Gradient
283 //[-1 0 1]
284 //[-2 0 2]
285 //[-1 0 1]
286 float xgrad = (tx + cx + cx + bx) / 8.0;
287
288 //Vertical Gradient
289 //[-1 -2 -1]
290 //[ 0 0 0]
291 //[ 1 2 1]
292 float ygrad = (-ty + by) / 8.0;
293
294 //Computes the luminance's gradient
295 float norm = sqrt(xgrad * xgrad + ygrad * ygrad);
296 return vec4(pow(norm, 0.7));
297}
300//!DESC Anime4K-v3.2-Upscale-DTD-x2-Kernel-X
301//!WHEN OUTPUT.w MAIN.w / 1.200 > OUTPUT.h MAIN.h / 1.200 > *
302//!HOOK MAIN
303//!BIND HOOKED
304//!BIND LUMAD
305//!SAVE LUMADG
306//!COMPONENTS 1
308#define L_tex LUMAD_tex
310#define SIGMA (HOOKED_size.y / 1080.0) * 2.0
311#define KERNELSIZE (SIGMA * 2.0 + 1.0)
313float gaussian(float x, float s, float m) {
314 return (1.0 / (s * sqrt(2.0 * 3.14159))) * exp(-0.5 * pow(abs(x - m) / s, 2.0));
315}
317float lumGaussian(vec2 pos, vec2 d) {
318 float g = (L_tex(pos).x) * gaussian(0.0, SIGMA, 0.0);
319 g = g + (L_tex(pos - d).x + L_tex(pos + d).x) * gaussian(1.0, SIGMA, 0.0);
320 for (int i=2; float(i)<KERNELSIZE; i++) {
321 g = g + (L_tex(pos - (d * float(i))).x + L_tex(pos + (d * float(i))).x) * gaussian(float(i), SIGMA, 0.0);
322 }
323
324 return g;
325}
327vec4 hook() {
328 return vec4(lumGaussian(HOOKED_pos, vec2(HOOKED_pt.x, 0)));
329}
332//!DESC Anime4K-v3.2-Upscale-DTD-x2-Kernel-Y
333//!WHEN OUTPUT.w MAIN.w / 1.200 > OUTPUT.h MAIN.h / 1.200 > *
334//!HOOK MAIN
335//!BIND HOOKED
336//!BIND LUMAD
337//!BIND LUMADG
338//!SAVE LUMAD
339//!COMPONENTS 1
341#define L_tex LUMADG_tex
343#define SIGMA (HOOKED_size.y / 1080.0) * 2.0
344#define KERNELSIZE (SIGMA * 2.0 + 1.0)
346float gaussian(float x, float s, float m) {
347 return (1.0 / (s * sqrt(2.0 * 3.14159))) * exp(-0.5 * pow(abs(x - m) / s, 2.0));
348}
350float lumGaussian(vec2 pos, vec2 d) {
351 float g = (L_tex(pos).x) * gaussian(0.0, SIGMA, 0.0);
352 g = g + (L_tex(pos - d).x + L_tex(pos + d).x) * gaussian(1.0, SIGMA, 0.0);
353 for (int i=2; float(i)<KERNELSIZE; i++) {
354 g = g + (L_tex(pos - (d * float(i))).x + L_tex(pos + (d * float(i))).x) * gaussian(float(i), SIGMA, 0.0);
355 }
356
357 return g;
358}
360vec4 hook() {
361 float g = lumGaussian(HOOKED_pos, vec2(0, HOOKED_pt.y));
362 return vec4(g);
363}
368//!DESC Anime4K-v3.2-Upscale-DTD-x2-Kernel-X
369//!WHEN OUTPUT.w MAIN.w / 1.200 > OUTPUT.h MAIN.h / 1.200 > *
370//!HOOK MAIN
371//!BIND HOOKED
372//!BIND LUMAD
373//!SAVE LUMAD2
374//!COMPONENTS 2
376vec4 hook() {
377 vec2 d = HOOKED_pt;
378
379 //[tl t tr]
380 //[ l c r]
381 //[bl b br]
382 float l = LUMAD_tex(HOOKED_pos + vec2(-d.x, 0)).x;
383 float c = LUMAD_tex(HOOKED_pos).x;
384 float r = LUMAD_tex(HOOKED_pos + vec2(d.x, 0)).x;
385
386
387 //Horizontal Gradient
388 //[-1 0 1]
389 //[-2 0 2]
390 //[-1 0 1]
391 float xgrad = (-l + r);
392
393 //Vertical Gradient
394 //[-1 -2 -1]
395 //[ 0 0 0]
396 //[ 1 2 1]
397 float ygrad = (l + c + c + r);
398
399 //Computes the luminance's gradient
400 return vec4(xgrad, ygrad, 0, 0);
401}
404//!DESC Anime4K-v3.2-Upscale-DTD-x2-Kernel-Y
405//!WHEN OUTPUT.w MAIN.w / 1.200 > OUTPUT.h MAIN.h / 1.200 > *
406//!HOOK MAIN
407//!BIND HOOKED
408//!BIND LUMAD2
409//!SAVE LUMAD2
410//!COMPONENTS 2
412vec4 hook() {
413 vec2 d = HOOKED_pt;
414
415 //[tl t tr]
416 //[ l cc r]
417 //[bl b br]
418 float tx = LUMAD2_tex(HOOKED_pos + vec2(0, -d.y)).x;
419 float cx = LUMAD2_tex(HOOKED_pos).x;
420 float bx = LUMAD2_tex(HOOKED_pos + vec2(0, d.y)).x;
421
422
423 float ty = LUMAD2_tex(HOOKED_pos + vec2(0, -d.y)).y;
424 //float cy = LUMAD2_tex(HOOKED_pos).y;
425 float by = LUMAD2_tex(HOOKED_pos + vec2(0, d.y)).y;
426
427
428 //Horizontal Gradient
429 //[-1 0 1]
430 //[-2 0 2]
431 //[-1 0 1]
432 float xgrad = (tx + cx + cx + bx) / 8.0;
433
434 //Vertical Gradient
435 //[-1 -2 -1]
436 //[ 0 0 0]
437 //[ 1 2 1]
438 float ygrad = (-ty + by) / 8.0;
439
440 //Computes the luminance's gradient
441 return vec4(xgrad, ygrad, 0, 0);
442}
444//!DESC Anime4K-v3.2-Upscale-DTD-x2
445//!WHEN OUTPUT.w MAIN.w / 1.200 > OUTPUT.h MAIN.h / 1.200 > *
446//!HOOK MAIN
447//!BIND HOOKED
448//!BIND LUMAD
449//!BIND LUMAD2
450//!SAVE MAINTEMPTHIN
451//!WIDTH MAIN.w 2 *
452//!HEIGHT MAIN.h 2 *
454#define STRENGTH 0.4 //Strength of warping for each iteration
455#define ITERATIONS 1 //Number of iterations for the forwards solver, decreasing strength and increasing iterations improves quality at the cost of speed.
457#define L_tex HOOKED_tex
459vec4 hook() {
460 vec2 d = HOOKED_pt;
461
462 float relstr = HOOKED_size.y / 1080.0 * STRENGTH;
463
464 vec2 pos = HOOKED_pos;
465 for (int i=0; i<ITERATIONS; i++) {
466 vec2 dn = LUMAD2_tex(pos).xy;
467 vec2 dd = (dn / (length(dn) + 0.01)) * d * relstr; //Quasi-normalization for large vectors, avoids divide by zero
468 pos -= dd;
469 }
470
471 return L_tex(pos);
472
473}
475//!DESC Anime4K-v3.2-Upscale-DTD-x2-Luma
476//!HOOK MAIN
477//!BIND HOOKED
478//!BIND MAINTEMPTHIN
479//!COMPONENTS 1
480//!SAVE MAINTEMP
481//!WIDTH MAIN.w 2 *
482//!HEIGHT MAIN.h 2 *
484float get_luma(vec4 rgba) {
485 return dot(vec4(0.299, 0.587, 0.114, 0.0), rgba);
486}
488vec4 hook() {
489 return vec4(get_luma(MAINTEMPTHIN_tex(HOOKED_pos)), 0.0, 0.0, 0.0);
490}
492//!DESC Anime4K-v3.2-Upscale-DTD-x2-Kernel-X
493//!WHEN OUTPUT.w MAIN.w / 1.200 > OUTPUT.h MAIN.h / 1.200 > *
494//!HOOK MAIN
495//!BIND HOOKED
496//!BIND MAINTEMP
497//!SAVE MMKERNEL
498//!COMPONENTS 3
500#define L_tex MAINTEMP_tex
502float max3v(float a, float b, float c) {
503 return max(max(a, b), c);
504}
505float min3v(float a, float b, float c) {
506 return min(min(a, b), c);
507}
509vec2 minmax3(vec2 pos, vec2 d) {
510 float a = L_tex(pos - d).x;
511 float b = L_tex(pos).x;
512 float c = L_tex(pos + d).x;
513
514 return vec2(min3v(a, b, c), max3v(a, b, c));
515}
517float lumGaussian7(vec2 pos, vec2 d) {
518 float g = (L_tex(pos - (d + d)).x + L_tex(pos + (d + d)).x) * 0.06136;
519 g = g + (L_tex(pos - d).x + L_tex(pos + d).x) * 0.24477;
520 g = g + (L_tex(pos).x) * 0.38774;
521
522 return g;
523}
526vec4 hook() {
527 return vec4(lumGaussian7(HOOKED_pos, vec2(HOOKED_pt.x, 0)), minmax3(HOOKED_pos, vec2(HOOKED_pt.x, 0)), 0);
528}
531//!DESC Anime4K-v3.2-Upscale-DTD-x2-Kernel-Y
532//!WHEN OUTPUT.w MAIN.w / 1.200 > OUTPUT.h MAIN.h / 1.200 > *
533//!HOOK MAIN
534//!BIND HOOKED
535//!BIND MMKERNEL
536//!SAVE MMKERNEL
537//!COMPONENTS 3
539#define L_tex MMKERNEL_tex
541float max3v(float a, float b, float c) {
542 return max(max(a, b), c);
543}
544float min3v(float a, float b, float c) {
545 return min(min(a, b), c);
546}
548vec2 minmax3(vec2 pos, vec2 d) {
549 float a0 = L_tex(pos - d).y;
550 float b0 = L_tex(pos).y;
551 float c0 = L_tex(pos + d).y;
552
553 float a1 = L_tex(pos - d).z;
554 float b1 = L_tex(pos).z;
555 float c1 = L_tex(pos + d).z;
556
557 return vec2(min3v(a0, b0, c0), max3v(a1, b1, c1));
558}
560float lumGaussian7(vec2 pos, vec2 d) {
561 float g = (L_tex(pos - (d + d)).x + L_tex(pos + (d + d)).x) * 0.06136;
562 g = g + (L_tex(pos - d).x + L_tex(pos + d).x) * 0.24477;
563 g = g + (L_tex(pos).x) * 0.38774;
564
565 return g;
566}
569vec4 hook() {
570 return vec4(lumGaussian7(HOOKED_pos, vec2(0, HOOKED_pt.y)), minmax3(HOOKED_pos, vec2(0, HOOKED_pt.y)), 0);
571}
573//!DESC Anime4K-v3.2-Upscale-DTD-x2
574//!WHEN OUTPUT.w MAIN.w / 1.200 > OUTPUT.h MAIN.h / 1.200 > *
575//!HOOK MAIN
576//!BIND HOOKED
577//!BIND MAINTEMPTHIN
578//!BIND MAINTEMP
579//!BIND MMKERNEL
580//!WIDTH MAIN.w 2 *
581//!HEIGHT MAIN.h 2 *
583#define STRENGTH 0.5 //De-blur proportional strength, higher is sharper. However, it is better to tweak BLUR_CURVE instead to avoid ringing.
584#define BLUR_CURVE 0.8 //De-blur power curve, lower is sharper. Good values are between 0.3 - 1. Values greater than 1 softens the image;
585#define BLUR_THRESHOLD 0.1 //Value where curve kicks in, used to not de-blur already sharp edges. Only de-blur values that fall below this threshold.
586#define NOISE_THRESHOLD 0.004 //Value where curve stops, used to not sharpen noise. Only de-blur values that fall above this threshold.
588#define L_tex MAINTEMP_tex
590vec4 hook() {
591 float c = (L_tex(HOOKED_pos).x - MMKERNEL_tex(HOOKED_pos).x) * STRENGTH;
592
593 float t_range = BLUR_THRESHOLD - NOISE_THRESHOLD;
594
595 float c_t = abs(c);
596 if (c_t > NOISE_THRESHOLD) {
597 c_t = (c_t - NOISE_THRESHOLD) / t_range;
598 c_t = pow(c_t, BLUR_CURVE);
599 c_t = c_t * t_range + NOISE_THRESHOLD;
600 c_t = c_t * sign(c);
601 } else {
602 c_t = c;
603 }
604
605 float cc = clamp(c_t + L_tex(HOOKED_pos).x, MMKERNEL_tex(HOOKED_pos).y, MMKERNEL_tex(HOOKED_pos).z) - L_tex(HOOKED_pos).x;
606
607 //This trick is only possible if the inverse Y->RGB matrix has 1 for every row... (which is the case for BT.709)
608 //Otherwise we would need to convert RGB to YUV, modify Y then convert back to RGB.
609 return MAINTEMPTHIN_tex(HOOKED_pos) + cc;
610}

mpv/shaders/Anime4K_Upscale_Deblur_DoG_x2.glsl

Modified

+158 / −158 text lines

1// MIT License
2
3// Copyright (c) 2019-2021 bloc97
4// All rights reserved.
5
6// Permission is hereby granted, free of charge, to any person obtaining a copy
7// of this software and associated documentation files (the "Software"), to deal
8// in the Software without restriction, including without limitation the rights
9// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10// copies of the Software, and to permit persons to whom the Software is
11// furnished to do so, subject to the following conditions:
12
13// The above copyright notice and this permission notice shall be included in all
14// copies or substantial portions of the Software.
15
16// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22// SOFTWARE.
23
24//!DESC Anime4K-v3.2-Upscale-Deblur-DoG-x2-Luma
25//!HOOK MAIN
26//!BIND HOOKED
27//!SAVE LINELUMA
28//!COMPONENTS 1
29
30float get_luma(vec4 rgba) {
31 return dot(vec4(0.299, 0.587, 0.114, 0.0), rgba);
32}
33
34vec4 hook() {
35 return vec4(get_luma(HOOKED_tex(HOOKED_pos)), 0.0, 0.0, 0.0);
36}
37
38//!DESC Anime4K-v3.2-Upscale-Deblur-DoG-x2-Kernel-X
39//!WHEN OUTPUT.w MAIN.w / 1.200 > OUTPUT.h MAIN.h / 1.200 > *
40//!HOOK MAIN
41//!BIND HOOKED
42//!BIND LINELUMA
43//!SAVE GAUSS_X2
44//!COMPONENTS 3
45
46#define L_tex LINELUMA_tex
47
48float max3v(float a, float b, float c) {
49 return max(max(a, b), c);
50}
51float min3v(float a, float b, float c) {
52 return min(min(a, b), c);
53}
54
55vec2 minmax3(vec2 pos, vec2 d) {
56 float a = L_tex(pos - d).x;
57 float b = L_tex(pos).x;
58 float c = L_tex(pos + d).x;
59
60 return vec2(min3v(a, b, c), max3v(a, b, c));
61}
62
63float lumGaussian7(vec2 pos, vec2 d) {
64 float g = (L_tex(pos - (d + d)).x + L_tex(pos + (d + d)).x) * 0.06136;
65 g = g + (L_tex(pos - d).x + L_tex(pos + d).x) * 0.24477;
66 g = g + (L_tex(pos).x) * 0.38774;
67
68 return g;
69}
70
71
72vec4 hook() {
73 return vec4(lumGaussian7(HOOKED_pos, vec2(HOOKED_pt.x, 0)), minmax3(HOOKED_pos, vec2(HOOKED_pt.x, 0)), 0);
74}
75
76
77//!DESC Anime4K-v3.2-Upscale-Deblur-DoG-x2-Kernel-Y
78//!WHEN OUTPUT.w MAIN.w / 1.200 > OUTPUT.h MAIN.h / 1.200 > *
79//!HOOK MAIN
80//!BIND HOOKED
81//!BIND GAUSS_X2
82//!SAVE GAUSS_X2
83//!COMPONENTS 3
84
85#define L_tex GAUSS_X2_tex
86
87float max3v(float a, float b, float c) {
88 return max(max(a, b), c);
89}
90float min3v(float a, float b, float c) {
91 return min(min(a, b), c);
92}
93
94vec2 minmax3(vec2 pos, vec2 d) {
95 float a0 = L_tex(pos - d).y;
96 float b0 = L_tex(pos).y;
97 float c0 = L_tex(pos + d).y;
98
99 float a1 = L_tex(pos - d).z;
100 float b1 = L_tex(pos).z;
101 float c1 = L_tex(pos + d).z;
102
103 return vec2(min3v(a0, b0, c0), max3v(a1, b1, c1));
104}
105
106float lumGaussian7(vec2 pos, vec2 d) {
107 float g = (L_tex(pos - (d + d)).x + L_tex(pos + (d + d)).x) * 0.06136;
108 g = g + (L_tex(pos - d).x + L_tex(pos + d).x) * 0.24477;
109 g = g + (L_tex(pos).x) * 0.38774;
110
111 return g;
112}
113
114
115vec4 hook() {
116 return vec4(lumGaussian7(HOOKED_pos, vec2(0, HOOKED_pt.y)), minmax3(HOOKED_pos, vec2(0, HOOKED_pt.y)), 0);
117}
118
119//!DESC Anime4K-v3.2-Upscale-Deblur-DoG-x2-Apply
120//!WHEN OUTPUT.w MAIN.w / 1.200 > OUTPUT.h MAIN.h / 1.200 > *
121//!HOOK MAIN
122//!BIND HOOKED
123//!BIND LINELUMA
124//!BIND GAUSS_X2
125//!WIDTH MAIN.w 2 *
126//!HEIGHT MAIN.h 2 *
127
128#define STRENGTH 0.6 //De-blur proportional strength, higher is sharper. However, it is better to tweak BLUR_CURVE instead to avoid ringing.
129#define BLUR_CURVE 0.6 //De-blur power curve, lower is sharper. Good values are between 0.3 - 1. Values greater than 1 softens the image;
130#define BLUR_THRESHOLD 0.1 //Value where curve kicks in, used to not de-blur already sharp edges. Only de-blur values that fall below this threshold.
131#define NOISE_THRESHOLD 0.001 //Value where curve stops, used to not sharpen noise. Only de-blur values that fall above this threshold.
132
133#define L_tex LINELUMA_tex
134
135vec4 hook() {
136 float c = (L_tex(HOOKED_pos).x - GAUSS_X2_tex(HOOKED_pos).x) * STRENGTH;
137
138 float t_range = BLUR_THRESHOLD - NOISE_THRESHOLD;
139
140 float c_t = abs(c);
141 if (c_t > NOISE_THRESHOLD && c_t < BLUR_THRESHOLD) {
142 c_t = (c_t - NOISE_THRESHOLD) / t_range;
143 c_t = pow(c_t, BLUR_CURVE);
144 c_t = c_t * t_range + NOISE_THRESHOLD;
145 c_t = c_t * sign(c);
146 } else {
147 c_t = c;
148 }
149
150 float cc = clamp(c_t + L_tex(HOOKED_pos).x, GAUSS_X2_tex(HOOKED_pos).y, GAUSS_X2_tex(HOOKED_pos).z) - L_tex(HOOKED_pos).x;
151
152 //This trick is only possible if the inverse Y->RGB matrix has 1 for every row... (which is the case for BT.709)
153 //Otherwise we would need to convert RGB to YUV, modify Y then convert back to RGB.
154 return HOOKED_tex(HOOKED_pos) + cc;
155}
156
157
158
1// MIT License
2
3// Copyright (c) 2019-2021 bloc97
4// All rights reserved.
5
6// Permission is hereby granted, free of charge, to any person obtaining a copy
7// of this software and associated documentation files (the "Software"), to deal
8// in the Software without restriction, including without limitation the rights
9// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10// copies of the Software, and to permit persons to whom the Software is
11// furnished to do so, subject to the following conditions:
13// The above copyright notice and this permission notice shall be included in all
14// copies or substantial portions of the Software.
16// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22// SOFTWARE.
24//!DESC Anime4K-v3.2-Upscale-Deblur-DoG-x2-Luma
25//!HOOK MAIN
26//!BIND HOOKED
27//!SAVE LINELUMA
28//!COMPONENTS 1
30float get_luma(vec4 rgba) {
31 return dot(vec4(0.299, 0.587, 0.114, 0.0), rgba);
32}
34vec4 hook() {
35 return vec4(get_luma(HOOKED_tex(HOOKED_pos)), 0.0, 0.0, 0.0);
36}
38//!DESC Anime4K-v3.2-Upscale-Deblur-DoG-x2-Kernel-X
39//!WHEN OUTPUT.w MAIN.w / 1.200 > OUTPUT.h MAIN.h / 1.200 > *
40//!HOOK MAIN
41//!BIND HOOKED
42//!BIND LINELUMA
43//!SAVE GAUSS_X2
44//!COMPONENTS 3
46#define L_tex LINELUMA_tex
48float max3v(float a, float b, float c) {
49 return max(max(a, b), c);
50}
51float min3v(float a, float b, float c) {
52 return min(min(a, b), c);
53}
55vec2 minmax3(vec2 pos, vec2 d) {
56 float a = L_tex(pos - d).x;
57 float b = L_tex(pos).x;
58 float c = L_tex(pos + d).x;
59
60 return vec2(min3v(a, b, c), max3v(a, b, c));
61}
63float lumGaussian7(vec2 pos, vec2 d) {
64 float g = (L_tex(pos - (d + d)).x + L_tex(pos + (d + d)).x) * 0.06136;
65 g = g + (L_tex(pos - d).x + L_tex(pos + d).x) * 0.24477;
66 g = g + (L_tex(pos).x) * 0.38774;
67
68 return g;
69}
72vec4 hook() {
73 return vec4(lumGaussian7(HOOKED_pos, vec2(HOOKED_pt.x, 0)), minmax3(HOOKED_pos, vec2(HOOKED_pt.x, 0)), 0);
74}
77//!DESC Anime4K-v3.2-Upscale-Deblur-DoG-x2-Kernel-Y
78//!WHEN OUTPUT.w MAIN.w / 1.200 > OUTPUT.h MAIN.h / 1.200 > *
79//!HOOK MAIN
80//!BIND HOOKED
81//!BIND GAUSS_X2
82//!SAVE GAUSS_X2
83//!COMPONENTS 3
85#define L_tex GAUSS_X2_tex
87float max3v(float a, float b, float c) {
88 return max(max(a, b), c);
89}
90float min3v(float a, float b, float c) {
91 return min(min(a, b), c);
92}
94vec2 minmax3(vec2 pos, vec2 d) {
95 float a0 = L_tex(pos - d).y;
96 float b0 = L_tex(pos).y;
97 float c0 = L_tex(pos + d).y;
98
99 float a1 = L_tex(pos - d).z;
100 float b1 = L_tex(pos).z;
101 float c1 = L_tex(pos + d).z;
102
103 return vec2(min3v(a0, b0, c0), max3v(a1, b1, c1));
104}
106float lumGaussian7(vec2 pos, vec2 d) {
107 float g = (L_tex(pos - (d + d)).x + L_tex(pos + (d + d)).x) * 0.06136;
108 g = g + (L_tex(pos - d).x + L_tex(pos + d).x) * 0.24477;
109 g = g + (L_tex(pos).x) * 0.38774;
110
111 return g;
112}
115vec4 hook() {
116 return vec4(lumGaussian7(HOOKED_pos, vec2(0, HOOKED_pt.y)), minmax3(HOOKED_pos, vec2(0, HOOKED_pt.y)), 0);
117}
119//!DESC Anime4K-v3.2-Upscale-Deblur-DoG-x2-Apply
120//!WHEN OUTPUT.w MAIN.w / 1.200 > OUTPUT.h MAIN.h / 1.200 > *
121//!HOOK MAIN
122//!BIND HOOKED
123//!BIND LINELUMA
124//!BIND GAUSS_X2
125//!WIDTH MAIN.w 2 *
126//!HEIGHT MAIN.h 2 *
128#define STRENGTH 0.6 //De-blur proportional strength, higher is sharper. However, it is better to tweak BLUR_CURVE instead to avoid ringing.
129#define BLUR_CURVE 0.6 //De-blur power curve, lower is sharper. Good values are between 0.3 - 1. Values greater than 1 softens the image;
130#define BLUR_THRESHOLD 0.1 //Value where curve kicks in, used to not de-blur already sharp edges. Only de-blur values that fall below this threshold.
131#define NOISE_THRESHOLD 0.001 //Value where curve stops, used to not sharpen noise. Only de-blur values that fall above this threshold.
133#define L_tex LINELUMA_tex
135vec4 hook() {
136 float c = (L_tex(HOOKED_pos).x - GAUSS_X2_tex(HOOKED_pos).x) * STRENGTH;
137
138 float t_range = BLUR_THRESHOLD - NOISE_THRESHOLD;
139
140 float c_t = abs(c);
141 if (c_t > NOISE_THRESHOLD && c_t < BLUR_THRESHOLD) {
142 c_t = (c_t - NOISE_THRESHOLD) / t_range;
143 c_t = pow(c_t, BLUR_CURVE);
144 c_t = c_t * t_range + NOISE_THRESHOLD;
145 c_t = c_t * sign(c);
146 } else {
147 c_t = c;
148 }
149
150 float cc = clamp(c_t + L_tex(HOOKED_pos).x, GAUSS_X2_tex(HOOKED_pos).y, GAUSS_X2_tex(HOOKED_pos).z) - L_tex(HOOKED_pos).x;
151
152 //This trick is only possible if the inverse Y->RGB matrix has 1 for every row... (which is the case for BT.709)
153 //Otherwise we would need to convert RGB to YUV, modify Y then convert back to RGB.
154 return HOOKED_tex(HOOKED_pos) + cc;
155}

mpv/shaders/Anime4K_Upscale_Deblur_Original_x2.glsl

Modified

+277 / −277 text lines

1// MIT License
2
3// Copyright (c) 2019-2021 bloc97
4// All rights reserved.
5
6// Permission is hereby granted, free of charge, to any person obtaining a copy
7// of this software and associated documentation files (the "Software"), to deal
8// in the Software without restriction, including without limitation the rights
9// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10// copies of the Software, and to permit persons to whom the Software is
11// furnished to do so, subject to the following conditions:
12
13// The above copyright notice and this permission notice shall be included in all
14// copies or substantial portions of the Software.
15
16// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22// SOFTWARE.
23
24//!DESC Anime4K-v3.2-Upscale-Deblur-Original-x2-Luma
25//!HOOK MAIN
26//!BIND HOOKED
27//!SAVE LINELUMA
28//!COMPONENTS 1
29
30float get_luma(vec4 rgba) {
31 return dot(vec4(0.299, 0.587, 0.114, 0.0), rgba);
32}
33
34vec4 hook() {
35 return vec4(get_luma(HOOKED_tex(HOOKED_pos)), 0.0, 0.0, 0.0);
36}
37
38//!DESC Anime4K-v3.2-Upscale-Deblur-Original-x2-Kernel-X
39//!HOOK MAIN
40//!BIND HOOKED
41//!BIND LINELUMA
42//!SAVE LUMAD
43//!WIDTH MAIN.w 2 *
44//!HEIGHT MAIN.h 2 *
45//!COMPONENTS 2
46
47vec4 hook() {
48 vec2 d = HOOKED_pt;
49
50 //[tl t tr]
51 //[ l c r]
52 //[bl b br]
53 float l = LINELUMA_tex(HOOKED_pos + vec2(-d.x, 0.0)).x;
54 float c = LINELUMA_tex(HOOKED_pos).x;
55 float r = LINELUMA_tex(HOOKED_pos + vec2(d.x, 0.0)).x;
56
57
58 //Horizontal Gradient
59 //[-1 0 1]
60 //[-2 0 2]
61 //[-1 0 1]
62 float xgrad = (-l + r);
63
64 //Vertical Gradient
65 //[-1 -2 -1]
66 //[ 0 0 0]
67 //[ 1 2 1]
68 float ygrad = (l + c + c + r);
69
70 //Computes the luminance's gradient
71 return vec4(xgrad, ygrad, 0.0, 0.0);
72}
73
74
75//!DESC Anime4K-v3.2-Upscale-Deblur-Original-x2-Kernel-Y
76//!HOOK MAIN
77//!BIND HOOKED
78//!BIND LUMAD
79//!SAVE LUMAD
80//!WIDTH MAIN.w 2 *
81//!HEIGHT MAIN.h 2 *
82//!COMPONENTS 2
83
84
85/* --------------------- SETTINGS --------------------- */
86
87//Strength of edge refinement, good values are between 0.2 and 4
88#define REFINE_STRENGTH 1.0
89
90
91/* --- MODIFY THESE SETTINGS BELOW AT YOUR OWN RISK --- */
92
93//Bias of the refinement function, good values are between 0 and 1
94#define REFINE_BIAS 0.0
95
96//Polynomial fit obtained by minimizing MSE error on image
97#define P5 ( 11.68129591)
98#define P4 (-42.46906057)
99#define P3 ( 60.28286266)
100#define P2 (-41.84451327)
101#define P1 ( 14.05517353)
102#define P0 (-1.081521930)
103
104/* ----------------- END OF SETTINGS ----------------- */
105
106float power_function(float x) {
107 float x2 = x * x;
108 float x3 = x2 * x;
109 float x4 = x2 * x2;
110 float x5 = x2 * x3;
111
112 return P5*x5 + P4*x4 + P3*x3 + P2*x2 + P1*x + P0;
113}
114
115vec4 hook() {
116 vec2 d = HOOKED_pt;
117
118 //[tl t tr]
119 //[ l cc r]
120 //[bl b br]
121 float tx = LUMAD_tex(HOOKED_pos + vec2(0.0, -d.y)).x;
122 float cx = LUMAD_tex(HOOKED_pos).x;
123 float bx = LUMAD_tex(HOOKED_pos + vec2(0.0, d.y)).x;
124
125
126 float ty = LUMAD_tex(HOOKED_pos + vec2(0.0, -d.y)).y;
127 //float cy = LUMAD_tex(HOOKED_pos).y;
128 float by = LUMAD_tex(HOOKED_pos + vec2(0.0, d.y)).y;
129
130
131 //Horizontal Gradient
132 //[-1 0 1]
133 //[-2 0 2]
134 //[-1 0 1]
135 float xgrad = (tx + cx + cx + bx);
136
137 //Vertical Gradient
138 //[-1 -2 -1]
139 //[ 0 0 0]
140 //[ 1 2 1]
141 float ygrad = (-ty + by);
142
143 //Computes the luminance's gradient
144 float sobel_norm = clamp(sqrt(xgrad * xgrad + ygrad * ygrad), 0.0, 1.0);
145
146 float dval = clamp(power_function(clamp(sobel_norm, 0.0, 1.0)) * REFINE_STRENGTH + REFINE_BIAS, 0.0, 1.0);
147
148 return vec4(sobel_norm, dval, 0.0, 0.0);
149}
150
151//!DESC Anime4K-v3.2-Upscale-Deblur-Original-x2-Kernel-X
152//!HOOK MAIN
153//!BIND HOOKED
154//!BIND LUMAD
155//!SAVE LUMAMM
156//!WIDTH MAIN.w 2 *
157//!HEIGHT MAIN.h 2 *
158//!COMPONENTS 2
159
160
161vec4 hook() {
162 vec2 d = HOOKED_pt;
163
164 if (LUMAD_tex(HOOKED_pos).y < 0.1) {
165 return vec4(0.0);
166 }
167
168 //[tl t tr]
169 //[ l c r]
170 //[bl b br]
171 float l = LUMAD_tex(HOOKED_pos + vec2(-d.x, 0.0)).x;
172 float c = LUMAD_tex(HOOKED_pos).x;
173 float r = LUMAD_tex(HOOKED_pos + vec2(d.x, 0.0)).x;
174
175 //Horizontal Gradient
176 //[-1 0 1]
177 //[-2 0 2]
178 //[-1 0 1]
179 float xgrad = (-l + r);
180
181 //Vertical Gradient
182 //[-1 -2 -1]
183 //[ 0 0 0]
184 //[ 1 2 1]
185 float ygrad = (l + c + c + r);
186
187
188 return vec4(xgrad, ygrad, 0.0, 0.0);
189}
190
191
192//!DESC Anime4K-v3.2-Upscale-Deblur-Original-x2-Kernel-Y
193//!HOOK MAIN
194//!BIND HOOKED
195//!BIND LUMAD
196//!BIND LUMAMM
197//!SAVE LUMAMM
198//!WIDTH MAIN.w 2 *
199//!HEIGHT MAIN.h 2 *
200//!COMPONENTS 2
201
202vec4 hook() {
203 vec2 d = HOOKED_pt;
204
205 if (LUMAD_tex(HOOKED_pos).y < 0.1) {
206 return vec4(0.0);
207 }
208
209 //[tl t tr]
210 //[ l cc r]
211 //[bl b br]
212 float tx = LUMAMM_tex(HOOKED_pos + vec2(0.0, -d.y)).x;
213 float cx = LUMAMM_tex(HOOKED_pos).x;
214 float bx = LUMAMM_tex(HOOKED_pos + vec2(0.0, d.y)).x;
215
216 float ty = LUMAMM_tex(HOOKED_pos + vec2(0.0, -d.y)).y;
217 //float cy = LUMAMM_tex(HOOKED_pos).y;
218 float by = LUMAMM_tex(HOOKED_pos + vec2(0.0, d.y)).y;
219
220 //Horizontal Gradient
221 //[-1 0 1]
222 //[-2 0 2]
223 //[-1 0 1]
224 float xgrad = (tx + cx + cx + bx);
225
226 //Vertical Gradient
227 //[-1 -2 -1]
228 //[ 0 0 0]
229 //[ 1 2 1]
230 float ygrad = (-ty + by);
231
232 float norm = sqrt(xgrad * xgrad + ygrad * ygrad);
233 if (norm <= 0.001) {
234 xgrad = 0.0;
235 ygrad = 0.0;
236 norm = 1.0;
237 }
238
239 return vec4(xgrad/norm, ygrad/norm, 0.0, 0.0);
240}
241
242
243//!DESC Anime4K-v3.2-Upscale-Deblur-Original-x2-Apply
244//!HOOK MAIN
245//!BIND HOOKED
246//!BIND LUMAD
247//!BIND LUMAMM
248//!WIDTH MAIN.w 2 *
249//!HEIGHT MAIN.h 2 *
250
251
252vec4 hook() {
253 vec2 d = HOOKED_pt;
254
255 float dval = LUMAD_tex(HOOKED_pos).y;
256 if (dval < 0.1) {
257 return HOOKED_tex(HOOKED_pos);
258 }
259
260 vec4 dc = LUMAMM_tex(HOOKED_pos);
261 if (abs(dc.x + dc.y) <= 0.0001) {
262 return HOOKED_tex(HOOKED_pos);
263 }
264
265 float xpos = -sign(dc.x);
266 float ypos = -sign(dc.y);
267
268 vec4 xval = HOOKED_tex(HOOKED_pos + vec2(d.x * xpos, 0.0));
269 vec4 yval = HOOKED_tex(HOOKED_pos + vec2(0.0, d.y * ypos));
270
271 float xyratio = abs(dc.x) / (abs(dc.x) + abs(dc.y));
272
273 vec4 avg = xyratio * xval + (1.0 - xyratio) * yval;
274
275 return avg * dval + HOOKED_tex(HOOKED_pos) * (1.0 - dval);
276
277}
1// MIT License
2
3// Copyright (c) 2019-2021 bloc97
4// All rights reserved.
5
6// Permission is hereby granted, free of charge, to any person obtaining a copy
7// of this software and associated documentation files (the "Software"), to deal
8// in the Software without restriction, including without limitation the rights
9// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10// copies of the Software, and to permit persons to whom the Software is
11// furnished to do so, subject to the following conditions:
13// The above copyright notice and this permission notice shall be included in all
14// copies or substantial portions of the Software.
16// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22// SOFTWARE.
24//!DESC Anime4K-v3.2-Upscale-Deblur-Original-x2-Luma
25//!HOOK MAIN
26//!BIND HOOKED
27//!SAVE LINELUMA
28//!COMPONENTS 1
30float get_luma(vec4 rgba) {
31 return dot(vec4(0.299, 0.587, 0.114, 0.0), rgba);
32}
34vec4 hook() {
35 return vec4(get_luma(HOOKED_tex(HOOKED_pos)), 0.0, 0.0, 0.0);
36}
38//!DESC Anime4K-v3.2-Upscale-Deblur-Original-x2-Kernel-X
39//!HOOK MAIN
40//!BIND HOOKED
41//!BIND LINELUMA
42//!SAVE LUMAD
43//!WIDTH MAIN.w 2 *
44//!HEIGHT MAIN.h 2 *
45//!COMPONENTS 2
47vec4 hook() {
48 vec2 d = HOOKED_pt;
49
50 //[tl t tr]
51 //[ l c r]
52 //[bl b br]
53 float l = LINELUMA_tex(HOOKED_pos + vec2(-d.x, 0.0)).x;
54 float c = LINELUMA_tex(HOOKED_pos).x;
55 float r = LINELUMA_tex(HOOKED_pos + vec2(d.x, 0.0)).x;
56
57
58 //Horizontal Gradient
59 //[-1 0 1]
60 //[-2 0 2]
61 //[-1 0 1]
62 float xgrad = (-l + r);
63
64 //Vertical Gradient
65 //[-1 -2 -1]
66 //[ 0 0 0]
67 //[ 1 2 1]
68 float ygrad = (l + c + c + r);
69
70 //Computes the luminance's gradient
71 return vec4(xgrad, ygrad, 0.0, 0.0);
72}
75//!DESC Anime4K-v3.2-Upscale-Deblur-Original-x2-Kernel-Y
76//!HOOK MAIN
77//!BIND HOOKED
78//!BIND LUMAD
79//!SAVE LUMAD
80//!WIDTH MAIN.w 2 *
81//!HEIGHT MAIN.h 2 *
82//!COMPONENTS 2
85/* --------------------- SETTINGS --------------------- */
87//Strength of edge refinement, good values are between 0.2 and 4
88#define REFINE_STRENGTH 1.0
91/* --- MODIFY THESE SETTINGS BELOW AT YOUR OWN RISK --- */
93//Bias of the refinement function, good values are between 0 and 1
94#define REFINE_BIAS 0.0
96//Polynomial fit obtained by minimizing MSE error on image
97#define P5 ( 11.68129591)
98#define P4 (-42.46906057)
99#define P3 ( 60.28286266)
100#define P2 (-41.84451327)
101#define P1 ( 14.05517353)
102#define P0 (-1.081521930)
104/* ----------------- END OF SETTINGS ----------------- */
106float power_function(float x) {
107 float x2 = x * x;
108 float x3 = x2 * x;
109 float x4 = x2 * x2;
110 float x5 = x2 * x3;
111
112 return P5*x5 + P4*x4 + P3*x3 + P2*x2 + P1*x + P0;
113}
115vec4 hook() {
116 vec2 d = HOOKED_pt;
117
118 //[tl t tr]
119 //[ l cc r]
120 //[bl b br]
121 float tx = LUMAD_tex(HOOKED_pos + vec2(0.0, -d.y)).x;
122 float cx = LUMAD_tex(HOOKED_pos).x;
123 float bx = LUMAD_tex(HOOKED_pos + vec2(0.0, d.y)).x;
124
125
126 float ty = LUMAD_tex(HOOKED_pos + vec2(0.0, -d.y)).y;
127 //float cy = LUMAD_tex(HOOKED_pos).y;
128 float by = LUMAD_tex(HOOKED_pos + vec2(0.0, d.y)).y;
129
130
131 //Horizontal Gradient
132 //[-1 0 1]
133 //[-2 0 2]
134 //[-1 0 1]
135 float xgrad = (tx + cx + cx + bx);
136
137 //Vertical Gradient
138 //[-1 -2 -1]
139 //[ 0 0 0]
140 //[ 1 2 1]
141 float ygrad = (-ty + by);
142
143 //Computes the luminance's gradient
144 float sobel_norm = clamp(sqrt(xgrad * xgrad + ygrad * ygrad), 0.0, 1.0);
145
146 float dval = clamp(power_function(clamp(sobel_norm, 0.0, 1.0)) * REFINE_STRENGTH + REFINE_BIAS, 0.0, 1.0);
147
148 return vec4(sobel_norm, dval, 0.0, 0.0);
149}
151//!DESC Anime4K-v3.2-Upscale-Deblur-Original-x2-Kernel-X
152//!HOOK MAIN
153//!BIND HOOKED
154//!BIND LUMAD
155//!SAVE LUMAMM
156//!WIDTH MAIN.w 2 *
157//!HEIGHT MAIN.h 2 *
158//!COMPONENTS 2
161vec4 hook() {
162 vec2 d = HOOKED_pt;
163
164 if (LUMAD_tex(HOOKED_pos).y < 0.1) {
165 return vec4(0.0);
166 }
167
168 //[tl t tr]
169 //[ l c r]
170 //[bl b br]
171 float l = LUMAD_tex(HOOKED_pos + vec2(-d.x, 0.0)).x;
172 float c = LUMAD_tex(HOOKED_pos).x;
173 float r = LUMAD_tex(HOOKED_pos + vec2(d.x, 0.0)).x;
174
175 //Horizontal Gradient
176 //[-1 0 1]
177 //[-2 0 2]
178 //[-1 0 1]
179 float xgrad = (-l + r);
180
181 //Vertical Gradient
182 //[-1 -2 -1]
183 //[ 0 0 0]
184 //[ 1 2 1]
185 float ygrad = (l + c + c + r);
186
187
188 return vec4(xgrad, ygrad, 0.0, 0.0);
189}
192//!DESC Anime4K-v3.2-Upscale-Deblur-Original-x2-Kernel-Y
193//!HOOK MAIN
194//!BIND HOOKED
195//!BIND LUMAD
196//!BIND LUMAMM
197//!SAVE LUMAMM
198//!WIDTH MAIN.w 2 *
199//!HEIGHT MAIN.h 2 *
200//!COMPONENTS 2
202vec4 hook() {
203 vec2 d = HOOKED_pt;
204
205 if (LUMAD_tex(HOOKED_pos).y < 0.1) {
206 return vec4(0.0);
207 }
208
209 //[tl t tr]
210 //[ l cc r]
211 //[bl b br]
212 float tx = LUMAMM_tex(HOOKED_pos + vec2(0.0, -d.y)).x;
213 float cx = LUMAMM_tex(HOOKED_pos).x;
214 float bx = LUMAMM_tex(HOOKED_pos + vec2(0.0, d.y)).x;
215
216 float ty = LUMAMM_tex(HOOKED_pos + vec2(0.0, -d.y)).y;
217 //float cy = LUMAMM_tex(HOOKED_pos).y;
218 float by = LUMAMM_tex(HOOKED_pos + vec2(0.0, d.y)).y;
219
220 //Horizontal Gradient
221 //[-1 0 1]
222 //[-2 0 2]
223 //[-1 0 1]
224 float xgrad = (tx + cx + cx + bx);
225
226 //Vertical Gradient
227 //[-1 -2 -1]
228 //[ 0 0 0]
229 //[ 1 2 1]
230 float ygrad = (-ty + by);
231
232 float norm = sqrt(xgrad * xgrad + ygrad * ygrad);
233 if (norm <= 0.001) {
234 xgrad = 0.0;
235 ygrad = 0.0;
236 norm = 1.0;
237 }
238
239 return vec4(xgrad/norm, ygrad/norm, 0.0, 0.0);
240}
243//!DESC Anime4K-v3.2-Upscale-Deblur-Original-x2-Apply
244//!HOOK MAIN
245//!BIND HOOKED
246//!BIND LUMAD
247//!BIND LUMAMM
248//!WIDTH MAIN.w 2 *
249//!HEIGHT MAIN.h 2 *
252vec4 hook() {
253 vec2 d = HOOKED_pt;
254
255 float dval = LUMAD_tex(HOOKED_pos).y;
256 if (dval < 0.1) {
257 return HOOKED_tex(HOOKED_pos);
258 }
259
260 vec4 dc = LUMAMM_tex(HOOKED_pos);
261 if (abs(dc.x + dc.y) <= 0.0001) {
262 return HOOKED_tex(HOOKED_pos);
263 }
264
265 float xpos = -sign(dc.x);
266 float ypos = -sign(dc.y);
267
268 vec4 xval = HOOKED_tex(HOOKED_pos + vec2(d.x * xpos, 0.0));
269 vec4 yval = HOOKED_tex(HOOKED_pos + vec2(0.0, d.y * ypos));
270
271 float xyratio = abs(dc.x) / (abs(dc.x) + abs(dc.y));
272
273 vec4 avg = xyratio * xval + (1.0 - xyratio) * yval;
274
275 return avg * dval + HOOKED_tex(HOOKED_pos) * (1.0 - dval);
276
277}

mpv/shaders/Anime4K_Upscale_DoG_x2.glsl

Modified

+143 / −143 text lines

1// MIT License
2
3// Copyright (c) 2019-2021 bloc97
4// All rights reserved.
5
6// Permission is hereby granted, free of charge, to any person obtaining a copy
7// of this software and associated documentation files (the "Software"), to deal
8// in the Software without restriction, including without limitation the rights
9// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10// copies of the Software, and to permit persons to whom the Software is
11// furnished to do so, subject to the following conditions:
12
13// The above copyright notice and this permission notice shall be included in all
14// copies or substantial portions of the Software.
15
16// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22// SOFTWARE.
23
24//!DESC Anime4K-v3.2-Upscale-DoG-x2-Luma
25//!HOOK MAIN
26//!BIND HOOKED
27//!SAVE LINELUMA
28//!COMPONENTS 1
29
30float get_luma(vec4 rgba) {
31 return dot(vec4(0.299, 0.587, 0.114, 0.0), rgba);
32}
33
34vec4 hook() {
35 return vec4(get_luma(HOOKED_tex(HOOKED_pos)), 0.0, 0.0, 0.0);
36}
37
38//!DESC Anime4K-v3.2-Upscale-DoG-x2-Kernel-X
39//!WHEN OUTPUT.w MAIN.w / 1.200 > OUTPUT.h MAIN.h / 1.200 > *
40//!HOOK MAIN
41//!BIND HOOKED
42//!BIND LINELUMA
43//!SAVE GAUSS_X2
44//!COMPONENTS 3
45
46#define L_tex LINELUMA_tex
47
48float max3v(float a, float b, float c) {
49 return max(max(a, b), c);
50}
51float min3v(float a, float b, float c) {
52 return min(min(a, b), c);
53}
54
55vec2 minmax3(vec2 pos, vec2 d) {
56 float a = L_tex(pos - d).x;
57 float b = L_tex(pos).x;
58 float c = L_tex(pos + d).x;
59
60 return vec2(min3v(a, b, c), max3v(a, b, c));
61}
62
63float lumGaussian7(vec2 pos, vec2 d) {
64 float g = (L_tex(pos - (d + d)).x + L_tex(pos + (d + d)).x) * 0.06136;
65 g = g + (L_tex(pos - d).x + L_tex(pos + d).x) * 0.24477;
66 g = g + (L_tex(pos).x) * 0.38774;
67
68 return g;
69}
70
71
72vec4 hook() {
73 return vec4(lumGaussian7(HOOKED_pos, vec2(HOOKED_pt.x, 0)), minmax3(HOOKED_pos, vec2(HOOKED_pt.x, 0)), 0);
74}
75
76
77//!DESC Anime4K-v3.2-Upscale-DoG-x2-Kernel-Y
78//!WHEN OUTPUT.w MAIN.w / 1.200 > OUTPUT.h MAIN.h / 1.200 > *
79//!HOOK MAIN
80//!BIND HOOKED
81//!BIND GAUSS_X2
82//!SAVE GAUSS_X2
83//!COMPONENTS 3
84
85#define L_tex GAUSS_X2_tex
86
87float max3v(float a, float b, float c) {
88 return max(max(a, b), c);
89}
90float min3v(float a, float b, float c) {
91 return min(min(a, b), c);
92}
93
94vec2 minmax3(vec2 pos, vec2 d) {
95 float a0 = L_tex(pos - d).y;
96 float b0 = L_tex(pos).y;
97 float c0 = L_tex(pos + d).y;
98
99 float a1 = L_tex(pos - d).z;
100 float b1 = L_tex(pos).z;
101 float c1 = L_tex(pos + d).z;
102
103 return vec2(min3v(a0, b0, c0), max3v(a1, b1, c1));
104}
105
106float lumGaussian7(vec2 pos, vec2 d) {
107 float g = (L_tex(pos - (d + d)).x + L_tex(pos + (d + d)).x) * 0.06136;
108 g = g + (L_tex(pos - d).x + L_tex(pos + d).x) * 0.24477;
109 g = g + (L_tex(pos).x) * 0.38774;
110
111 return g;
112}
113
114
115vec4 hook() {
116 return vec4(lumGaussian7(HOOKED_pos, vec2(0, HOOKED_pt.y)), minmax3(HOOKED_pos, vec2(0, HOOKED_pt.y)), 0);
117}
118
119//!DESC Anime4K-v3.2-Upscale-DoG-x2-Apply
120//!WHEN OUTPUT.w MAIN.w / 1.200 > OUTPUT.h MAIN.h / 1.200 > *
121//!HOOK MAIN
122//!BIND HOOKED
123//!BIND LINELUMA
124//!BIND GAUSS_X2
125//!WIDTH MAIN.w 2 *
126//!HEIGHT MAIN.h 2 *
127
128#define STRENGTH 0.8 //De-blur proportional strength, higher is sharper.
129
130#define L_tex LINELUMA_tex
131
132vec4 hook() {
133
134 float c = (L_tex(HOOKED_pos).x - GAUSS_X2_tex(HOOKED_pos).x) * STRENGTH;
135 float cc = clamp(c + L_tex(HOOKED_pos).x, GAUSS_X2_tex(HOOKED_pos).y, GAUSS_X2_tex(HOOKED_pos).z) - L_tex(HOOKED_pos).x;
136
137 //This trick is only possible if the inverse Y->RGB matrix has 1 for every row... (which is the case for BT.709)
138 //Otherwise we would need to convert RGB to YUV, modify Y then convert back to RGB.
139 return HOOKED_tex(HOOKED_pos) + cc;
140}
141
142
143
1// MIT License
2
3// Copyright (c) 2019-2021 bloc97
4// All rights reserved.
5
6// Permission is hereby granted, free of charge, to any person obtaining a copy
7// of this software and associated documentation files (the "Software"), to deal
8// in the Software without restriction, including without limitation the rights
9// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10// copies of the Software, and to permit persons to whom the Software is
11// furnished to do so, subject to the following conditions:
13// The above copyright notice and this permission notice shall be included in all
14// copies or substantial portions of the Software.
16// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22// SOFTWARE.
24//!DESC Anime4K-v3.2-Upscale-DoG-x2-Luma
25//!HOOK MAIN
26//!BIND HOOKED
27//!SAVE LINELUMA
28//!COMPONENTS 1
30float get_luma(vec4 rgba) {
31 return dot(vec4(0.299, 0.587, 0.114, 0.0), rgba);
32}
34vec4 hook() {
35 return vec4(get_luma(HOOKED_tex(HOOKED_pos)), 0.0, 0.0, 0.0);
36}
38//!DESC Anime4K-v3.2-Upscale-DoG-x2-Kernel-X
39//!WHEN OUTPUT.w MAIN.w / 1.200 > OUTPUT.h MAIN.h / 1.200 > *
40//!HOOK MAIN
41//!BIND HOOKED
42//!BIND LINELUMA
43//!SAVE GAUSS_X2
44//!COMPONENTS 3
46#define L_tex LINELUMA_tex
48float max3v(float a, float b, float c) {
49 return max(max(a, b), c);
50}
51float min3v(float a, float b, float c) {
52 return min(min(a, b), c);
53}
55vec2 minmax3(vec2 pos, vec2 d) {
56 float a = L_tex(pos - d).x;
57 float b = L_tex(pos).x;
58 float c = L_tex(pos + d).x;
59
60 return vec2(min3v(a, b, c), max3v(a, b, c));
61}
63float lumGaussian7(vec2 pos, vec2 d) {
64 float g = (L_tex(pos - (d + d)).x + L_tex(pos + (d + d)).x) * 0.06136;
65 g = g + (L_tex(pos - d).x + L_tex(pos + d).x) * 0.24477;
66 g = g + (L_tex(pos).x) * 0.38774;
67
68 return g;
69}
72vec4 hook() {
73 return vec4(lumGaussian7(HOOKED_pos, vec2(HOOKED_pt.x, 0)), minmax3(HOOKED_pos, vec2(HOOKED_pt.x, 0)), 0);
74}
77//!DESC Anime4K-v3.2-Upscale-DoG-x2-Kernel-Y
78//!WHEN OUTPUT.w MAIN.w / 1.200 > OUTPUT.h MAIN.h / 1.200 > *
79//!HOOK MAIN
80//!BIND HOOKED
81//!BIND GAUSS_X2
82//!SAVE GAUSS_X2
83//!COMPONENTS 3
85#define L_tex GAUSS_X2_tex
87float max3v(float a, float b, float c) {
88 return max(max(a, b), c);
89}
90float min3v(float a, float b, float c) {
91 return min(min(a, b), c);
92}
94vec2 minmax3(vec2 pos, vec2 d) {
95 float a0 = L_tex(pos - d).y;
96 float b0 = L_tex(pos).y;
97 float c0 = L_tex(pos + d).y;
98
99 float a1 = L_tex(pos - d).z;
100 float b1 = L_tex(pos).z;
101 float c1 = L_tex(pos + d).z;
102
103 return vec2(min3v(a0, b0, c0), max3v(a1, b1, c1));
104}
106float lumGaussian7(vec2 pos, vec2 d) {
107 float g = (L_tex(pos - (d + d)).x + L_tex(pos + (d + d)).x) * 0.06136;
108 g = g + (L_tex(pos - d).x + L_tex(pos + d).x) * 0.24477;
109 g = g + (L_tex(pos).x) * 0.38774;
110
111 return g;
112}
115vec4 hook() {
116 return vec4(lumGaussian7(HOOKED_pos, vec2(0, HOOKED_pt.y)), minmax3(HOOKED_pos, vec2(0, HOOKED_pt.y)), 0);
117}
119//!DESC Anime4K-v3.2-Upscale-DoG-x2-Apply
120//!WHEN OUTPUT.w MAIN.w / 1.200 > OUTPUT.h MAIN.h / 1.200 > *
121//!HOOK MAIN
122//!BIND HOOKED
123//!BIND LINELUMA
124//!BIND GAUSS_X2
125//!WIDTH MAIN.w 2 *
126//!HEIGHT MAIN.h 2 *
128#define STRENGTH 0.8 //De-blur proportional strength, higher is sharper.
130#define L_tex LINELUMA_tex
132vec4 hook() {
134 float c = (L_tex(HOOKED_pos).x - GAUSS_X2_tex(HOOKED_pos).x) * STRENGTH;
135 float cc = clamp(c + L_tex(HOOKED_pos).x, GAUSS_X2_tex(HOOKED_pos).y, GAUSS_X2_tex(HOOKED_pos).z) - L_tex(HOOKED_pos).x;
136
137 //This trick is only possible if the inverse Y->RGB matrix has 1 for every row... (which is the case for BT.709)
138 //Otherwise we would need to convert RGB to YUV, modify Y then convert back to RGB.
139 return HOOKED_tex(HOOKED_pos) + cc;
140}

mpv/shaders/Anime4K_Upscale_Original_x2.glsl

Modified

+277 / −277 text lines

1// MIT License
2
3// Copyright (c) 2019-2021 bloc97
4// All rights reserved.
5
6// Permission is hereby granted, free of charge, to any person obtaining a copy
7// of this software and associated documentation files (the "Software"), to deal
8// in the Software without restriction, including without limitation the rights
9// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10// copies of the Software, and to permit persons to whom the Software is
11// furnished to do so, subject to the following conditions:
12
13// The above copyright notice and this permission notice shall be included in all
14// copies or substantial portions of the Software.
15
16// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22// SOFTWARE.
23
24//!DESC Anime4K-v3.2-Upscale-Original-x2-Luma
25//!HOOK MAIN
26//!BIND HOOKED
27//!SAVE LINELUMA
28//!COMPONENTS 1
29
30float get_luma(vec4 rgba) {
31 return dot(vec4(0.299, 0.587, 0.114, 0.0), rgba);
32}
33
34vec4 hook() {
35 return vec4(get_luma(HOOKED_tex(HOOKED_pos)), 0.0, 0.0, 0.0);
36}
37
38//!DESC Anime4K-v3.2-Upscale-Original-x2-Kernel-X
39//!HOOK MAIN
40//!BIND HOOKED
41//!BIND LINELUMA
42//!SAVE LUMAD
43//!WIDTH MAIN.w 2 *
44//!HEIGHT MAIN.h 2 *
45//!COMPONENTS 2
46
47vec4 hook() {
48 vec2 d = HOOKED_pt;
49
50 //[tl t tr]
51 //[ l c r]
52 //[bl b br]
53 float l = LINELUMA_tex(HOOKED_pos + vec2(-d.x, 0.0)).x;
54 float c = LINELUMA_tex(HOOKED_pos).x;
55 float r = LINELUMA_tex(HOOKED_pos + vec2(d.x, 0.0)).x;
56
57
58 //Horizontal Gradient
59 //[-1 0 1]
60 //[-2 0 2]
61 //[-1 0 1]
62 float xgrad = (-l + r);
63
64 //Vertical Gradient
65 //[-1 -2 -1]
66 //[ 0 0 0]
67 //[ 1 2 1]
68 float ygrad = (l + c + c + r);
69
70 //Computes the luminance's gradient
71 return vec4(xgrad, ygrad, 0.0, 0.0);
72}
73
74
75//!DESC Anime4K-v3.2-Upscale-Original-x2-Kernel-Y
76//!HOOK MAIN
77//!BIND HOOKED
78//!BIND LUMAD
79//!SAVE LUMAD
80//!WIDTH MAIN.w 2 *
81//!HEIGHT MAIN.h 2 *
82//!COMPONENTS 2
83
84
85/* --------------------- SETTINGS --------------------- */
86
87//Strength of edge refinement, good values are between 0.2 and 4
88#define REFINE_STRENGTH 0.5
89
90
91/* --- MODIFY THESE SETTINGS BELOW AT YOUR OWN RISK --- */
92
93//Bias of the refinement function, good values are between 0 and 1
94#define REFINE_BIAS 0.0
95
96//Polynomial fit obtained by minimizing MSE error on image
97#define P5 ( 11.68129591)
98#define P4 (-42.46906057)
99#define P3 ( 60.28286266)
100#define P2 (-41.84451327)
101#define P1 ( 14.05517353)
102#define P0 (-1.081521930)
103
104/* ----------------- END OF SETTINGS ----------------- */
105
106float power_function(float x) {
107 float x2 = x * x;
108 float x3 = x2 * x;
109 float x4 = x2 * x2;
110 float x5 = x2 * x3;
111
112 return P5*x5 + P4*x4 + P3*x3 + P2*x2 + P1*x + P0;
113}
114
115vec4 hook() {
116 vec2 d = HOOKED_pt;
117
118 //[tl t tr]
119 //[ l cc r]
120 //[bl b br]
121 float tx = LUMAD_tex(HOOKED_pos + vec2(0.0, -d.y)).x;
122 float cx = LUMAD_tex(HOOKED_pos).x;
123 float bx = LUMAD_tex(HOOKED_pos + vec2(0.0, d.y)).x;
124
125
126 float ty = LUMAD_tex(HOOKED_pos + vec2(0.0, -d.y)).y;
127 //float cy = LUMAD_tex(HOOKED_pos).y;
128 float by = LUMAD_tex(HOOKED_pos + vec2(0.0, d.y)).y;
129
130
131 //Horizontal Gradient
132 //[-1 0 1]
133 //[-2 0 2]
134 //[-1 0 1]
135 float xgrad = (tx + cx + cx + bx);
136
137 //Vertical Gradient
138 //[-1 -2 -1]
139 //[ 0 0 0]
140 //[ 1 2 1]
141 float ygrad = (-ty + by);
142
143 //Computes the luminance's gradient
144 float sobel_norm = clamp(sqrt(xgrad * xgrad + ygrad * ygrad), 0.0, 1.0);
145
146 float dval = clamp(power_function(clamp(sobel_norm, 0.0, 1.0)) * REFINE_STRENGTH + REFINE_BIAS, 0.0, 1.0);
147
148 return vec4(sobel_norm, dval, 0.0, 0.0);
149}
150
151//!DESC Anime4K-v3.2-Upscale-Original-x2-Kernel-X
152//!HOOK MAIN
153//!BIND HOOKED
154//!BIND LUMAD
155//!SAVE LUMAMM
156//!WIDTH MAIN.w 2 *
157//!HEIGHT MAIN.h 2 *
158//!COMPONENTS 2
159
160
161vec4 hook() {
162 vec2 d = HOOKED_pt;
163
164 if (LUMAD_tex(HOOKED_pos).y < 0.1) {
165 return vec4(0.0);
166 }
167
168 //[tl t tr]
169 //[ l c r]
170 //[bl b br]
171 float l = LUMAD_tex(HOOKED_pos + vec2(-d.x, 0.0)).x;
172 float c = LUMAD_tex(HOOKED_pos).x;
173 float r = LUMAD_tex(HOOKED_pos + vec2(d.x, 0.0)).x;
174
175 //Horizontal Gradient
176 //[-1 0 1]
177 //[-2 0 2]
178 //[-1 0 1]
179 float xgrad = (-l + r);
180
181 //Vertical Gradient
182 //[-1 -2 -1]
183 //[ 0 0 0]
184 //[ 1 2 1]
185 float ygrad = (l + c + c + r);
186
187
188 return vec4(xgrad, ygrad, 0.0, 0.0);
189}
190
191
192//!DESC Anime4K-v3.2-Upscale-Original-x2-Kernel-Y
193//!HOOK MAIN
194//!BIND HOOKED
195//!BIND LUMAD
196//!BIND LUMAMM
197//!SAVE LUMAMM
198//!WIDTH MAIN.w 2 *
199//!HEIGHT MAIN.h 2 *
200//!COMPONENTS 2
201
202vec4 hook() {
203 vec2 d = HOOKED_pt;
204
205 if (LUMAD_tex(HOOKED_pos).y < 0.1) {
206 return vec4(0.0);
207 }
208
209 //[tl t tr]
210 //[ l cc r]
211 //[bl b br]
212 float tx = LUMAMM_tex(HOOKED_pos + vec2(0.0, -d.y)).x;
213 float cx = LUMAMM_tex(HOOKED_pos).x;
214 float bx = LUMAMM_tex(HOOKED_pos + vec2(0.0, d.y)).x;
215
216 float ty = LUMAMM_tex(HOOKED_pos + vec2(0.0, -d.y)).y;
217 //float cy = LUMAMM_tex(HOOKED_pos).y;
218 float by = LUMAMM_tex(HOOKED_pos + vec2(0.0, d.y)).y;
219
220 //Horizontal Gradient
221 //[-1 0 1]
222 //[-2 0 2]
223 //[-1 0 1]
224 float xgrad = (tx + cx + cx + bx);
225
226 //Vertical Gradient
227 //[-1 -2 -1]
228 //[ 0 0 0]
229 //[ 1 2 1]
230 float ygrad = (-ty + by);
231
232 float norm = sqrt(xgrad * xgrad + ygrad * ygrad);
233 if (norm <= 0.001) {
234 xgrad = 0.0;
235 ygrad = 0.0;
236 norm = 1.0;
237 }
238
239 return vec4(xgrad/norm, ygrad/norm, 0.0, 0.0);
240}
241
242
243//!DESC Anime4K-v3.2-Upscale-Original-x2-Apply
244//!HOOK MAIN
245//!BIND HOOKED
246//!BIND LUMAD
247//!BIND LUMAMM
248//!WIDTH MAIN.w 2 *
249//!HEIGHT MAIN.h 2 *
250
251
252vec4 hook() {
253 vec2 d = HOOKED_pt;
254
255 float dval = LUMAD_tex(HOOKED_pos).y;
256 if (dval < 0.1) {
257 return HOOKED_tex(HOOKED_pos);
258 }
259
260 vec4 dc = LUMAMM_tex(HOOKED_pos);
261 if (abs(dc.x + dc.y) <= 0.0001) {
262 return HOOKED_tex(HOOKED_pos);
263 }
264
265 float xpos = -sign(dc.x);
266 float ypos = -sign(dc.y);
267
268 vec4 xval = HOOKED_tex(HOOKED_pos + vec2(d.x * xpos, 0.0));
269 vec4 yval = HOOKED_tex(HOOKED_pos + vec2(0.0, d.y * ypos));
270
271 float xyratio = abs(dc.x) / (abs(dc.x) + abs(dc.y));
272
273 vec4 avg = xyratio * xval + (1.0 - xyratio) * yval;
274
275 return avg * dval + HOOKED_tex(HOOKED_pos) * (1.0 - dval);
276
277}
1// MIT License
2
3// Copyright (c) 2019-2021 bloc97
4// All rights reserved.
5
6// Permission is hereby granted, free of charge, to any person obtaining a copy
7// of this software and associated documentation files (the "Software"), to deal
8// in the Software without restriction, including without limitation the rights
9// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10// copies of the Software, and to permit persons to whom the Software is
11// furnished to do so, subject to the following conditions:
13// The above copyright notice and this permission notice shall be included in all
14// copies or substantial portions of the Software.
16// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22// SOFTWARE.
24//!DESC Anime4K-v3.2-Upscale-Original-x2-Luma
25//!HOOK MAIN
26//!BIND HOOKED
27//!SAVE LINELUMA
28//!COMPONENTS 1
30float get_luma(vec4 rgba) {
31 return dot(vec4(0.299, 0.587, 0.114, 0.0), rgba);
32}
34vec4 hook() {
35 return vec4(get_luma(HOOKED_tex(HOOKED_pos)), 0.0, 0.0, 0.0);
36}
38//!DESC Anime4K-v3.2-Upscale-Original-x2-Kernel-X
39//!HOOK MAIN
40//!BIND HOOKED
41//!BIND LINELUMA
42//!SAVE LUMAD
43//!WIDTH MAIN.w 2 *
44//!HEIGHT MAIN.h 2 *
45//!COMPONENTS 2
47vec4 hook() {
48 vec2 d = HOOKED_pt;
49
50 //[tl t tr]
51 //[ l c r]
52 //[bl b br]
53 float l = LINELUMA_tex(HOOKED_pos + vec2(-d.x, 0.0)).x;
54 float c = LINELUMA_tex(HOOKED_pos).x;
55 float r = LINELUMA_tex(HOOKED_pos + vec2(d.x, 0.0)).x;
56
57
58 //Horizontal Gradient
59 //[-1 0 1]
60 //[-2 0 2]
61 //[-1 0 1]
62 float xgrad = (-l + r);
63
64 //Vertical Gradient
65 //[-1 -2 -1]
66 //[ 0 0 0]
67 //[ 1 2 1]
68 float ygrad = (l + c + c + r);
69
70 //Computes the luminance's gradient
71 return vec4(xgrad, ygrad, 0.0, 0.0);
72}
75//!DESC Anime4K-v3.2-Upscale-Original-x2-Kernel-Y
76//!HOOK MAIN
77//!BIND HOOKED
78//!BIND LUMAD
79//!SAVE LUMAD
80//!WIDTH MAIN.w 2 *
81//!HEIGHT MAIN.h 2 *
82//!COMPONENTS 2
85/* --------------------- SETTINGS --------------------- */
87//Strength of edge refinement, good values are between 0.2 and 4
88#define REFINE_STRENGTH 0.5
91/* --- MODIFY THESE SETTINGS BELOW AT YOUR OWN RISK --- */
93//Bias of the refinement function, good values are between 0 and 1
94#define REFINE_BIAS 0.0
96//Polynomial fit obtained by minimizing MSE error on image
97#define P5 ( 11.68129591)
98#define P4 (-42.46906057)
99#define P3 ( 60.28286266)
100#define P2 (-41.84451327)
101#define P1 ( 14.05517353)
102#define P0 (-1.081521930)
104/* ----------------- END OF SETTINGS ----------------- */
106float power_function(float x) {
107 float x2 = x * x;
108 float x3 = x2 * x;
109 float x4 = x2 * x2;
110 float x5 = x2 * x3;
111
112 return P5*x5 + P4*x4 + P3*x3 + P2*x2 + P1*x + P0;
113}
115vec4 hook() {
116 vec2 d = HOOKED_pt;
117
118 //[tl t tr]
119 //[ l cc r]
120 //[bl b br]
121 float tx = LUMAD_tex(HOOKED_pos + vec2(0.0, -d.y)).x;
122 float cx = LUMAD_tex(HOOKED_pos).x;
123 float bx = LUMAD_tex(HOOKED_pos + vec2(0.0, d.y)).x;
124
125
126 float ty = LUMAD_tex(HOOKED_pos + vec2(0.0, -d.y)).y;
127 //float cy = LUMAD_tex(HOOKED_pos).y;
128 float by = LUMAD_tex(HOOKED_pos + vec2(0.0, d.y)).y;
129
130
131 //Horizontal Gradient
132 //[-1 0 1]
133 //[-2 0 2]
134 //[-1 0 1]
135 float xgrad = (tx + cx + cx + bx);
136
137 //Vertical Gradient
138 //[-1 -2 -1]
139 //[ 0 0 0]
140 //[ 1 2 1]
141 float ygrad = (-ty + by);
142
143 //Computes the luminance's gradient
144 float sobel_norm = clamp(sqrt(xgrad * xgrad + ygrad * ygrad), 0.0, 1.0);
145
146 float dval = clamp(power_function(clamp(sobel_norm, 0.0, 1.0)) * REFINE_STRENGTH + REFINE_BIAS, 0.0, 1.0);
147
148 return vec4(sobel_norm, dval, 0.0, 0.0);
149}
151//!DESC Anime4K-v3.2-Upscale-Original-x2-Kernel-X
152//!HOOK MAIN
153//!BIND HOOKED
154//!BIND LUMAD
155//!SAVE LUMAMM
156//!WIDTH MAIN.w 2 *
157//!HEIGHT MAIN.h 2 *
158//!COMPONENTS 2
161vec4 hook() {
162 vec2 d = HOOKED_pt;
163
164 if (LUMAD_tex(HOOKED_pos).y < 0.1) {
165 return vec4(0.0);
166 }
167
168 //[tl t tr]
169 //[ l c r]
170 //[bl b br]
171 float l = LUMAD_tex(HOOKED_pos + vec2(-d.x, 0.0)).x;
172 float c = LUMAD_tex(HOOKED_pos).x;
173 float r = LUMAD_tex(HOOKED_pos + vec2(d.x, 0.0)).x;
174
175 //Horizontal Gradient
176 //[-1 0 1]
177 //[-2 0 2]
178 //[-1 0 1]
179 float xgrad = (-l + r);
180
181 //Vertical Gradient
182 //[-1 -2 -1]
183 //[ 0 0 0]
184 //[ 1 2 1]
185 float ygrad = (l + c + c + r);
186
187
188 return vec4(xgrad, ygrad, 0.0, 0.0);
189}
192//!DESC Anime4K-v3.2-Upscale-Original-x2-Kernel-Y
193//!HOOK MAIN
194//!BIND HOOKED
195//!BIND LUMAD
196//!BIND LUMAMM
197//!SAVE LUMAMM
198//!WIDTH MAIN.w 2 *
199//!HEIGHT MAIN.h 2 *
200//!COMPONENTS 2
202vec4 hook() {
203 vec2 d = HOOKED_pt;
204
205 if (LUMAD_tex(HOOKED_pos).y < 0.1) {
206 return vec4(0.0);
207 }
208
209 //[tl t tr]
210 //[ l cc r]
211 //[bl b br]
212 float tx = LUMAMM_tex(HOOKED_pos + vec2(0.0, -d.y)).x;
213 float cx = LUMAMM_tex(HOOKED_pos).x;
214 float bx = LUMAMM_tex(HOOKED_pos + vec2(0.0, d.y)).x;
215
216 float ty = LUMAMM_tex(HOOKED_pos + vec2(0.0, -d.y)).y;
217 //float cy = LUMAMM_tex(HOOKED_pos).y;
218 float by = LUMAMM_tex(HOOKED_pos + vec2(0.0, d.y)).y;
219
220 //Horizontal Gradient
221 //[-1 0 1]
222 //[-2 0 2]
223 //[-1 0 1]
224 float xgrad = (tx + cx + cx + bx);
225
226 //Vertical Gradient
227 //[-1 -2 -1]
228 //[ 0 0 0]
229 //[ 1 2 1]
230 float ygrad = (-ty + by);
231
232 float norm = sqrt(xgrad * xgrad + ygrad * ygrad);
233 if (norm <= 0.001) {
234 xgrad = 0.0;
235 ygrad = 0.0;
236 norm = 1.0;
237 }
238
239 return vec4(xgrad/norm, ygrad/norm, 0.0, 0.0);
240}
243//!DESC Anime4K-v3.2-Upscale-Original-x2-Apply
244//!HOOK MAIN
245//!BIND HOOKED
246//!BIND LUMAD
247//!BIND LUMAMM
248//!WIDTH MAIN.w 2 *
249//!HEIGHT MAIN.h 2 *
252vec4 hook() {
253 vec2 d = HOOKED_pt;
254
255 float dval = LUMAD_tex(HOOKED_pos).y;
256 if (dval < 0.1) {
257 return HOOKED_tex(HOOKED_pos);
258 }
259
260 vec4 dc = LUMAMM_tex(HOOKED_pos);
261 if (abs(dc.x + dc.y) <= 0.0001) {
262 return HOOKED_tex(HOOKED_pos);
263 }
264
265 float xpos = -sign(dc.x);
266 float ypos = -sign(dc.y);
267
268 vec4 xval = HOOKED_tex(HOOKED_pos + vec2(d.x * xpos, 0.0));
269 vec4 yval = HOOKED_tex(HOOKED_pos + vec2(0.0, d.y * ypos));
270
271 float xyratio = abs(dc.x) / (abs(dc.x) + abs(dc.y));
272
273 vec4 avg = xyratio * xval + (1.0 - xyratio) * yval;
274
275 return avg * dval + HOOKED_tex(HOOKED_pos) * (1.0 - dval);
276
277}

neovide/config.toml

Modified

+4 / −3 text lines

1frame = "none"
2tabs = true
3theme = "auto"
1frame = "none"
2tabs = true
3theme = "auto"
4fork = true

neovim/.editorconfig

Modified

+141 / −141 text lines

1root = true
2
3# see https://github.com/CppCXY/EmmyLuaCodeStyle
4# optional space/tab
5indent_style = space
6# if indent_style is space, this is valid
7indent_size = 2
8# if indent_style is tab, this is valid
9tab_width = 2
10# none/single/double
11quote_style = single
12
13continuation_indent = 2
14
15# this mean utf8 length , if this is 'unset' then the line width is no longer checked
16# this option decides when to chopdown the code
17max_line_length = 120
18
19# optional crlf/lf/cr/auto, if it is 'auto', in windows it is crlf other platforms are lf
20# in neovim the value 'auto' is not a valid option, please use 'unset'
21end_of_line = lf
22
23# none/ comma / semicolon / only_kv_colon
24table_separator_style = comma
25
26#optional keep/never/always/smart
27trailing_table_separator = smart
28
29# keep/remove/remove_table_only/remove_string_only
30call_arg_parentheses = remove
31
32detect_end_of_line = false
33
34# this will check text end with new line
35insert_final_newline = true
36
37# [space]
38space_around_table_field_list = true
39
40space_before_attribute = true
41
42space_before_function_open_parenthesis = false
43
44space_before_function_call_open_parenthesis = false
45
46space_before_closure_open_parenthesis = true
47
48# optional always/only_string/only_table/none
49# or true/false
50space_before_function_call_single_arg = always
51
52space_before_open_square_bracket = false
53
54space_inside_function_call_parentheses = true
55
56space_inside_function_param_list_parentheses = true
57
58space_inside_square_brackets = false
59
60# like t[#t+1] = 1
61space_around_table_append_operator = false
62
63ignore_spaces_inside_function_call = false
64
65space_before_inline_comment = 1
66
67# [operator space]
68space_around_math_operator = true
69
70space_after_comma = true
71
72space_after_comma_in_for_statement = true
73
74space_around_concat_operator = true
75
76# [align]
77
78align_call_args = true
79
80align_function_params = true
81
82align_continuous_assign_statement = true
83
84align_continuous_rect_table_field = true
85
86align_continuous_line_space = 2
87
88align_if_branch = true
89
90# option none / always / contain_curly/
91align_array_table = true
92
93align_continuous_similar_call_args = true
94
95align_continuous_inline_comment = true
96# option none / always / only_call_stmt
97align_chain_expr = none
98
99# [indent]
100
101never_indent_before_if_condition = false
102
103never_indent_comment_on_if_branch = false
104
105# [line space]
106
107# The following configuration supports four expressions
108# keep
109# fixed(n)
110# min(n)
111# max(n)
112# for eg. min(2)
113
114line_space_after_if_statement = keep
115
116line_space_after_do_statement = keep
117
118line_space_after_while_statement = keep
119
120line_space_after_repeat_statement = keep
121
122line_space_after_for_statement = keep
123
124line_space_after_local_or_assign_statement = keep
125
126line_space_after_function_statement = fixed(2)
127
128line_space_after_expression_statement = keep
129
130line_space_after_comment = keep
131
132# [line break]
133break_all_list_when_line_exceed = false
134
135auto_collapse_lines = false
136
137break_before_braces = false
138# [preference]
139ignore_space_after_colon = false
140
141remove_call_expression_list_finish_comma = false
1root = true
2
3# see https://github.com/CppCXY/EmmyLuaCodeStyle
4# optional space/tab
5indent_style = space
6# if indent_style is space, this is valid
7indent_size = 2
8# if indent_style is tab, this is valid
9tab_width = 2
10# none/single/double
11quote_style = single
13continuation_indent = 2
15# this mean utf8 length , if this is 'unset' then the line width is no longer checked
16# this option decides when to chopdown the code
17max_line_length = 120
19# optional crlf/lf/cr/auto, if it is 'auto', in windows it is crlf other platforms are lf
20# in neovim the value 'auto' is not a valid option, please use 'unset'
21end_of_line = lf
23# none/ comma / semicolon / only_kv_colon
24table_separator_style = comma
26#optional keep/never/always/smart
27trailing_table_separator = smart
29# keep/remove/remove_table_only/remove_string_only
30call_arg_parentheses = remove
32detect_end_of_line = false
34# this will check text end with new line
35insert_final_newline = true
37# [space]
38space_around_table_field_list = true
40space_before_attribute = true
42space_before_function_open_parenthesis = false
44space_before_function_call_open_parenthesis = false
46space_before_closure_open_parenthesis = true
48# optional always/only_string/only_table/none
49# or true/false
50space_before_function_call_single_arg = always
52space_before_open_square_bracket = false
54space_inside_function_call_parentheses = true
56space_inside_function_param_list_parentheses = true
58space_inside_square_brackets = false
60# like t[#t+1] = 1
61space_around_table_append_operator = false
63ignore_spaces_inside_function_call = false
65space_before_inline_comment = 1
67# [operator space]
68space_around_math_operator = true
70space_after_comma = true
72space_after_comma_in_for_statement = true
74space_around_concat_operator = true
76# [align]
78align_call_args = true
80align_function_params = true
82align_continuous_assign_statement = true
84align_continuous_rect_table_field = true
86align_continuous_line_space = 2
88align_if_branch = true
90# option none / always / contain_curly/
91align_array_table = true
93align_continuous_similar_call_args = true
95align_continuous_inline_comment = true
96# option none / always / only_call_stmt
97align_chain_expr = none
99# [indent]
101never_indent_before_if_condition = false
103never_indent_comment_on_if_branch = false
105# [line space]
107# The following configuration supports four expressions
108# keep
109# fixed(n)
110# min(n)
111# max(n)
112# for eg. min(2)
114line_space_after_if_statement = keep
116line_space_after_do_statement = keep
118line_space_after_while_statement = keep
120line_space_after_repeat_statement = keep
122line_space_after_for_statement = keep
124line_space_after_local_or_assign_statement = keep
126line_space_after_function_statement = fixed(2)
128line_space_after_expression_statement = keep
130line_space_after_comment = keep
132# [line break]
133break_all_list_when_line_exceed = false
135auto_collapse_lines = false
137break_before_braces = false
138# [preference]
139ignore_space_after_colon = false
141remove_call_expression_list_finish_comma = false

neovim/.luarc.json

Added
new file mode 100644

+11 / −0 text lines

1{
2 "runtime.version": "LuaJIT",
3 "diagnostics.globals": ["vim", "describe", "it", "before_each", "after_each"],
4 "workspace.checkThirdParty": false,
5 "workspace.library": [
6 "$VIMRUNTIME",
7 "${3rd}/luv/library",
8 "${3rd}/busted/library",
9 "${3rd}/luassert/library"
10 ]
11}

neovim/.system/MISSION.md

Added
new file mode 100644

+4 / −0 text lines

1# MISSION
2
3Enduring high-level project objective and why it matters.
4Update only when the end goal changes; current operating priorities belong in a phase.

neovim/.system/RULES.md

Added
new file mode 100644

+4 / −0 text lines

1# RULES
2
3Concrete operating constraints: commands, safety, style, boundaries, and do/don't rules.
4Keep executable; avoid goals and rationale unless needed.

neovim/.system/SYSTEM.md

Added
new file mode 100644

+4 / −0 text lines

1# SYSTEM
2
3Stable project identity, domain truths, architecture invariants, and non-negotiable conventions.
4Keep durable; do not put current tasks here.

neovim/.system/board.json

Added
new file mode 100644

+41 / −0 text lines

1{
2 "schemaVersion": 0,
3 "items": {
4 "NVIM-ISSUE-9MP5JYUO": {
5 "state": "done",
6 "updatedAt": "2026-10-02T01:47:18.875Z",
7 "source": "agent",
8 "note": "session.sync fetches get_state+get_session_stats on lifecycle; status folds model/thinking/context/cost/tokens; publish forwards full set + ANSI-stripped keyed ext. suite green 61 files."
9 },
10 "NVIM-ISSUE-INA9RX_F": {
11 "state": "done",
12 "updatedAt": "2026-10-02T01:17:38.217Z",
13 "source": "agent",
14 "note": "transcript.lua now tail-guards autoscroll: only windows already on the final line follow a write; readers hold position. 2 new editor specs + full suite green (59 files, 0 fail)."
15 },
16 "NVIM-PLAN-CEJPO_XF": {
17 "state": "done",
18 "updatedAt": "2026-10-02T02:38:40.635Z",
19 "source": "agent",
20 "note": "All 12 slices implemented; rpc/session/transcript/command/help/status/publish/context/edit/activity/follow/dialog specs pass. Fresh just test: 669 pass, 0 fail/err."
21 },
22 "NVIM-PLAN-LAJ8PGRK": {
23 "state": "done",
24 "updatedAt": "2026-10-02T02:38:40.635Z",
25 "source": "agent",
26 "note": "All 7 transcript slices implemented; entry/render/fold/navigate/detail specs pass. Fresh just test: 669 pass, 0 fail/err."
27 },
28 "NVIM-PLAN-T7XG71CC": {
29 "state": "done",
30 "updatedAt": "2026-10-02T02:38:40.635Z",
31 "source": "agent",
32 "note": "All 7 tool-presentation slices implemented; tool/diff/navigate/render/fold specs pass. Fresh just test: 669 pass, 0 fail/err."
33 },
34 "NVIM-SPEC-GMWDCMJZ": {
35 "state": "todo",
36 "source": "agent",
37 "updatedAt": "2026-10-02T03:07:41.664Z",
38 "note": "Tool-presentation amended (C2); only partially delivered: per-tool colour, failure-outcome-only, focus done. Outstanding: grep file-grouping, bash full-output surface, read preview. Suite 671 green."
39 }
40 }
41}

neovim/.system/config.json

Added
new file mode 100644

+5 / −0 text lines

1{
2 "prefix": "NVIM",
3 "schemaVersion": 0,
4 "title": "neovim"
5}

neovim/.system/issues/NVIM-ISSUE-8I3OSH4M-prompt-accept-auto-steers-diverging-from-explici/index.md

Added
new file mode 100644

+47 / −0 text lines

1---
2id: NVIM-ISSUE-8I3OSH4M
3type: issue
4title: Prompt accept auto-steers, diverging from explicit queued delivery
5specs:
6 - NVIM-SPEC-GMWDCMJZ
7---
8
9# Prompt accept auto-steers, diverging from explicit queued delivery
11## Symptom
13Accepting the prompt while the agent is working now delivers the text as a steer, chosen implicitly by the accept key rather than by an explicit delivery decision. A follow-up has its own keys, but a steer is injected into the live run immediately; it is not queued, listed, or clearable.
15## Impact
17Diverges from [NVIM-SPEC-GMWDCMJZ](../../specs/NVIM-SPEC-GMWDCMJZ-pivi-native-neovim-integration/index.md), which states:
19- "While a session run is active, a new submission is queued with an explicit delivery choice and is never silently dropped."
20- "Queued submissions remain listable and clearable before delivery."
21- Acceptance: "A submission made during an active run is queued with explicit delivery and can be listed and cleared before delivery."
23Two gaps against that contract:
25- Delivery is now implicit for the accept key: pressing accept while working picks steer with no separate choice.
26- A steer is injected into the active run, so it is neither queued nor listable nor clearable, unlike a follow-up.
28Nothing is silently dropped, so that half of the contract still holds. The desired behavior (accept steers while working, as in pi) is intentional; the spec is what no longer matches.
30## Evidence
32`lua/bugabinga/pivi/command.lua`, the prompt `send`:
34- When no delivery is passed and the session is busy, it sets delivery to `steer`.
35- `<Plug>(pivi-submit)` and `<Plug>(pivi-accept)` call `send()` with no delivery, so the accept key auto-steers during a run.
36- `<Plug>(pivi-follow-up)` calls `send('follow_up')`, which queues.
38`lua/bugabinga/pivi/session.lua` maps `steer` to a `steer` command (immediate) and `follow_up` to a `follow_up` command (queued); only the latter appears in the status queue that `:Pi queue` lists and `:Pi clear` clears.
40## Expected
42Resolve the divergence one way:
44- Amend the spec so an accept while working is a defined, visible steer (winbar hint states it), treating a bound, announced key as an explicit choice, and scope "queued, listable, clearable" to follow-ups; or
45- Change the behavior so an accept during a run requires an explicit delivery choice and queues rather than injecting.
47The spec's intent for steering versus follow-up delivery decides which; this issue records the mismatch, not the resolution.

neovim/.system/issues/NVIM-ISSUE-9MP5JYUO-session-status-never-fetches-or-publishes-model/index.md

Added
new file mode 100644

+80 / −0 text lines

1---
2id: NVIM-ISSUE-9MP5JYUO
3type: issue
4title: Session status never fetches or publishes model, context, and cost
5specs:
6 - NVIM-SPEC-GMWDCMJZ
7---
8
9# Session status never fetches or publishes model, context, and cost
11## Symptom
13A pivi session surfaces none of the rich Pi status a user sees in Pi's own interface: model, thinking level, context usage percent, token counts, and accumulated cost. Only connection, run, tool, queue, and error states appear.
15## Impact
17Violates the transport-and-status contract of [NVIM-SPEC-GMWDCMJZ](../../specs/NVIM-SPEC-GMWDCMJZ-pivi-native-neovim-integration/index.md):
19- "Status also exposes available model, thinking, session, context, usage, and extension-status data."
20- "Status changes redraw native status surfaces and emit a semantic event."
22Consumers reading `vim.g.pivi` can never show model, context, or cost, so a user-built statusline is starved of the data the spec promises to publish.
24Scope note: cwd, git branch, and editor version from the user's Pi TUI statusline are out of scope. The native-integration invariant makes pivi a producer of session status, not the owner of a statusline; those fields belong to the user's own statusline, not to pivi's published state.
26## Generality
28The fix must not depend on the reporter's specific Pi extensions.
30- Core fields (model, thinking, context usage, cost, token counts) come from core Pi RPC `get_state` and `get_session_stats`, present for any Pi configuration.
31- The extra segments in the reporter's TUI line (tokens/s, credit balance, rate-limit window) are extension widgets delivered generically through `setStatus` / `setWidget`, keyed by an arbitrary string. `dialog.lua` already stores them by key and emits `PiviActivity`; nothing references a named extension, and the path works with zero extensions and with arbitrary ones.
32- Required: the published status snapshot is the single generic source that merges core fields with whatever extensions contributed by key, so a consumer reads one place. Today extension status/widget entries live only in `dialog.lua` tables and a separate `PiviActivity` event, decoupled from `vim.g.pivi.sessions[name]` and not scoped per session.
34## Surface
36Pi's status is multi-segment and renders across multiple rows in the TUI; `setWidget` even delivers `widgetLines` as an array, so the data is inherently multi-line. A Neovim `statusline` (and `winbar`) is a single line. pivi therefore must not collapse status into one lossy statusline string as its only output.
38- pivi publishes structured per-field data plus multi-line widget arrays as data; the consumer owns the surface (a statusline segment, winbar, tabline, or a dedicated multi-line status buffer or float).
39- A compact single-line `summary` stays available for the trivial statusline case, but is a convenience over the structured data, never a replacement for it.
40- pivi's own winbar shows at most a compact subset; full multi-line detail belongs to the structured data and to an optional richer surface, not to the one winbar line.
42## Evidence
44The reducers for the two status-bearing RPC responses exist but are never driven:
46- `status.reduce_state` (folds `get_state`: model, thinking, session) has no live caller. `session.refresh` issues `get_state` and is exported as `self.refresh`, but nothing ever calls it: no command, no lifecycle event, no poll.
47- `status.reduce_stats` (folds `get_session_stats`: context usage, cost) has no caller at all; it is dead code.
48- `command.lua` `subcommands.session` does request `get_session_stats`, but only prints a one-off `notify`; it neither folds the result into cached status nor publishes it.
49- `publish.session_status` forwards `model`, `thinking`, `session`, `context`, but omits `cost` and any token breakdown, so even a populated reducer would not reach consumers in full.
51Net effect: the published status carries only event-derived fields (connection, run, tool, queue, compacting, retry, error). The fields that require a request, model/thinking/context/usage/cost, stay `nil` for the entire run.
53```mermaid
54sequenceDiagram
55 participant Pi
56 participant session as pivi.session
57 participant status as pivi.status (reducer)
58 participant publish as pivi.publish
59 participant consumer as user statusline
60 Pi-->>session: event stream (agent/tool/queue)
61 session->>status: reduce(event)
62 status->>publish: connection/run/tool/queue only
63 Note over session,status: get_state / get_session_stats never requested
64 Note over status: reduce_state, reduce_stats never called
65 publish-->>consumer: vim.g.pivi without model/context/cost
66 consumer-->>consumer: nothing to show
67```
69## Expected
71- Model, thinking, session, context usage, and cost populate cached status during a normal run, refreshed on the events that change them and at settle, for any Pi configuration.
72- `publish.session_status` forwards the full set, including cost and token usage, plus generic extension status and widget entries merged by key, through `vim.g.pivi` and the semantic `User PiviStatus` event.
73- Published status is structured per-field data with multi-line widget arrays preserved; the single-line `summary` remains a convenience, not the only output.
74- Status evaluation still performs no RPC; refreshes are triggered by run lifecycle, not by consumers reading the variable.
76## Reproduction
781. Start a session and submit a prompt that calls a model.
792. Inspect `vim.g.pivi.sessions[<name>]` during and after the run.
803. Observe `model`, `thinking`, `context`, and `cost` remain `nil`; only connection/run/tool/queue/error are present.

neovim/.system/issues/NVIM-ISSUE-INA9RX_F-transcript-force-scrolls-to-bottom-on-every-writ/index.md

Added
new file mode 100644

+68 / −0 text lines

1---
2id: NVIM-ISSUE-INA9RX_F
3type: issue
4title: Transcript force-scrolls to bottom on every write
5specs:
6 - NVIM-SPEC-GMWDCMJZ
7---
8
9# Transcript force-scrolls to bottom on every write
11## Symptom
13In a grown transcript, scrolling is erratic: the view jumps on every new streamed delta, navigation away from the bottom does not hold, and expanding a tool entry appears broken.
15## Impact
17Violates transcript behavior of [NVIM-SPEC-GMWDCMJZ](../../specs/NVIM-SPEC-GMWDCMJZ-pivi-native-neovim-integration/index.md):
19- Transcript navigation requires moving between entries "with ordinary motions"; the cursor cannot be held off the last line while a run streams.
20- Follow mode is "optional and disabled unless selected", yet the transcript force-follows unconditionally.
21- Entry collapse/expand is defeated because the expanded entry is scrolled out of view and the toggle acts on the wrong line.
23## Evidence
25`lua/bugabinga/pivi/transcript.lua` — `follow_windows` forces the cursor to the last line in every window showing the buffer, and is called unconditionally after `append`, `line`, and `replace`:
27```
28local follow_windows = function( bufnr )
29 local last = vim.api.nvim_buf_line_count( bufnr )
30 for _, win in ipairs( vim.api.nvim_list_wins() ) do
31 if vim.api.nvim_win_get_buf( win ) == bufnr then
32 pcall( vim.api.nvim_win_set_cursor, win, { last, 0, } )
33 end
34 end
35end
36```
38No guard checks whether a window is already tailing the bottom, so any user navigation is overwritten by the next streamed delta.
40Expand breakage follows from the same force: `fold.toggle` reads `nvim_win_get_cursor( 0 )[1]` to pick the entry, but `follow_windows` has already yanked the cursor to the last line, so `<Plug>(pivi-toggle-entry)` toggles the final entry rather than the one under the reader; and `fold.apply`'s `normal! zX` recompute runs against a view scrolled to the bottom.
42```mermaid
43sequenceDiagram
44 participant User
45 participant session
46 participant transcript
47 participant window as transcript window
48 participant fold
49 User->>window: move cursor up / expand entry
50 session->>transcript: append streamed delta
51 transcript->>window: follow_windows -> cursor = last line
52 window-->>User: view jumps to bottom
53 User->>fold: toggle entry at cursor
54 fold->>window: reads cursor (already at last line)
55 window-->>User: wrong entry toggled, scrolled away
56```
58## Expected
60- Auto-follow only when the window is already at the transcript tail; otherwise leave cursor and view untouched.
61- User navigation holds across streamed writes.
62- Expanding or collapsing acts on the entry the reader is on and keeps it in view.
64## Reproduction
661. Start a session and submit a prompt that produces a long streamed answer with tool calls.
672. While it streams, move the cursor up or expand a collapsed tool entry.
683. Observe the view snap back to the bottom on the next delta and the toggled entry change or scroll away.

neovim/.system/plans/NVIM-PLAN-CEJPO_XF-deliver-pivi-native-neovim-integration/index.md

Added
new file mode 100644

+104 / −0 text lines

1---
2id: NVIM-PLAN-CEJPO_XF
3type: plan
4title: Deliver pivi native Neovim integration
5spec: NVIM-SPEC-GMWDCMJZ
6status: approved
7---
8
9# Deliver pivi native Neovim integration
11## Intent
13Deliver [NVIM-SPEC-GMWDCMJZ](../../specs/NVIM-SPEC-GMWDCMJZ-pivi-native-neovim-integration/index.md) as vertical slices, each observable through Neovim surfaces.
14Evidence for transport, tool authority, and concurrency comes from [NVIM-RESEARCH-KZYYEFY_](../../research/NVIM-RESEARCH-KZYYEFY_-pi-and-neovim-capabilities-for-pivi/index.md).
16Placement: pivi is an ordinary configuration module at `lua/bugabinga/pivi/`, like the other Neovim modules, with its bundled Pi companion extension under `lua/bugabinga/pivi/extension/`.
17Module-level testing rules live in that directory's `AGENTS.md`.
18Publishing state through native variables and `User` events still holds, so other configuration consumes pivi without depending on its internals.
20## Module map
22```mermaid
23flowchart TB
24 command["bugabinga.pivi.command"] --> session["bugabinga.pivi.session"]
25 command --> help["bugabinga.pivi.help"]
26 session --> rpc["bugabinga.pivi.rpc"]
27 session --> status["bugabinga.pivi.status"]
28 status --> publish["bugabinga.pivi.publish"]
29 session --> transcript["bugabinga.pivi.transcript"]
30 session --> context["bugabinga.pivi.context"]
31 session --> dialog["bugabinga.pivi.dialog"]
32 rpc --> extension["companion Pi extension"]
33 extension --> edit["bugabinga.pivi.edit"]
34 edit --> activity["bugabinga.pivi.activity"]
35 activity --> follow["bugabinga.pivi.follow"]
36 help --> rpc
37```
39| Module | Responsibility |
40| --- | --- |
41| `bugabinga.pivi.rpc` | Child process lifetime, strict LF JSONL framing, request correlation, deferral out of fast contexts |
42| `bugabinga.pivi.session` | Session identity, working directory, queue delivery, abort, resume, switch |
43| `bugabinga.pivi.status` | Cached semantic state; no RPC during status evaluation |
44| `bugabinga.pivi.publish` | `vim.g` state plus `User` autocmd events with payload data |
45| `bugabinga.pivi.transcript` | Prompt, transcript, and detail buffers |
46| `bugabinga.pivi.context` | Immutable submission snapshots and ambient editor state |
47| `bugabinga.pivi.edit` | Buffer-authoritative mutation, undo coherence, disk visibility |
48| `bugabinga.pivi.activity` | Extmarks, signs, virtual text, diagnostics, quickfix and location lists |
49| `bugabinga.pivi.follow` | Optional viewport following |
50| `bugabinga.pivi.dialog` | Extension UI requests mapped to `vim.ui` surfaces |
51| `bugabinga.pivi.help` | Ephemeral session-less run |
52| `bugabinga.pivi.command` | `:Pi` subcommands, slash-command entry, `<Plug>` mappings |
53| companion extension | Editor tools plus buffer-authoritative operations for built-in Pi tools |
55## Slice order
57```mermaid
58flowchart LR
59 s1["1 Ask and stream"] --> s3["3 Status and events"]
60 s1 --> s2["2 Ephemeral help"]
61 s3 --> s4["4 Session control"]
62 s4 --> s5["5 Submission context"]
63 s5 --> s6["6 Buffer-authoritative reads"]
64 s6 --> s7["7 Native edits"]
65 s7 --> s8["8 Activity and lists"]
66 s7 --> s9["9 Streaming ghost text"]
67 s8 --> s10["10 Follow mode"]
68 s4 --> s11["11 Slash commands"]
69 s4 --> s12["12 Extension dialogs"]
70```
72| # | Observable behavior | Modules touched | Verified by |
73| --- | --- | --- | --- |
74| 1 | `:Pi ask {text}` starts Pi, streams assistant text into a transcript buffer, and survives partial reads | `bugabinga.pivi.rpc`, `bugabinga.pivi.session`, `bugabinga.pivi.transcript`, `bugabinga.pivi.command` | Framing and assembly specs plus a live round trip |
75| 2 | `:Pi help {q}` answers from an independent session-less run without touching any working session | `bugabinga.pivi.help`, `bugabinga.pivi.command` | Concurrent-run spec asserting untouched session history, queue, and status |
76| 3 | Status changes update cached state, emit semantic `User` events, and never issue RPC during evaluation | `bugabinga.pivi.status`, `bugabinga.pivi.publish` | Event payload spec plus a consumer that degrades when pivi is absent |
77| 4 | Create, resume, switch, stop sessions; queue steering or follow-up during a run; list, clear, abort | `bugabinga.pivi.session`, `bugabinga.pivi.command`, `bugabinga.pivi.transcript` | Queue state-machine spec matching the spec's run states |
78| 5 | Submissions carry immutable buffer, revision, cursor, range, and selection snapshots; queued items keep their own | `bugabinga.pivi.context`, `bugabinga.pivi.session` | Snapshot immutability spec under later buffer edits |
79| 6 | Pi reads unsaved loaded-buffer content and current core editor state on demand, including arbitrary Lua | companion extension, `bugabinga.pivi.rpc` | Tool-result spec comparing buffer versus disk content |
80| 7 | A normal Pi edit lands in a loaded buffer without reload, stays undoable as one change, and is visible to later shell work | `bugabinga.pivi.edit`, companion extension | Undo and coherence spec covering join failure fallback |
81| 8 | Edits leave a navigable trail; findings populate quickfix, location lists, and a distinct diagnostic namespace | `bugabinga.pivi.activity` | Namespace isolation and navigation spec |
82| 9 | Streaming tool arguments render ghost text that never mutates a buffer before arguments are complete | `bugabinga.pivi.activity`, `bugabinga.pivi.edit` | Partial-argument spec asserting zero mutation |
83| 10 | Follow mode tracks located events in a dedicated window or tab and restores the prior location | `bugabinga.pivi.follow` | Window ownership and restore spec |
84| 11 | `:Pi command ...` runs discovered Pi commands; `/` opens entry only at the first character of an input buffer | `bugabinga.pivi.command` | Cursor-position and discovery spec |
85| 12 | Extension dialogs and fire-and-forget status map to native surfaces and answer with matching identifiers | `bugabinga.pivi.dialog` | Request and response correlation spec |
87Slice 1 is the walking skeleton; every later slice keeps `just test` green before the next begins.
89## Critical paths
91- Child output arrives in fast contexts; all editor work defers through scheduling before API calls.
92- Submission during an active run always chooses steering or follow-up; rejection is never silent.
93- Help spawns its own session-less child so working-session history, queue, and status remain untouched.
94- Buffer authority prefers injecting operations into Pi's built-in tools over reimplementing them, because result and detail shapes must match exactly.
96## Risks
98| Risk | Slice | Mitigation |
99| --- | --- | --- |
100| Undo join refuses after undo or redo | 7 | Detect refusal and fall back to separate undo blocks rather than losing the edit |
101| Partial tool arguments are invalid JSON | 9 | Treat ghost text as presentation only; mutate solely on complete validated arguments |
102| Tool override breaks rendering or session state | 6, 7 | Keep built-in renderers and detail shapes; override behavior only |
103| Status consumers stall the statusline | 3 | Read cached state only |
104| Agent shell work reads stale disk content | 7 | Make agent buffer edits visible to filesystem readers as part of the edit behavior |

neovim/.system/plans/NVIM-PLAN-LAJ8PGRK-deliver-pivi-transcript-presentation-and-navigat/index.md

Added
new file mode 100644

+92 / −0 text lines

1---
2id: NVIM-PLAN-LAJ8PGRK
3type: plan
4title: Deliver pivi transcript presentation and navigation
5spec: NVIM-SPEC-GMWDCMJZ
6status: approved
7depends_on:
8 - NVIM-PLAN-CEJPO_XF
9---
11# Deliver pivi transcript presentation and navigation
13## Intent
15Deliver the transcript presentation and navigation behavior of
16[NVIM-SPEC-GMWDCMJZ](../../specs/NVIM-SPEC-GMWDCMJZ-pivi-native-neovim-integration/index.md).
18[NVIM-PLAN-CEJPO_XF](../NVIM-PLAN-CEJPO_XF-deliver-pivi-native-neovim-integration/index.md) delivered a working transcript that appends plain text and mixes pivi's own framing into the content.
19This plan makes the transcript the conversation document it already is: addressable entries, message text as authored, rendered formatting, and ordinary motion.
21Placement continues from the earlier plan: `lua/bugabinga/pivi/`, with module-level testing rules in that directory's `AGENTS.md`.
23Measured constraint, not assumption: a transcript that reparses on every streamed delta costs roughly five hundred times a transcript that lets redraw drive parsing.
24Presentation must therefore never force parsing per delta.
26## Module map
28```mermaid
29flowchart TB
30 session["bugabinga.pivi.session"] --> entry["bugabinga.pivi.entry"]
31 entry --> transcript["bugabinga.pivi.transcript"]
32 transcript --> render["bugabinga.pivi.render"]
33 entry --> fold["bugabinga.pivi.fold"]
34 entry --> navigate["bugabinga.pivi.navigate"]
35 navigate --> follow["bugabinga.pivi.follow"]
36 navigate --> detail["bugabinga.pivi.detail"]
37 command["bugabinga.pivi.command"] --> navigate
38 command --> fold
39```
41| Module | Responsibility |
42| --- | --- |
43| `bugabinga.pivi.entry` | Entry identity, kind, bounds, metadata, and lifecycle over a transcript buffer |
44| `bugabinga.pivi.transcript` | Buffer ownership; message text only, with framing delegated to presentation |
45| `bugabinga.pivi.render` | Formatting, embedded language presentation, and framing decoration |
46| `bugabinga.pivi.fold` | Collapsed and expanded presentation of an entry |
47| `bugabinga.pivi.navigate` | Motion between entries and tool calls, and reaching a referenced location |
48| `bugabinga.pivi.detail` | Detailed inspection of one entry without leaving the transcript |
49| `bugabinga.pivi.session` | Emits entries instead of writing framing text |
50| `bugabinga.pivi.command` | `:Pi` subcommands and `<Plug>` mappings for the new behavior |
52## Slice order
54```mermaid
55flowchart LR
56 s1["1 Addressable entries"] --> s2["2 Pure message text"]
57 s1 --> s3["3 Collapse and expand"]
58 s2 --> s4["4 Rendered formatting"]
59 s1 --> s5["5 Motion between entries"]
60 s5 --> s6["6 Reach a referenced location"]
61 s3 --> s7["7 Detailed inspection"]
62```
64| # | Observable behavior | Modules touched | Verified by |
65| --- | --- | --- | --- |
66| 1 | Every appended submission, answer, tool call, result, and error is an addressable entry with stable bounds that survive later appends | `bugabinga.pivi.entry`, `bugabinga.pivi.transcript`, `bugabinga.pivi.session` | Entry bounds spec under streaming appends and buffer growth |
67| 2 | Transcript text is the message as authored; copying an answer yields the original text without framing | `bugabinga.pivi.transcript`, `bugabinga.pivi.render`, `bugabinga.pivi.session` | Copy spec comparing buffer text with recorded message content |
68| 3 | A tool result arrives collapsed to one readable line and expands on request; entry state never alters session history | `bugabinga.pivi.fold`, `bugabinga.pivi.entry`, `bugabinga.pivi.command` | Collapse spec asserting unchanged session entries and message state |
69| 4 | Message formatting renders rather than showing markup, embedded code appears in its own language, and unknown formats stay plain | `bugabinga.pivi.render` | Rendering spec plus a streaming budget assertion over a recorded answer |
70| 5 | Ordinary motions move between entries and between tool calls in both directions | `bugabinga.pivi.navigate`, `bugabinga.pivi.command` | Motion spec over a replayed recorded run |
71| 6 | An entry that names a location navigates there, reusing the existing follow surfaces | `bugabinga.pivi.navigate`, `bugabinga.pivi.follow` | Navigation spec asserting the working window is preserved |
72| 7 | An entry can be inspected in full, including tool arguments and results, without leaving the transcript | `bugabinga.pivi.detail`, `bugabinga.pivi.entry` | Inspection spec asserting the transcript window and cursor are unchanged |
74Slice 1 is the walking skeleton; every later slice keeps the whole suite green before the next begins.
76## Critical paths
78- Entry bounds must be extmark-backed, because text appended later shifts every fixed line number.
79- Presentation is driven by redraw, never by a forced parse per streamed delta.
80- Framing lives in decoration, so the buffer stays copyable message text.
81- Collapsing is presentation only; the session transcript and Pi history are untouched.
82- Location navigation reuses follow-mode surfaces rather than introducing a second window policy.
84## Risks
86| Risk | Slice | Mitigation |
87| --- | --- | --- |
88| Entry bounds drift as the transcript grows | 1 | Extmark-backed ranges, asserted after appends and after edits to earlier entries |
89| Moving framing out of the text loses scannability | 2 | Replace it with decoration in the same slice, and assert both text purity and visible framing |
90| Rendering cost grows with a long answer | 4 | Assert a streaming budget over a recorded answer; keep parsing redraw-driven |
91| Collapsed entries hide errors the user needs | 3 | Collapse voluminous results only; keep errors expanded |
92| New mappings collide with user keys | 3, 5, 7 | Buffer-local mappings in pivi buffers plus `<Plug>` mappings; no global keys |

neovim/.system/plans/NVIM-PLAN-T7XG71CC-deliver-pivi-tool-presentation/index.md

Added
new file mode 100644

+103 / −0 text lines

1---
2id: NVIM-PLAN-T7XG71CC
3type: plan
4title: Deliver pivi tool presentation
5spec: NVIM-SPEC-GMWDCMJZ
6status: approved
7depends_on:
8 - NVIM-PLAN-CEJPO_XF
9 - NVIM-PLAN-LAJ8PGRK
10---
12# Deliver pivi tool presentation
14## Intent
16Make a tool call as legible in Neovim as it is in Pi's own interface, using native surfaces rather than a ported component tree.
18[NVIM-PLAN-LAJ8PGRK](../NVIM-PLAN-LAJ8PGRK-deliver-pivi-transcript-presentation-and-navigat/index.md) made every tool call an addressable, collapsible entry.
19That entry currently shows what a tool acted on and nothing about how it ended, and it discards everything a tool reports about its own work.
21Blocker: the behavior below is not yet in [NVIM-SPEC-GMWDCMJZ](../../specs/NVIM-SPEC-GMWDCMJZ-pivi-native-neovim-integration/index.md).
22A tool presentation section and its acceptance criteria were drafted and await one-shot approval.
23This plan is not executable until that amendment lands.
25## Evidence
27Read from the installed Pi 0.85.1 implementation, not from prose.
28Tool results reach a client unchanged, so everything a tool reports is already on the wire and merely unused.
30| Tool | What it reports about its own work | When |
31| --- | --- | --- |
32| edit | a display diff, a unified patch, and the first changed line | always |
33| bash | progressive output, truncation, and a full output path | while running, throttled |
34| read | truncation | only when truncated |
35| grep, find, ls | truncation and the limit that was reached | only at a limit |
36| write | nothing | — |
38Neovim side: no diff parser ships, but diff syntax and the diff highlight groups do, and the theme already defines them.
40## Module map
42```mermaid
43flowchart TB
44 session["bugabinga.pivi.session"] --> tool["bugabinga.pivi.tool"]
45 tool --> entry["bugabinga.pivi.entry"]
46 tool --> render["bugabinga.pivi.render"]
47 render --> fold["bugabinga.pivi.fold"]
48 tool --> diff["bugabinga.pivi.diff"]
49 diff --> command["bugabinga.pivi.command"]
50 tool --> navigate["bugabinga.pivi.navigate"]
51```
53| Module | Responsibility |
54| --- | --- |
55| `bugabinga.pivi.tool` | Interprets what a tool reports: outcome, change, progress, language, truncation |
56| `bugabinga.pivi.render` | Presents that interpretation as decoration inside the entry |
57| `bugabinga.pivi.diff` | Editor comparison of a completed change |
58| `bugabinga.pivi.fold` | Collapsed line that still states subject and outcome |
59| `bugabinga.pivi.navigate` | Reaching the first changed line rather than the file start |
60| `bugabinga.pivi.entry` | Carries the interpretation as entry metadata |
61| `bugabinga.pivi.session` | Feeds tool reports in, including while a tool still runs |
63## Slice order
65```mermaid
66flowchart LR
67 s1["1 Outcome after the name"] --> s2["2 Change as a diff"]
68 s1 --> s6["6 Truncation is reachable"]
69 s2 --> s3["3 First changed line"]
70 s2 --> s4["4 Editor comparison"]
71 s1 --> s5["5 Output while running"]
72 s5 --> s7["7 Output in its language"]
73```
75| # | Observable behavior | Modules touched | Verified by |
76| --- | --- | --- | --- |
77| 1 | A finished tool entry states how it ended beside what it acted on, and a collapsed entry keeps both | `bugabinga.pivi.tool`, `bugabinga.pivi.render`, `bugabinga.pivi.fold`, `bugabinga.pivi.session` | Outcome spec across edit, shell, search, and failure, plus a collapsed-line spec |
78| 2 | A completed edit shows its change with added and removed lines distinguished | `bugabinga.pivi.tool`, `bugabinga.pivi.render` | Diff presentation spec asserting distinct added and removed lines and unchanged buffer text |
79| 3 | Navigating from an edit lands on its first changed line | `bugabinga.pivi.navigate`, `bugabinga.pivi.tool` | Navigation spec over a recorded edit |
80| 4 | A change can be opened as a full editor comparison and left again | `bugabinga.pivi.diff`, `bugabinga.pivi.command` | Comparison spec asserting the working window survives and the transcript is unchanged |
81| 5 | Output of a running tool appears as it arrives rather than only at completion | `bugabinga.pivi.session`, `bugabinga.pivi.tool`, `bugabinga.pivi.entry` | Progressive-output spec asserting growth before completion and stable bounds |
82| 6 | A truncated result says so, and its full output is reachable | `bugabinga.pivi.tool`, `bugabinga.pivi.render`, `bugabinga.pivi.navigate` | Truncation spec asserting the notice and a reachable full output |
83| 7 | Output is presented in the language it came from when that language is known | `bugabinga.pivi.tool`, `bugabinga.pivi.render` | Language spec asserting a second language is parsed inside the transcript |
85Slice 1 is the walking skeleton: it establishes the interpretation every later slice reads.
87## Critical paths
89- Interpretation is derived only from what a tool reports; a tool that reports nothing degrades to today's behavior rather than to a guess.
90- Diff presentation is decoration over reported change text, so the transcript still yields message text when copied.
91- An editor comparison reconstructs the prior content from the reported change rather than re-reading a file that has already moved on.
92- Progressive output replaces the tail of its own entry; entry bounds stay extmark-backed and must survive repeated rewrites.
93- Presentation stays redraw-driven, so a tool that emits output continuously cannot force parsing per update.
95## Risks
97| Risk | Slice | Mitigation |
98| --- | --- | --- |
99| Tools differ in what they report | 1 | Interpretation is per tool with a plain fallback, asserted for a tool that reports nothing |
100| Diff decoration drifts from the text it marks | 2 | Anchor decoration to entry-relative rows and assert after later entries are appended |
101| A reconstructed comparison disagrees with the file on disk | 4 | Present it as a comparison of the recorded change, and state when the file has moved on |
102| Frequent progress updates cost too much | 5 | Rewrite only the entry tail, keep parsing redraw-driven, and hold the streaming budget spec |
103| A collapsed line grows unreadable | 1 | Bound subject and outcome, and assert a maximum collapsed width |

neovim/.system/research/NVIM-RESEARCH-KZYYEFY_-pi-and-neovim-capabilities-for-pivi/index.md

Added
new file mode 100644

+144 / −0 text lines

1---
2id: NVIM-RESEARCH-KZYYEFY_
3type: research
4title: Pi and Neovim capabilities for pivi
5---
6
7# Pi and Neovim capabilities for pivi
8
9## Sources
11Installed documentation only; no remembered API behavior.
13| Source | Version | Location |
14| --- | --- | --- |
15| Pi docs (`rpc.md`, `extensions.md`, `usage.md`, `sessions.md`, `json.md`) | 0.85.1 | `$PI_CONTEXT_DOCS_PATH` |
16| Neovim runtime docs (`api.txt`, `lua.txt`, `undo.txt`, `editing.txt`, `options.txt`) | 0.12.5 | `$VIMRUNTIME/doc` |
18## Pi facts
20### Transport
22- `pi --mode rpc` speaks JSON commands on stdin, responses and events on stdout.
23- Strict JSONL, LF only; clients strip a trailing `\r`; Unicode separators must not split records.
24- Optional `id` on commands correlates responses; most events carry no `id`.
25- Startup flags relevant to a client: `--provider`, `--model`, `--name`, `--session <path|id>`, `--session-dir`, `--no-session`, `-e <ext>`, `--tools`, `--append-system-prompt`.
27### Commands that map to pivi surfaces
29| pivi need | RPC command | Notes |
30| --- | --- | --- |
31| Submit prompt | `prompt` | During streaming requires `streamingBehavior: steer \| followUp`, else error |
32| Queue while running | `steer`, `follow_up`, `clear_queue` | Extension commands rejected here |
33| Stop | `abort`, `abort_retry`, `abort_bash` | `abort` waits for idle |
34| Status | `get_state`, `get_session_stats` | Model, thinking, streaming, queue, context usage |
35| Transcript | `get_messages`, `get_entries`, `get_tree` | `get_entries since` is a durable cursor; `leafId` detects branch moves |
36| Sessions | `new_session`, `switch_session`, `fork`, `clone`, `set_session_name` | Switch/fork cancellable by extensions |
37| Slash commands | `get_commands` | Returns extension, prompt-template, and skill commands; invoked as `/name` through `prompt` |
38| Model/thinking | `set_model`, `cycle_model`, `get_available_models`, `set_thinking_level`, `get_available_thinking_levels` | |
39| Compaction | `compact`, `set_auto_compaction` | |
41Built-in TUI commands such as `/settings` and `/hotkeys` are absent from `get_commands` and do not execute over RPC.
43### Concurrency semantics
45```mermaid
46stateDiagram-v2
47 [*] --> Idle
48 Idle --> Streaming: prompt
49 Streaming --> Streaming: steer / follow_up queued
50 Streaming --> Streaming: extension command executes immediately
51 Streaming --> Idle: agent_settled
52 Streaming --> Idle: abort
53```
55- A plain `prompt` while streaming is rejected without `streamingBehavior`.
56- An extension command (`/name`) sent through `prompt` executes immediately even during streaming and manages its own LLM interaction.
57- `agent_end` marks one low-level run; `agent_settled` marks full settlement after retry, compaction, and queued continuations.
58- Therefore a truly ephemeral question that never enters session history needs either an extension command or a separate process (`pi -p` / `pi --mode json` / a second `--mode rpc --no-session` child).
60### Events
62Streamed as JSONL: `agent_start`, `agent_end`, `agent_settled`, `turn_start`, `turn_end`, `message_start`, `message_update`, `message_end`, `tool_execution_start|update|end`, `bash_execution_update`, `queue_update`, `compaction_start|end`, `auto_retry_start|end`, `summarization_retry_*`, `extension_error`.
64- `message_update` carries only deltas; clients assemble partial state by `contentIndex`; `message_end.message` is authoritative.
65- Tool-call streaming exposes `toolcall_start` (`id`, `toolName`), `toolcall_delta` (argument chunks), `toolcall_end` (complete call). This is the only source for progressive edit intent, and argument chunks are partial JSON text.
66- `tool_execution_update.partialResult` is cumulative, not a delta.
68### Extension UI over RPC
70| Method | RPC behavior |
71| --- | --- |
72| `select`, `confirm`, `input`, `editor` | Request/response sub-protocol with matching `id`; optional `timeout` auto-resolves agent-side |
73| `notify`, `setStatus`, `setWidget`, `setTitle`, `set_editor_text` | Fire-and-forget requests |
74| `custom` | Returns `undefined` |
75| `setWorkingMessage`, `setWorkingIndicator`, `setFooter`, `setHeader`, `setEditorComponent`, `setToolsExpanded` | No-ops |
76| `getEditorText`, `getToolsExpanded`, theme getters/setters | Degraded or empty |
78`ctx.mode === "rpc"` and `ctx.hasUI === true`; TUI-only capability must be guarded on `ctx.mode === "tui"`.
80### Extension hooks a companion extension can use
82- `pi.registerTool` at load or at runtime; new tools are callable without `/reload`.
83- Built-in tools `read`, `bash`, `powershell`, `edit`, `write`, `grep`, `find`, `ls` can be overridden by registering the same name; result and `details` shapes must match exactly; omitted renderers fall back to built-ins; `promptSnippet`/`promptGuidelines` are not inherited.
84- Built-in tools also accept pluggable operations (`ReadOperations`, `WriteOperations`, `EditOperations`, `BashOperations`, …) via `createReadTool` and siblings, plus a `spawnHook` for shell tools. This delegates I/O without reimplementing tool semantics.
85- `tool_call` can mutate arguments or block; `tool_result` can post-process.
86- `input` event sees raw text with `source` of `interactive | rpc | extension` and can `continue`, `transform`, or `handled`.
87- `before_agent_start` exposes and can extend `systemPrompt` and structured `systemPromptOptions`.
88- `pi.registerCommand` supports `getArgumentCompletions`; `pi.getCommands` mirrors `get_commands`.
89- Tool output must be truncated; built-in limits are 50KB and 2000 lines.
91## Neovim facts
93### Transport
95- `vim.system(cmd, { stdin = true, stdout = fun(err, data), stderr = fun(err, data) })` gives streaming callbacks plus `SystemObj:write(data)` and `obj:write(nil)` to close stdin; `obj:kill()` stops the child.
96- Output callbacks run in fast contexts; API calls must be deferred through `vim.schedule` (`api-fast`, `vim.in_fast_event()`).
97- `jobstart`/`nvim_chan_send` remain the alternative channel API.
99### Buffers and edits
101| Need | Mechanism | Caveat |
102| --- | --- | --- |
103| Precise edit | `nvim_buf_set_text`, `nvim_buf_set_lines` | Each call opens a new undo block |
104| One undoable change | `:undojoin` before the next change | `E790` after undo/redo; must not be used blindly |
105| Change detection | `nvim_buf_attach` `on_lines`, `b:changedtick` | Callbacks are fast-context |
106| Diffing model output against buffer | `vim.text.diff` with `result_type = 'indices'` | Available in 0.12 |
107| Disk coherence after buffer edits | buffer write plus `:checktime`; `'autoread'` defaults on | Unwritten buffers stay invisible to filesystem tools |
109### Presentation
111- Extmarks provide `virt_text` with `virt_text_pos = "inline"` for ghost text, `virt_lines` (with `virt_lines_above`, `virt_lines_overflow`), highlights, and signs.
112- `nvim_set_decoration_provider` with `ephemeral` marks renders per redraw without persistent state.
113- `vim.diagnostic` namespaces keep agent findings separate from LSP and compiler diagnostics.
114- Quickfix and location lists use `setqflist`/`setloclist` and normal navigation.
116### Integration surface
118- `nvim_exec_autocmds` emits `User` events with a `data` payload (`event-data`), which fits publishing cached pivi state.
119- `nvim_create_user_command` supplies subcommands, `nargs`, and custom completion for `:Pi help` and `:Pi command ...`.
120- `<Plug>` mappings expose behavior without claiming global keys.
121- `vim.ui.select` and `vim.ui.input` can back RPC dialog methods.
123## Spec claims versus evidence
125| Spec claim | Support | Risk |
126| --- | --- | --- |
127| Non-terminal JSONL subprocess channel | `pi --mode rpc` plus `vim.system` stdin/stdout | Low |
128| Semantic status (queue, run, tool, retry, compaction) | `get_state`, `get_session_stats`, event stream | Low |
129| Slash commands via `:Pi command ...` | `get_commands` plus `prompt` with `/name` | Low; TUI-only commands unavailable |
130| `:Pi help` runnable during an active run | Extension command executes during streaming, or a separate ephemeral process | Medium; not ephemeral if routed through the working session |
131| Loaded buffers authoritative for reads and edits | Built-in tool override or injected `ReadOperations`/`EditOperations`/`WriteOperations` | Medium; result and `details` shapes must match exactly |
132| Progressive ghost text from streaming tool arguments | `toolcall_delta` plus inline `virt_text` | Medium; requires tolerant partial-JSON parsing |
133| One coherent undoable change per edit | `nvim_buf_set_text` plus `:undojoin` | Medium; `E790` and multi-hunk edits |
134| Edits visible to later shell work without watchers | Explicit buffer write plus `:checktime` | Medium; unwritten buffers diverge from disk |
135| Extension dialogs mapped to native surfaces | `extension_ui_request`/`extension_ui_response` | Low |
136| Multiple sessions, resume, switch | `--session`, `switch_session`, `new_session`, `fork`, `clone` | Low |
138## Open questions
140- Does `:Pi help` use a second short-lived Pi process, or a companion extension command inside the working session that suppresses history?
141- Can two Pi processes safely target one session file, or must ephemeral help always run with `--no-session`?
142- Is buffer authority better implemented as operations injection into built-in tools than as full tool overrides, given the exact `details` shape requirement?
143- How should partial `toolcall_delta` arguments be parsed safely enough to show ghost text without ever mutating a buffer?
144- When must pivi write a modified buffer to disk so that agent shell commands observe agent edits?

neovim/.system/research/NVIM-RESEARCH-NOSZ7JUQ-pi-session-resume-and-transcript-backfill-capabi/index.md

Added
new file mode 100644

+76 / −0 text lines

1---
2id: NVIM-RESEARCH-NOSZ7JUQ
3type: research
4title: Pi session resume and transcript backfill capabilities
5---
6
7# Pi session resume and transcript backfill capabilities
8
9Verified against the installed Pi `0.87.1` (`pi --mode rpc`), not from prose.
10Probed live by resuming a real session with `--continue` and issuing query RPCs.
12## Resume is a native Pi capability
14Pi already resolves "last session in cwd"; pivi need not enumerate to get the common case.
16| Flag | Meaning | Usable over RPC |
17| --- | --- | --- |
18| `--continue`, `-c` | resume the most recent session for the project (cwd) | yes |
19| `--session <path\|id>` | resume a specific session file or partial UUID | yes |
20| `--session-id <id>` | use an exact project session id, creating it if missing | yes |
21| `--resume`, `-r` | interactive picker to select a session | no — TUI only |
22| `--fork <path\|id>` | fork a session into a new one | yes |
23| `--session-dir <dir>` | directory for session storage and lookup | yes |
24| `--no-session` | ephemeral, nothing saved | yes |
25| `--name`, `-n` | display name only, not a resume key | yes |
27`PI_CODING_AGENT_SESSION_DIR` sets the storage directory (`--session-dir` overrides it).
28On this machine it resolves to `/home/me/.local/state/pi/sessions`, not the `~/.pi/agent/sessions` shown in `--help` examples; resolve it at runtime, never hardcode.
30## Session storage layout
32- Sessions are bucketed per project under the session dir, one directory per cwd.
33- The bucket directory name encodes the cwd (`/` to `-`, wrapped in `--…--`), but the encoding is lossy and ambiguous; do not decode it.
34- Each session is a file `<ISO-timestamp>_<uuid>.jsonl`.
35- The first line is a header: `{ "type":"session", "id", "timestamp", "cwd" }`.
36- Robust cwd enumeration: read each file's header `cwd` and sort by header `timestamp` or the filename timestamp. This is authoritative; the bucket name is not.
37- There is no session-listing RPC. The Sessions RPC surface is `new_session`, `switch_session`, `fork`, `clone`, `set_session_name`. Listing for a cwd picker must read the filesystem.
39## Transcript backfill RPCs
41All three return `success:true` on a resumed session with no prompt sent, so backfill performs no model call.
43| RPC | Response shape | Use |
44| --- | --- | --- |
45| `get_entries` | `{ entries: [ { type, id, parentId, timestamp, … } ] }` | flat log, authoritative for full re-render |
46| `get_entries` with `since:<entryId>` | entries after the cursor; unknown id fails with `"Entry not found: <id>"` | durable incremental cursor |
47| `get_tree` | `{ tree: [ { entry, children: [ … ] } ] }`, recursive | branch and leaf detection |
48| `get_messages` | `{ messages: [ { role, content, sections:{ preamble, … } } ] }` | rendered messages, includes the system preamble |
50### Entry vocabulary
52`get_entries` entry `type` values observed: `model_change`, `thinking_level_change`, `message`, `session_info`, `custom`.
53A `message` entry carries a full message object under `.message`.
55Message roles: `system`, `user`, `assistant`, `toolResult`.
57- Assistant `message.content` is a list of parts, each tagged by `type`:
58 - `{ type:"thinking", thinking, thinkingSignature }`
59 - `{ type:"tool_call", id, name, arguments }` where `arguments` is a decoded object, not a string.
60 - text parts.
61 - Assistant messages also carry `usage`, `stopReason`, `model`, `provider`, `responseId`.
62- A tool result is its own message: `{ role:"toolResult", toolCallId, toolName, content:[{type,text}], isError, timestamp }`, matched to its call by `toolCallId`.
64## Conclusions
66- `:Pi resume` default ("last in cwd") maps directly to `--continue`; a specific target maps to `--session <id>`. No encoding of the bucket name is required for either.
67- A cwd session picker needs a filesystem scan of the session dir, filtering by each header's `cwd`, because no listing RPC exists.
68- Full transcript re-render is possible from `get_entries`: it carries tool calls (as assistant content parts) and tool results (as `toolResult` messages) correlated by id, plus model and usage.
69- The stored shape differs from the live streaming shape. The live stream delivers `message_update` deltas and rich tool-result `details` (display diff, unified patch, first changed line, truncation, output path); a stored `toolResult` carries only `content` text and `isError`. A backfill adapter is therefore distinct from the live assembly path, and backfilled tool entries degrade to subject and text rather than a reconstructed diff, consistent with "never invent an outcome".
71## Unresolved
73- Exact, reversible bucket-name encoding. Treated as opaque; headers are read instead.
74- Whether any persisted `toolResult` ever includes the live `details` (diff/patch/truncation); none seen in the sample. Decides whether backfilled edits can show a diff or only text.
75- `leafId` selection: `get_tree` exposes branches via `children`, but which leaf is the current head on resume is not yet pinned.
76- Whether `--continue` over `--mode rpc` always attaches without a model call under all providers; the probe showed query-only RPCs succeed with no prompt.

neovim/.system/research/NVIM-RESEARCH-T3BL4TK4-pi-tool-result-formats-for-presentation/index.md

Added
new file mode 100644

+79 / −0 text lines

1---
2id: NVIM-RESEARCH-T3BL4TK4
3type: research
4title: Pi tool result formats for presentation
5---
6
7# Pi tool result formats for presentation
8
9Read from real Pi session logs on disk (`$PI_CODING_AGENT_SESSION_DIR`), not from prose.
10Each tool result is a `toolResult` message: `{ role, toolCallId, toolName, content, isError, timestamp, details? }`.
11`content` is always a text block list `[{ type:"text", text }]`; the rich, per-tool structure lives in `details`.
13This closes the evidence gap that blocked grep file-grouping and the bash full-output surface.
15## Per-tool shapes
17| Tool | `details` keys | `content` text shape |
18| --- | --- | --- |
19| edit | `diff`, `firstChangedLine` | a short sentence, e.g. `Successfully replaced 4 block(s) in <path>.` |
20| grep | none | ripgrep context output, or `No matches found` |
21| find | none | newline-separated names, no line numbers |
22| ls | none | newline-separated entries, directories suffixed `/` |
23| bash | `truncation`, `fullOutputPath` | the captured output, possibly truncated |
24| read | `truncation` | file content |
25| write | none | a short sentence |
27### edit
29`details.diff` is a display diff with a line-number gutter and change markers, for example:
31```
32 9 * ...
33+ 11 * The tools use ...
34+ 12 * a system prompt section ...
35```
37A removed line is marked `-`, an added line `+`, and a context line has no marker.
38`details.firstChangedLine` is the first changed line number.
39This matches what pivi already consumes; no change needed for the edit diff.
41### grep
43No `details`. The match structure is only in `content.text`, in ripgrep's context format:
45- a match line is `PATH:LINE:TEXT`
46- a context line is `PATH-LINE-TEXT`
47- distinct match groups may be separated by a `--` line
48- an empty search is exactly `No matches found`
50The path repeats on every line, so grouping by file means reading the `PATH` prefix and collecting consecutive lines that share it; the match lines are the ones joined by `:` rather than `-`.
51There is no column offset in this format, so an exact in-line match span is not available; only the whole match line can be distinguished without re-searching the text client-side.
53### find and ls
55`content.text` is a newline-separated list.
56`find` returns names or paths with no line numbers, so a find result groups trivially as a flat list.
57`ls` suffixes directories with `/`.
59### bash
61`details.truncation` carries `{ truncated: bool, ... }`; `details.fullOutputPath` is a filesystem path to the complete output when the kept result was trimmed.
62A full-output detail surface opens that path.
64### read
66`details.truncation` only; the subject path is the file itself, so a preview leads back to the file that was read.
68## Conclusions
70- grep and find file-grouping is implementable now: parse the ripgrep context format, grouping consecutive lines by their `PATH` prefix and marking the `:` match lines; `find` is a flat list.
71- Exact in-line match highlighting is not supported by the data; distinguish the match line, or re-find the term client-side, rather than relying on an offset.
72- The bash full-output surface opens `details.fullOutputPath`; truncation is `details.truncation.truncated`.
73- Edit diff and first-changed-line are already correct against the real shape; no rework there.
75## Unresolved
77- Whether ripgrep emits `--` separators and heading lines under every Pi configuration, or only with certain flags; the parser must tolerate both.
78- Whether a stable match column is ever present in any grep mode; none seen in the sampled logs.
79- Whether `details.truncation` ever includes a kept/total count useful to show beyond the boolean.

neovim/.system/specs/NVIM-SPEC-GMWDCMJZ-pivi-native-neovim-integration/index.md

Added
new file mode 100644

+297 / −0 text lines

1---
2id: NVIM-SPEC-GMWDCMJZ
3type: spec
4title: pivi Native Neovim Integration
5research:
6 - NVIM-RESEARCH-KZYYEFY_
7 - NVIM-RESEARCH-NOSZ7JUQ
8 - NVIM-RESEARCH-T3BL4TK4
9---
11# pivi Native Neovim Integration
13## Intent
15pivi makes Pi feel native inside Neovim rather than embedding Pi's terminal interface.
16Pi remains a fully empowered coding agent.
17Neovim supplies editing, navigation, presentation, and live editor context.
19[Accepted native edit and follow-mode mockup](./native-agent-trail.html)
21## Scope
23pivi provides:
25- Persistent Pi sessions controlled through Pi RPC.
26- Neovim buffers for prompts, transcripts, session navigation, and detailed output.
27- Native quickfix lists, location lists, diagnostics, extmarks, signs, diffs, and navigation.
28- Live access to core Neovim state and unrestricted Neovim Lua execution.
29- A bundled Pi companion extension loaded in addition to the user's normal Pi configuration.
31Initial editor tools focus on buffers, selections, windows, tabs, marks, jumps, changes, lists, diagnostics, commands, and Lua execution.
32LSP-specific tools are outside the initial scope.
34## Session behavior
36- A Pi session is an explicit task identity with persistent history.
37- Each session captures a working directory as its execution scope.
38- Multiple sessions may share one working directory.
39- A tab may select a default session but does not own its lifetime.
40- Source buffers do not own sessions.
41- Closing a session window hides presentation without deleting history or implicitly stopping Pi.
42- A session can be resumed: the most recent session for the working directory by default, or an earlier session chosen by identity.
43- Resuming attaches to persistent history without starting a new conversation and without a model call.
44- Prior sessions for the working directory are listable so one can be chosen to resume.
45- The client can restart: pivi reloads itself while a working session is resumed by identity, losing neither its history nor its place.
46- While a session run is active, a submission is delivered as steering or as a follow-up, by a distinct and announced choice, and is never silently dropped.
47- Accepting the prompt while the agent is working steers the active run, the way Pi does; a separate, announced key queues a follow-up.
48- Steering reaches the active run; a follow-up is queued, and queued follow-ups remain listable and clearable before delivery.
50```mermaid
51stateDiagram-v2
52 [*] --> Idle
53 Idle --> Running: submit
54 Running --> Running: steer, or queue follow-up
55 Running --> Idle: settle
56 Running --> Idle: abort
57 Idle --> [*]: stop session
58```
60## Session restoration
62Resuming a session is worthless if the conversation it resumes is invisible, so a resumed session shows the document it already is.
64- Resuming rebuilds the transcript from the session's recorded history as addressable entries, with messages rendered and tool calls paired with their results.
65- A restored entry is navigable, collapsible, and inspectable exactly like a live one; restoration is presentation and never alters recorded history.
66- A restored tool entry whose recorded result carries no change detail degrades to its subject and result text rather than a fabricated diff.
67- Restoration performs the history reads it needs but no model call, and a large history stays responsive as it renders.
69pivi restores its own sessions; it never owns the editor's session persistence. Coupling to a native Neovim session workflow stays weak.
71- pivi publishes a serializable descriptor of its live sessions for a working directory, and an idempotent restore entry point.
72- A consumer captures the descriptor when it saves its own editor session and invokes restore after loading it; pivi registers no editor session-load hook and imposes no global mapping.
73- Restore resumes the described sessions and rebuilds their transcripts; a missing descriptor or an absent session degrades quietly to no restoration.
75```mermaid
76stateDiagram-v2
77 [*] --> Absent
78 Absent --> Resuming: resume last in cwd or chosen session
79 Absent --> Resuming: consumer restore from descriptor
80 Resuming --> Restored: history rebuilt as entries
81 Restored --> Restored: restart reloads client, resumes by identity
82 Restored --> [*]: stop session
83```
85## Slash commands
87- Pi slash commands are available through `:Pi command ...`.
88- Only commands Pi exposes to non-interactive clients are offered; terminal-only commands are absent.
89- In a Pi input buffer, `/` invokes slash-command entry only when the cursor is at the first character.
90- Elsewhere, `/` retains ordinary Neovim behavior.
92## One-shot help
94- `:Pi help` answers a fast question about Neovim, pivi, or Pi.
95- Help runs as an independent ephemeral agent run with no persisted session and no shared history.
96- Help never enters a working session's transcript, queue, or status.
97- Help stays available while a working session runs, and neither delays nor interrupts it.
98- Help failure is isolated and never degrades a working session.
99- Help may read, and never modifies the editor, the filesystem, or Pi state.
100- Each question carries what the user can currently see rather than whole buffers.
101- Editor documentation is answered from the running instance, so the version and installed plugins decide the answer.
102- pivi's own behavior is supplied as knowledge to the agent rather than assumed.
104```mermaid
105flowchart LR
106 editor["Neovim"] --> session["Working session run"]
107 editor --> help["Ephemeral help run"]
108 session --> history["Persistent session history"]
109 help --> discard["Discarded after answer"]
110 help --> readonly["Read-only editor and documentation lookups"]
111```
113## Editor context
115- Each submission may carry an immutable snapshot of its originating buffer, path, revision, cursor, range, selection kind, selected text, and bounded surrounding text.
116- Queued submissions retain their own snapshots.
117- Pi can obtain fresh ambient editor state before later model calls.
118- Full buffer contents are fetched on demand rather than attaching every open buffer automatically.
119- Loaded buffers, including unsaved contents, are authoritative for editor-aware reads.
120- The Pi prompt receives a short stable orientation to the live Neovim environment without replacing existing system or project instructions.
122## Editing
124- Pi may edit without an approval gate.
125- Reads, edits, and writes preserve the behavior and improvements of Pi's upstream tools while making loaded Neovim buffers authoritative.
126- Agent changes to loaded buffers appear directly in Neovim, remain undoable, and become visible to filesystem-based commands without requiring manual reload.
127- Unloaded paths retain normal Pi filesystem behavior.
128- Validated edit intent may appear progressively as ghost text while tool arguments stream.
129- Real buffer mutation begins only after complete valid edit arguments exist.
130- An edit operation presents one coherent undoable change where Neovim permits it.
131- pivi uses no filesystem watchers.
132- Arbitrary shell or third-party tool mutations without identified paths are not represented as precise editor edits.
134## Transcript presentation
136A transcript is the conversation itself, presented as the document it already is.
138- Transcript text is the messages as authored; pivi's own framing is presentation rather than content.
139- Copying transcript text yields the original message text, without framing.
140- Message formatting is rendered rather than shown as markup, and embedded code is presented in its own language.
141- Rendering degrades to plain readable text when a format cannot be rendered.
142- Presentation never performs Pi RPC, and streaming stays responsive as a transcript grows.
144## Transcript navigation
146Every transcript entry is an addressable unit: a submission, an answer, a tool call, a tool result, or an error.
148- An entry can be collapsed to a single readable line or expanded to its full content.
149- Voluminous entries, such as tool results, start collapsed.
150- The user can move between entries, and between tool calls, with ordinary motions.
151- An entry that names a location is navigable to that location.
152- An entry can be inspected in detail without leaving the transcript.
153- Entry state is presentation only and never alters session history.
155```mermaid
156stateDiagram-v2
157 [*] --> Collapsed: entry appended
158 Collapsed --> Expanded: expand
159 Expanded --> Collapsed: collapse
160 Expanded --> Located: follow reference
161 Located --> Expanded: return
162```
164## Tool presentation
166A tool call is work the user did not watch happen, so the transcript has to account for it, the way Pi's own interface does, without turning the log into noise.
168[Accepted tool presentation mockup](./tool-presentation.html)
170The transcript stays a lean log and the detail is summoned, not spilled.
172- A tool is one headline while collapsed: a tool-coloured gutter indicator, the tool, what it acted on, and how it ended.
173- An entry expands in place to its detail and collapses back; voluminous detail starts collapsed and an outcome stays legible either way.
174- Expanded detail reads as the tool's own content set apart from the conversation, not as more message text.
175- The focused entry is distinguished from the rest.
176- A tool that reports nothing about its own work degrades to its subject and indicator, never to a guess.
178Each tool is presented as what it actually reports.
180- A completed edit shows its change as a diff with added and removed lines distinguished, and that change opens as a full editor comparison on request; navigating from the edit reaches its first changed line.
181- A shell tool shows its output as it arrives, in the language it came from when known, and a truncated result says so while its full output stays reachable.
182- A search tool groups its matches by file with the matched text distinguished, and its cross-file findings reach a quickfix list.
183- A file read shows a syntax-aware preview that leads to the file itself.
184- A failed tool shows a single red outcome and no body.
186Full detail that does not belong inline is a dedicated detail surface, distinct from the transcript and dismissible, never overwriting the user's working window.
188```mermaid
189stateDiagram-v2
190 [*] --> Collapsed: tool call
191 Collapsed --> Collapsed: output arrives, outcome updates
192 Collapsed --> Expanded: expand
193 Expanded --> Collapsed: collapse
194 Expanded --> Detail: open comparison or full output
195 Collapsed --> Detail: open comparison or full output
196 Detail --> Expanded: dismiss
197 Detail --> Collapsed: dismiss
198```
200## Agent activity
202- Active edits may use signs, line highlights, extmarks, virtual text, or virtual lines.
203- Completed edits leave a navigable changed-line trail until cleared by defined editor activity or session action.
204- Activity belongs to its Pi session and does not overwrite unrelated diagnostic or extmark namespaces.
205- File and range references are navigable through normal Neovim motions and lists.
206- Cross-file findings use quickfix lists.
207- Window-associated findings use location lists.
208- AI diagnostics remain distinguishable from compiler and language-server diagnostics.
210## Follow-agent mode
212- Follow mode is optional and disabled unless selected by the user.
213- It follows location-bearing reads, edits, findings, and explicit navigation rather than every event.
214- It can follow in a dedicated window, a dedicated tab, or the current window.
215- Dedicated-window following preserves the user's working window.
216- Passive following avoids unnecessary jumplist pollution.
217- The user can return to the location held before following began.
219## Pi compatibility
221- Pi RPC is pivi's sole integration channel; no embedded Pi TUI or TUI escape hatch.
222- Implement every supported RPC capability through native Neovim surfaces, generically rather than per extension.
223- Preserve Pi-owned behavior; use public RPC operations without private internals or TUI emulation.
224- New features using existing RPC contracts remain usable without feature-specific pivi changes.
225- Unknown content remains readable and inspectable; unsupported interactions are reported explicitly.
226- RPC UI state belongs to its session; concurrent tool activity is correlated by call ID.
227- The companion extension is shipped with pivi and injected additively when Pi starts.
228- User, project, package, provider, skill, prompt, and tool configuration continues to load under Pi's normal rules.
229- pivi does not silently alter Pi project trust or restrict available tools.
230- Extension tools, commands, hooks, prompt changes, session behavior, and supported RPC dialogs remain functional.
231- TUI-only renderers, custom components, keybindings, headers, footers, and terminal input are not emulated.
232- Supported extension dialogs and status requests map to native Neovim surfaces.
233- Unrestricted Neovim Lua execution is available alongside structured convenience tools.
235## Native integration invariant
237pivi is an optional producer of native Neovim state, never the owner of surrounding configuration.
239- It does not replace or require a statusline, winbar, tabline, picker, notification system, layout, or keymap framework.
240- It publishes cached state through native variables and semantic `User` events.
241- It offers commands and `<Plug>` mappings without imposing global mappings.
242- Consumers can degrade to ordinary Neovim behavior when pivi is absent.
243- Loading pivi succeeds when the Pi executable is unavailable; starting Pi reports the missing capability.
244- Status consumers never perform Pi RPC during statusline evaluation.
246## Transport and status
248- Pi RPC uses a non-terminal JSONL subprocess channel.
249- Terminal dimensions, alternate screens, cursor escapes, and terminal key forwarding are not part of pivi.
250- Standard error remains separate from protocol output.
251- ANSI styling in payload text is stripped or translated before native presentation.
252- Semantic session status includes connection, queue, run, tool, waiting, compaction, retry, abort, and error states.
253- Status also exposes available model, thinking, session, context, usage, and extension-status data.
254- Status changes redraw native status surfaces and emit a semantic event.
256## Acceptance criteria
258- A Pi slash command can run through `:Pi command ...`; `/` invokes slash-command entry only at the first character of a Pi input buffer.
259- A transcript renders message formatting, presents embedded code in its own language, and still yields the original text when copied.
260- A collapsed tool entry is one line carrying a tool-coloured indicator, the subject, and the outcome; the focused entry is visibly distinguished.
261- A tool entry expands its detail in place and collapses back, and the detail is set apart from conversation text.
262- A completed edit shows added and removed lines distinctly, opens as an editor comparison on a dedicated surface that preserves the working window, and navigating from it lands on its first changed line.
263- Output of a long-running tool appears progressively rather than only at completion, and a truncated result is marked and its full output stays reachable.
264- A search tool groups matches by file with the matched text distinguished and sends cross-file findings to a quickfix list.
265- A file read presents a syntax-aware preview that leads to the file.
266- A failed tool shows a single outcome line and no body.
267- A tool result is collapsed on arrival, expands on request, and collapsing never changes session history.
268- A user can move between transcript entries with ordinary motions and reach the location an entry names.
269- Transcript presentation performs no Pi RPC, and a long streamed answer stays responsive.
270- `:Pi help` answers while a working session run is active, without appearing in that session's history, queue, or status.
271- A help question carries the visible editor region, layout, selection, recent messages, and the last error, and no full buffer.
272- Help can answer an editor documentation question from the running instance, including documentation of installed plugins.
273- No help run can modify a buffer, a file, or Pi state.
274- A submission made during an active run is delivered as steering or a follow-up by a distinct, announced choice, and is never silently dropped.
275- Accepting the prompt while the agent is working steers the run; a separate announced key queues a follow-up.
276- A queued follow-up can be listed and cleared before delivery.
277- A user can create, resume, switch, and stop explicit Pi sessions without tying their lifetime to a source buffer or tab.
278- Resuming with no target resumes the most recent session for the working directory; a specific session resumes by identity; neither starts a new conversation nor calls the model.
279- Prior sessions for the working directory can be listed and one chosen to resume.
280- Resuming rebuilds the transcript as addressable entries with rendered messages and tool calls paired to their results, and the rebuild performs no model call.
281- A restored tool entry whose recorded result carries no change detail shows its subject and result text rather than a fabricated diff.
282- Restarting reloads the pivi client and resumes the active session by identity with its history and place intact.
283- pivi publishes a serializable per-working-directory session descriptor and an idempotent restore entry point, registers no editor session-load hook, and imposes no global mapping, so a native-session workflow can capture and restore pivi without pivi owning session persistence.
284- Restoring from a missing descriptor or an absent session degrades quietly to no restoration.
285- A prompt can include an unsaved selection with stable source and revision metadata.
286- Pi can read unsaved loaded-buffer content and use current core Neovim context on demand.
287- Pi can execute arbitrary Neovim Lua and use structured editor operations.
288- A normal Pi edit to a loaded buffer appears without reload, is undoable, remains coherent with subsequent shell work, and receives visible activity markers.
289- Streaming edit arguments can produce non-mutating ghost presentation; incomplete arguments never mutate the real buffer.
290- Follow mode can track an agent edit in a dedicated viewport without taking over the user's working window.
291- Quickfix, location-list, diagnostic, and file navigation use normal Neovim behavior.
292- Existing Pi extensions and tools continue to run except for capabilities inherently specific to Pi's TUI.
293- A custom Neovim configuration can consume pivi state and events without requiring pivi to be installed or loaded.
294- pivi does not modify user-owned statuslines, winbars, tablines, global mappings, or picker configuration.
295- No filesystem watcher is started.
296- Acceptance tests verify RPC-only integration, generic native capability mapping, public RPC ownership boundaries, forward-compatible content fallback, explicit unsupported interactions, session-scoped UI state, and call-ID correlation for concurrent tools.
297- Acceptance tests cover multiline editing, prompt updates, widget placement, cancellation, and session isolation.

neovim/.system/specs/NVIM-SPEC-GMWDCMJZ-pivi-native-neovim-integration/native-agent-trail.html

Added
new file mode 100644

+92 / −0 text lines

1<section class="pivi-mockup">
2 <style>
3 :host { color-scheme: dark; font: 14px/1.35 ui-monospace, "Cascadia Mono", Consolas, monospace; }
4 .pivi-mockup { max-width: 1120px; margin: 0 auto; color: #d7d7d7; background: #17191d; border: 1px solid #464b55; box-shadow: 0 10px 35px #0008; }
5 .tabs, .winbar, .status { display: flex; align-items: center; min-height: 1.7em; padding: 0 .65em; white-space: pre; }
6 .tabs { background: #242830; gap: 1.1em; color: #a9b0bc; }
7 .tabs .active { color: #f0f0f0; background: #343945; margin: 0 -.4em; padding: 0 .4em; }
8 .workspace { display: grid; grid-template-columns: minmax(0, 3fr) minmax(24em, 2fr); min-height: 29em; }
9 .window { min-width: 0; position: relative; }
10 .window + .window { border-left: 1px solid #464b55; }
11 .winbar { justify-content: space-between; background: #202329; color: #bfc5cf; border-bottom: 1px solid #30343c; }
12 .agent { color: #deb887; }
13 .buffer { padding: .45em 0 1em; overflow: hidden; }
14 .line { display: grid; grid-template-columns: 2em 1.2em minmax(0, 1fr); min-height: 1.45em; }
15 .num { color: #636b78; text-align: right; padding-right: .45em; user-select: none; }
16 .sign { color: #7f8794; text-align: center; }
17 .code { white-space: pre; overflow: hidden; }
18 .kw { color: #d49adf; } .str { color: #e6c384; }
19 .editing { background: #3a3223; }
20 .editing .sign { color: #efbd6b; }
21 .changed { background: #22352c; }
22 .changed .sign { color: #8ec07c; }
23 .virt { display: grid; grid-template-columns: 3.2em minmax(0, 1fr); color: #87b98b; background: #1c2923; }
24 .virt::before { content: "+"; text-align: right; padding-right: .55em; color: #8ec07c; }
25 .ghost { color: #98a1ad; font-style: italic; }
26 .status { justify-content: space-between; background: #292d35; color: #ccd0d8; border-top: 1px solid #464b55; }
27 .external { color: #89919e; }
28 .controls { display: flex; gap: .5em; padding: .65em; border-top: 1px solid #343944; background: #202329; }
29 button { font: inherit; color: #d7d7d7; background: #303540; border: 1px solid #565d69; padding: .3em .7em; }
30 button[aria-pressed="true"] { border-color: #d7a85d; color: #f3c77b; }
31 button:focus-visible { outline: 2px solid #9ccfd8; outline-offset: 2px; }
32 .note { margin-left: auto; align-self: center; color: #7f8794; }
33 </style>
34 <div class="tabs"><span class="active">1 api</span><span>2 tests</span><span>3 docs</span><span class="agent">π refactor-parser</span></div>
35 <div class="workspace">
36 <article class="window">
37 <header class="winbar"><span>lua/parser.lua</span><span>human workspace</span></header>
38 <div class="buffer">
39 <div class="line"><span class="num">38</span><span class="sign"> </span><span class="code"><span class="kw">local function</span> parse(input)</span></div>
40 <div class="line"><span class="num">39</span><span class="sign"> </span><span class="code"> <span class="kw">local</span> tokens = tokenize(input)</span></div>
41 <div class="line changed"><span class="num">40</span><span class="sign">┃</span><span class="code"> <span class="kw">return</span> parse_tokens(tokens)</span></div>
42 <div class="line"><span class="num">41</span><span class="sign"> </span><span class="code"><span class="kw">end</span></span></div>
43 <div class="line"><span class="num">42</span><span class="sign"> </span><span class="code"></span></div>
44 <div class="line"><span class="num">43</span><span class="sign"> </span><span class="code"><span class="kw">return</span> { parse = parse }</span></div>
45 </div>
46 </article>
47 <article class="window">
48 <header class="winbar"><span>lua/tokenize.lua</span><span class="agent">π editing 17:19</span></header>
49 <div class="buffer">
50 <div class="line"><span class="num">15</span><span class="sign"> </span><span class="code"><span class="kw">local function</span> scan(input)</span></div>
51 <div class="line"><span class="num">16</span><span class="sign"> </span><span class="code"> <span class="kw">local</span> result = {}</span></div>
52 <div class="line editing"><span class="num">17</span><span class="sign">●</span><span class="code"> <span class="kw">for</span> token <span class="kw">in</span> input:gmatch(<span class="str">'%S+'</span>) <span class="kw">do</span> <span class="ghost">π editing…</span></span></div>
53 <div class="virt"><span></span><span class="code"> result[#result + 1] = normalize(token)</span></div>
54 <div class="line editing"><span class="num">18</span><span class="sign">│</span><span class="code"> result[#result + 1] = token</span></div>
55 <div class="line editing"><span class="num">19</span><span class="sign">└</span><span class="code"> <span class="kw">end</span></span></div>
56 <div class="line"><span class="num">20</span><span class="sign"> </span><span class="code"> <span class="kw">return</span> result</span></div>
57 <div class="line"><span class="num">21</span><span class="sign"> </span><span class="code"><span class="kw">end</span></span></div>
58 </div>
59 </article>
60 </div>
61 <footer class="status"><span>NORMAL lua/parser.lua</span><span class="external">existing user-owned statusline remains untouched</span><span>40:3</span></footer>
62 <div class="controls" aria-label="Representative controls">
63 <button type="button" data-follow aria-pressed="true">Follow: window</button>
64 <button type="button" data-state aria-pressed="false">Show completed state</button>
65 <span class="note">Illustrative interaction only</span>
66 </div>
67 <script>
68 (() => {
69 const root = document.currentScript.mockupRoot;
70 const follow = root.querySelector('[data-follow]');
71 const state = root.querySelector('[data-state]');
72 follow.addEventListener('click', () => {
73 const on = follow.getAttribute('aria-pressed') !== 'true';
74 follow.setAttribute('aria-pressed', String(on));
75 follow.textContent = on ? 'Follow: window' : 'Follow: off';
76 });
77 state.addEventListener('click', () => {
78 const completed = state.getAttribute('aria-pressed') !== 'true';
79 state.setAttribute('aria-pressed', String(completed));
80 state.textContent = completed ? 'Show active state' : 'Show completed state';
81 root.querySelectorAll('.editing').forEach((line) => {
82 line.classList.toggle('editing', !completed);
83 line.classList.toggle('changed', completed);
84 });
85 const winbar = root.querySelectorAll('.winbar')[1].lastElementChild;
86 winbar.textContent = completed ? 'π edited 17:19' : 'π editing 17:19';
87 const ghost = root.querySelector('.ghost');
88 ghost.textContent = completed ? 'π changed' : 'π editing…';
89 });
90 })();
91 </script>
92</section>

neovim/.system/specs/NVIM-SPEC-GMWDCMJZ-pivi-native-neovim-integration/tool-presentation.html

Added
new file mode 100644

+96 / −0 text lines

1<!doctype html>
2<html lang="en">
3<head>
4<meta charset="utf-8">
5<meta name="viewport" content="width=device-width, initial-scale=1">
6<title>pivi tool presentation — accepted direction (C2 canonical)</title>
7<style>
8 body{background:#111;margin:0;padding:24px;color-scheme:dark;font-family:system-ui,sans-serif}
9 .cap{max-width:680px;margin:0 auto 12px;color:#bbb;font:13px/1.5 system-ui}
10 .cap b{color:#c9b6eb}
11 .t{position:relative;max-width:680px;margin:0 auto;font:13px/1.62 'JetBrains Mono',ui-monospace,monospace;background:#1b1b1b;color:#ededed;padding:10px 0;border-radius:6px;overflow:hidden;min-height:360px}
12 .r{display:grid;grid-template-columns:3ch 1fr;white-space:pre;padding:0 10px}
13 .sign{text-align:center}
14 .head{cursor:pointer}.head:hover{background:#202020}
15 .user{color:#b59ae4}.pi{color:#3ec5e3}.dim{color:#8b8b8b}.faint{color:#5d5d5d}
16 .add{color:#7ba1aa}.del{color:#ec6376}.ok{color:#7ba1aa}.bad{color:#ec6376}.warn{color:#f0ee69}
17 .se{color:#b59ae4}.sb{color:#3ec5e3}.sg{color:#f0ee69}.sr{color:#8b8b8b}
18 .cur{background:#242424}.rail{color:#39343f}.gut{color:#5d5d5d}
19 .kw{color:#b59ae4}.fn{color:#3ec5e3}.str{color:#7ba1aa}
20 .hide{display:none}.cmp{color:#c9b6eb;text-decoration:underline;cursor:pointer}.file{color:#9aabae}
21 .flo{position:absolute;right:12px;top:96px;width:42ch;background:#1f1f1f;border:1px solid #4f3c69;border-radius:4px;font-size:12px}
22 .flo .h{color:#c9b6eb;background:#2d2440;padding:3px 9px;display:flex;justify-content:space-between}
23 .flo .b{padding:5px 9px;white-space:pre}
24</style>
25</head>
26<body>
27<div class="cap">
28 <b>pivi tool presentation — accepted visual direction.</b>
29 Neovim transcript, nugu dark, monospace cells. One headline line per tool, collapsed by default;
30 click a headline to expand detail inline; click the edit's <i>compare</i> to toggle the floating comparison.
31 Terminal fidelity: border-only floats, no shadow.
32</div>
33<section class="t">
34 <div class="r user"><span class="sign">█</span><span class="user"> you</span></div>
35 <div class="r user"><span class="sign">█</span><span class="user">refactor the submission path and run tests</span></div>
36 <div class="r"><span class="sign"></span><span class="pi"> pi</span></div>
37 <div class="r"><span class="sign"></span><span>Reworking delivery resolution, then verifying.</span></div>
39 <div class="r head cur" data-k="edit"><span class="sign se"></span><span><span class="dim">▾ edit</span> session.lua <span class="add">+12</span> <span class="del">−3</span> <span class="cmp" data-cmp="1">↵ compare</span></span></div>
40 <div data-body="edit">
41 <div class="r"><span class="sign"><span class="rail">│</span></span><span><span class="gut">38 </span><span class="del">- local busy = status.is_busy( self.status )</span></span></div>
42 <div class="r"><span class="sign"><span class="rail">│</span></span><span><span class="gut">38 </span><span class="add">+ local busy, delivery = resolve( self, options )</span></span></div>
43 <div class="r"><span class="sign"><span class="rail">│</span></span><span><span class="gut">39 </span><span class="add">+ if busy and not delivery then return queue(…)</span></span></div>
44 </div>
46 <div class="r head" data-k="bash"><span class="sign sb"></span><span><span class="dim">▸ bash</span> just test <span class="ok">✓ 669 passed</span> <span class="faint">4.7s</span></span></div>
47 <div data-body="bash" class="hide">
48 <div class="r"><span class="sign"><span class="rail">│</span></span><span class="dim">Testing: tests/bugabinga/pivi/…</span></div>
49 <div class="r"><span class="sign"><span class="rail">│</span></span><span><span class="ok">Success: 669</span> Failed: 0 Errors: 0</span></div>
50 <div class="r"><span class="sign"><span class="rail">│</span></span><span class="faint">… 2140 lines truncated · 󰈙 full output</span></div>
51 </div>
53 <div class="r head" data-k="grep"><span class="sign sg"></span><span><span class="dim">▸ grep</span> is_busy <span class="warn">7 matches · 3 files</span> <span class="faint">→ quickfix</span></span></div>
54 <div data-body="grep" class="hide">
55 <div class="r"><span class="sign"><span class="rail">│</span></span><span class="file">session.lua</span></div>
56 <div class="r"><span class="sign"><span class="rail">│</span></span><span><span class="gut">409 </span>local busy = <span class="warn">is_busy</span>( self.status )</span></div>
57 <div class="r"><span class="sign"><span class="rail">│</span></span><span class="file">status.lua</span></div>
58 <div class="r"><span class="sign"><span class="rail">│</span></span><span><span class="gut">140 </span>local function <span class="warn">is_busy</span>( state )</span></div>
59 </div>
61 <div class="r head" data-k="read"><span class="sign sr"></span><span><span class="dim">▸ read</span> command.lua <span class="faint">120 lines</span></span></div>
62 <div data-body="read" class="hide">
63 <div class="r"><span class="sign"><span class="rail">│</span></span><span><span class="gut">1 </span><span class="kw">local</span> session = <span class="fn">require</span> <span class="str">'bugabinga.pivi.session'</span></span></div>
64 <div class="r"><span class="sign"><span class="rail">│</span></span><span><span class="gut">2 </span><span class="kw">local</span> notify = <span class="fn">require</span> <span class="str">'std.notify'</span></span></div>
65 <div class="r"><span class="sign"><span class="rail">│</span></span><span class="faint">… 󰈙 open file</span></div>
66 </div>
68 <div class="r"><span class="sign bad"></span><span><span class="dim">write</span> /etc/hosts <span class="bad">✗ permission denied</span></span></div>
70 <div class="flo hide" data-float="1"><div class="h"><span> session.lua</span><span class="faint">comparison · q close</span></div><div class="b"><span class="gut">37</span> local options = options or {}
71<span class="gut">38</span> <span class="del">- local busy = status.is_busy(self)</span>
72<span class="gut">38</span> <span class="add">+ local busy, delivery =</span>
73<span class="gut">39</span> <span class="add">+ resolve( self, options )</span>
74<span class="gut">40</span> if busy and not delivery then</div></div>
75</section>
76<script>
77 (() => {
78 const root = document;
79 root.querySelectorAll('.head').forEach((h) => {
80 h.addEventListener('click', (e) => {
81 if (e.target.dataset && e.target.dataset.cmp) {
82 root.querySelector('[data-float]').classList.toggle('hide');
83 e.stopPropagation();
84 return;
85 }
86 const body = root.querySelector('[data-body="' + h.dataset.k + '"]');
87 const chev = h.querySelector('.dim');
88 const open = !body.classList.contains('hide');
89 body.classList.toggle('hide');
90 chev.textContent = chev.textContent.replace(open ? '▾' : '▸', open ? '▸' : '▾');
91 });
92 });
93 })();
94</script>
95</body>
96</html>

neovim/AGENTS.md

Modified

+1 / −1 text lines

2525│ │ ├── prequire.lua # Protected require with nil-safe proxy
2626│ │ ├── project.lua # Project root detection (weighted markers)
2727│ │ ├── puk.lua # Plugin loader (vim.schedule_wrap defer)
28│ │ ├── table/ # Table util wrappers (deep_copy, join)
28│ │ ├── table/ # Table util wrappers (join)
2929│ │ └── user_command.lua # Fluent user command DSL
3030│ ├── bugabinga/ # Configuration modules (std + plugins only)
3131│ │ ├── lsp.lua # LSP config loader (lsp/*.lua auto-discovery)

neovim/after/ftplugin/image.lua

Added
new file mode 100644

+10 / −0 text lines

1vim.opt_local.number = false
2vim.opt_local.relativenumber = false
3vim.opt_local.signcolumn = 'no'
4vim.opt_local.foldcolumn = '0'
5vim.opt_local.cursorline = false
6vim.opt_local.wrap = false
7vim.opt_local.spell = false
8vim.opt_local.winbar = ''
9vim.opt_local.statuscolumn = ''
10vim.opt_local.scrolloff = 0

neovim/after/ftplugin/markdown.lua

Modified

+5 / −1 text lines

1vim.opt_local.spell = false
1vim.opt_local.wrap = true
2vim.opt_local.linebreak = true
3vim.opt_local.breakindent = true
4vim.opt_local.statuscolumn =
5 '%s%#LineNrBelow#%{%v:virtnum > 0 ? "╰─" : " "%}%*'

neovim/after/ftplugin/qml.lua

Added
new file mode 100644

+12 / −0 text lines

1-- QML/QMLLS tooling.
2-- Quickshell populates this marker with local import paths when the config runs.
3local current = vim.api.nvim_buf_get_name(0)
4local dir = vim.fs.dirname(current)
5local root = dir and vim.fs.root(dir, 'shell.qml')
6
7if root and current:find('/quickshell/', 1, true) then
8 local marker = root .. '/.qmlls.ini'
9 if vim.fn.filereadable(marker) == 0 then
10 vim.fn.writefile({}, marker)
11 end
12end

neovim/after/queries/bash/injections.scm

Added
new file mode 100644

+45 / −0 text lines

1; extends
2
3((comment) @injection.content
4 (#lua-match? @injection.content "^#MISE ")
5 (#offset! @injection.content 0 6 0 0)
6 (#set! injection.language "toml"))
7
8((comment) @injection.content
9 (#lua-match? @injection.content "^# MISE ")
10 (#offset! @injection.content 0 7 0 0)
11 (#set! injection.language "toml"))
13((comment) @injection.content
14 (#lua-match? @injection.content "^#%[MISE%] ")
15 (#offset! @injection.content 0 8 0 0)
16 (#set! injection.language "toml"))
18((comment) @injection.content
19 (#lua-match? @injection.content "^# %[MISE%] ")
20 (#offset! @injection.content 0 9 0 0)
21 (#set! injection.language "toml"))
23((comment) @injection.content
24 (#lua-match? @injection.content "^#USAGE ")
25 (#offset! @injection.content 0 7 0 1)
26 (#set! injection.combined)
27 (#set! injection.language "kdl"))
29((comment) @injection.content
30 (#lua-match? @injection.content "^# USAGE ")
31 (#offset! @injection.content 0 8 0 1)
32 (#set! injection.combined)
33 (#set! injection.language "kdl"))
35((comment) @injection.content
36 (#lua-match? @injection.content "^#%[USAGE%] ")
37 (#offset! @injection.content 0 9 0 1)
38 (#set! injection.combined)
39 (#set! injection.language "kdl"))
41((comment) @injection.content
42 (#lua-match? @injection.content "^# %[USAGE%] ")
43 (#offset! @injection.content 0 10 0 1)
44 (#set! injection.combined)
45 (#set! injection.language "kdl"))

neovim/after/queries/javascript/injections.scm

Added
new file mode 100644

+45 / −0 text lines

1; extends
2
3((comment) @injection.content
4 (#lua-match? @injection.content "^//MISE ")
5 (#offset! @injection.content 0 7 0 0)
6 (#set! injection.language "toml"))
7
8((comment) @injection.content
9 (#lua-match? @injection.content "^// MISE ")
10 (#offset! @injection.content 0 8 0 0)
11 (#set! injection.language "toml"))
13((comment) @injection.content
14 (#lua-match? @injection.content "^//%[MISE%] ")
15 (#offset! @injection.content 0 9 0 0)
16 (#set! injection.language "toml"))
18((comment) @injection.content
19 (#lua-match? @injection.content "^// %[MISE%] ")
20 (#offset! @injection.content 0 10 0 0)
21 (#set! injection.language "toml"))
23((comment) @injection.content
24 (#lua-match? @injection.content "^//USAGE ")
25 (#offset! @injection.content 0 8 0 1)
26 (#set! injection.combined)
27 (#set! injection.language "kdl"))
29((comment) @injection.content
30 (#lua-match? @injection.content "^// USAGE ")
31 (#offset! @injection.content 0 9 0 1)
32 (#set! injection.combined)
33 (#set! injection.language "kdl"))
35((comment) @injection.content
36 (#lua-match? @injection.content "^//%[USAGE%] ")
37 (#offset! @injection.content 0 10 0 1)
38 (#set! injection.combined)
39 (#set! injection.language "kdl"))
41((comment) @injection.content
42 (#lua-match? @injection.content "^// %[USAGE%] ")
43 (#offset! @injection.content 0 11 0 1)
44 (#set! injection.combined)
45 (#set! injection.language "kdl"))

neovim/after/queries/nu/injections.scm

Added
new file mode 100644

+45 / −0 text lines

1; extends
2
3((comment) @injection.content
4 (#lua-match? @injection.content "^#MISE ")
5 (#offset! @injection.content 0 6 0 0)
6 (#set! injection.language "toml"))
7
8((comment) @injection.content
9 (#lua-match? @injection.content "^# MISE ")
10 (#offset! @injection.content 0 7 0 0)
11 (#set! injection.language "toml"))
13((comment) @injection.content
14 (#lua-match? @injection.content "^#%[MISE%] ")
15 (#offset! @injection.content 0 8 0 0)
16 (#set! injection.language "toml"))
18((comment) @injection.content
19 (#lua-match? @injection.content "^# %[MISE%] ")
20 (#offset! @injection.content 0 9 0 0)
21 (#set! injection.language "toml"))
23((comment) @injection.content
24 (#lua-match? @injection.content "^#USAGE ")
25 (#offset! @injection.content 0 7 0 1)
26 (#set! injection.combined)
27 (#set! injection.language "kdl"))
29((comment) @injection.content
30 (#lua-match? @injection.content "^# USAGE ")
31 (#offset! @injection.content 0 8 0 1)
32 (#set! injection.combined)
33 (#set! injection.language "kdl"))
35((comment) @injection.content
36 (#lua-match? @injection.content "^#%[USAGE%] ")
37 (#offset! @injection.content 0 9 0 1)
38 (#set! injection.combined)
39 (#set! injection.language "kdl"))
41((comment) @injection.content
42 (#lua-match? @injection.content "^# %[USAGE%] ")
43 (#offset! @injection.content 0 10 0 1)
44 (#set! injection.combined)
45 (#set! injection.language "kdl"))

neovim/after/queries/python/injections.scm

Added
new file mode 100644

+45 / −0 text lines

1; extends
2
3((comment) @injection.content
4 (#lua-match? @injection.content "^#MISE ")
5 (#offset! @injection.content 0 6 0 0)
6 (#set! injection.language "toml"))
7
8((comment) @injection.content
9 (#lua-match? @injection.content "^# MISE ")
10 (#offset! @injection.content 0 7 0 0)
11 (#set! injection.language "toml"))
13((comment) @injection.content
14 (#lua-match? @injection.content "^#%[MISE%] ")
15 (#offset! @injection.content 0 8 0 0)
16 (#set! injection.language "toml"))
18((comment) @injection.content
19 (#lua-match? @injection.content "^# %[MISE%] ")
20 (#offset! @injection.content 0 9 0 0)
21 (#set! injection.language "toml"))
23((comment) @injection.content
24 (#lua-match? @injection.content "^#USAGE ")
25 (#offset! @injection.content 0 7 0 1)
26 (#set! injection.combined)
27 (#set! injection.language "kdl"))
29((comment) @injection.content
30 (#lua-match? @injection.content "^# USAGE ")
31 (#offset! @injection.content 0 8 0 1)
32 (#set! injection.combined)
33 (#set! injection.language "kdl"))
35((comment) @injection.content
36 (#lua-match? @injection.content "^#%[USAGE%] ")
37 (#offset! @injection.content 0 9 0 1)
38 (#set! injection.combined)
39 (#set! injection.language "kdl"))
41((comment) @injection.content
42 (#lua-match? @injection.content "^# %[USAGE%] ")
43 (#offset! @injection.content 0 10 0 1)
44 (#set! injection.combined)
45 (#set! injection.language "kdl"))

neovim/after/queries/toml/injections.scm

Added
new file mode 100644

+12 / −0 text lines

1; extends
2
3(pair
4 (bare_key) @_key
5 (#any-of? @_key "run" "run_windows")
6 [
7 (string) @injection.content
8 (array (string) @injection.content)
9 ]
10 (#is-mise?)
11 (#mise-run! @injection.content)
12 (#set! injection.include-children))

neovim/after/queries/typescript/injections.scm

Added
new file mode 100644

+45 / −0 text lines

1; extends
2
3((comment) @injection.content
4 (#lua-match? @injection.content "^//MISE ")
5 (#offset! @injection.content 0 7 0 0)
6 (#set! injection.language "toml"))
7
8((comment) @injection.content
9 (#lua-match? @injection.content "^// MISE ")
10 (#offset! @injection.content 0 8 0 0)
11 (#set! injection.language "toml"))
13((comment) @injection.content
14 (#lua-match? @injection.content "^//%[MISE%] ")
15 (#offset! @injection.content 0 9 0 0)
16 (#set! injection.language "toml"))
18((comment) @injection.content
19 (#lua-match? @injection.content "^// %[MISE%] ")
20 (#offset! @injection.content 0 10 0 0)
21 (#set! injection.language "toml"))
23((comment) @injection.content
24 (#lua-match? @injection.content "^//USAGE ")
25 (#offset! @injection.content 0 8 0 1)
26 (#set! injection.combined)
27 (#set! injection.language "kdl"))
29((comment) @injection.content
30 (#lua-match? @injection.content "^// USAGE ")
31 (#offset! @injection.content 0 9 0 1)
32 (#set! injection.combined)
33 (#set! injection.language "kdl"))
35((comment) @injection.content
36 (#lua-match? @injection.content "^//%[USAGE%] ")
37 (#offset! @injection.content 0 10 0 1)
38 (#set! injection.combined)
39 (#set! injection.language "kdl"))
41((comment) @injection.content
42 (#lua-match? @injection.content "^// %[USAGE%] ")
43 (#offset! @injection.content 0 11 0 1)
44 (#set! injection.combined)
45 (#set! injection.language "kdl"))

neovim/after/syntax/vfp.lua

Deleted
deleted file mode 100644

+0 / −276 text lines

1-- File: ~/.config/nvim/after/syntax/vfp.lua
2-- Syntax highlighting for Visual FoxPro 9.0
3
4-- Bail if syntax is already set
5if vim.b.current_syntax then return end
6
7local api = vim.api
8local fn = vim.fn
9
10-- Case-insensitive matching
11vim.opt.ignorecase = true
13-- Define VFP9 Commands (unchanged from earlier)
14local commands = {
15 'accept', 'activate', 'add', 'additive', 'after', 'again', 'aindent', 'alias', 'all', 'alt', 'alter', 'alternate',
16 'ansi', 'any', 'aplabout', 'app', 'append', 'array', 'as', 'asc', 'ascending', 'ascii', 'assert', 'asserts',
17 'assist', 'attributes', 'aused', 'automatic', 'autosave', 'average', 'avg', 'before', 'begin', 'bell', 'bitmap',
18 'blank', 'blink', 'blocksize', 'border', 'bottom', 'box', 'browse', 'brstatus', 'bucket', 'buffers', 'build', 'by',
19 'calculate', 'calcvalue', 'call', 'cancel', 'carry', 'cascade', 'catalog', 'cd', 'center', 'century', 'cga',
20 'change', 'character', 'chdir', 'check', 'classlib', 'clear', 'click', 'clock', 'close', 'cnt', 'codepage',
21 'collate', 'color', 'column', 'com1', 'com2', 'command', 'compact', 'compatible', 'compile', 'compress',
22 'confirm', 'connection', 'connections', 'connstring', 'console', 'container', 'continue', 'control', 'copies',
23 'copy', 'count', 'cpcompile', 'cpdialog', 'create', 'currency', 'cursor', 'cursorgetprop', 'cursorsetprop',
24 'cycle', 'database', 'databases', 'datasession', 'datasource', 'db4', 'dblclick', 'dbmemo3', 'dbtrap', 'dde',
25 'deactivate', 'debug', 'decimals', 'declare', 'default', 'defaultsource', 'define', 'delete', 'deletetables',
26 'delimited', 'delimiters', 'desc', 'design', 'development', 'device', 'dif', 'dimension', 'dir', 'directory',
27 'disabled', 'display', 'distinct', 'dll', 'dlls', 'do', 'dohistory', 'dos', 'dosmem', 'double', 'down', 'drag',
28 'draw', 'driver', 'duplex', 'echo', 'edit', 'editwork', 'ega25', 'ega43', 'eject', 'ems64', 'ems', 'enabled',
29 'encrypt', 'encryption', 'end', 'environment', 'erase', 'escape', 'events', 'exact', 'except', 'exclusive', 'exe',
30 'exists', 'exit', 'export', 'expression', 'extended', 'external', 'f11f12', 'fdow', 'fetch', 'fields', 'file',
31 'filer', 'fill', 'find', 'fixed', 'float', 'flush', 'foldconst', 'font', 'footer', 'for', 'force', 'foreign',
32 'form', 'format', 'formset', 'found', 'fox2x', 'foxplus', 'free', 'freeze', 'from', 'full', 'function', 'fw2',
33 'fweek', 'gather', 'general', 'get', 'getexpr', 'getnextmodified', 'getobject', 'gets', 'global', 'go', 'goto',
34 'group', 'grow', 'halfheight', 'having', 'heading', 'headings', 'height', 'help', 'helpfilter', 'hidden', 'hide',
35 'highlight', 'history', 'hmemory', 'hours', 'iblock', 'icon', 'id', 'import', 'in', 'index', 'indexes',
36 'information', 'inner', 'input', 'insert', 'instruct', 'integer', 'intensity', 'intersect', 'into', 'is',
37 'isometric', 'join', 'keyboard', 'keycolumns', 'keycomp', 'keyset', 'label', 'last', 'ldcheck', 'ledit', 'left',
38 'level', 'library', 'line', 'linked', 'list', 'load', 'local', 'locate', 'logerrors', 'long', 'loop',
39 'lparameters', 'lpartition', 'mac', 'macdesktop', 'machelp', 'mackey', 'macro', 'macros', 'margin', 'mark',
40 'master', 'maxmem', 'mblock', 'md', 'mdi', 'memlimit', 'memo', 'memos', 'memowidth', 'memvar', 'menu', 'menus',
41 'message', 'messages', 'middle', 'minimize', 'minus', 'mkdir', 'modal', 'modify', 'module', 'mono43', 'mono',
42 'mouse', 'move', 'movers', 'multilocks', 'multiselect', 'mvarsiz', 'mvcount', 'name', 'near', 'negotiate',
43 'next', 'noalias', 'noappend', 'noclear', 'noclose', 'noconsole', 'nocptrans', 'nodata', 'nodebug', 'nodelete',
44 'nodefault', 'nodup', 'noedit', 'noeject', 'noenvironment', 'nofloat', 'nofollow', 'nogrow', 'noinit', 'nolgrid',
45 'nolink', 'nolock', 'nolog', 'nomargin', 'nomdi', 'nomenu', 'nominimize', 'nomodify', 'nomouse', 'none',
46 'nooptimize', 'noorganize', 'nooverwrite', 'noprompt', 'noprojecthook', 'noread', 'norefresh', 'norequery',
47 'norgrid', 'normal', 'nosave', 'noshadow', 'noshow', 'nospace', 'notify', 'noupdate', 'novalidate', 'noverify',
48 'nowait', 'nowindow', 'nowrap', 'nozoom', 'npv', 'null', 'number', 'nvl', 'object', 'objects', 'odometer', 'of',
49 'off', 'ole', 'oleobject', 'oleobjects', 'olepublic', 'on', 'only', 'open', 'optimize', 'order', 'orientation',
50 'outer', 'output', 'outshow', 'overlay', 'overwrite', 'pack', 'page', 'palette', 'panel', 'paperlength',
51 'papersize', 'paperwidth', 'parameters', 'partition', 'password', 'path', 'pattern', 'pause', 'pdox', 'pdsetup',
52 'pen', 'percent', 'pfs', 'picture', 'pixels', 'plain', 'play', 'point', 'pop', 'popup', 'popups', 'precision',
53 'preference', 'preview', 'primary', 'printer', 'printquality', 'private', 'procedure', 'procedures', 'production',
54 'progwork', 'project', 'protected', 'public', 'push', 'query', 'quit', 'random', 'range', 'rd', 'read',
55 'readborder', 'readerror', 'recall', 'record', 'recover', 'recsize', 'redit', 'reference', 'references',
56 'refresh', 'regional', 'reindex', 'relation', 'relative', 'release', 'remote', 'remove', 'rename', 'replace',
57 'report', 'reprocess', 'required', 'resource', 'rest', 'restore', 'restrict', 'resume', 'retry', 'return',
58 'right', 'rmdir', 'rollback', 'rowset', 'rpd', 'run', 'runscript', 'runtime', 'safety', 'same', 'sample', 'save',
59 'say', 'scale', 'scatter', 'scheme', 'screen', 'screens', 'scroll', 'sdf', 'seek', 'select', 'selection',
60 'separator', 'set', 'setfldstate', 'shadows', 'shared', 'sheet', 'shell', 'shift', 'show', 'shutdown', 'single',
61 'size', 'skip', 'some', 'sort', 'sortwork', 'spinner', 'sql', 'standalone', 'status', 'std', 'step', 'sticky',
62 'store', 'stretch', 'string', 'structure', 'style', 'subclass', 'sum', 'summary', 'suspend', 'sylk', 'sysformats',
63 'sysmenu', 'sysmenus', 'system', 'tab', 'tag', 'table', 'tables', 'tabs', 'talk', 'tedit', 'textmerge', 'this',
64 'this_access', 'thisform', 'thisformset', 'timeout', 'titles', 'tmpfiles', 'to', 'top', 'topic', 'total',
65 'transaction', 'trap', 'trbetween', 'trigger', 'ttoption', 'type', 'typeahead', 'udfparms', 'union', 'unlock',
66 'up', 'update', 'use', 'userid', 'users', 'validate', 'values', 'var', 'verb', 'vga25', 'vga50', 'view', 'views',
67 'volume', 'wait', 'when', 'where', 'width', 'window', 'windows', 'with', 'wk1', 'wk3', 'wks', 'workarea', 'wp',
68 'wr1', 'wrap', 'wrk', 'xcmdfile', 'xl5', 'xls', 'zap',
69}
71-- Define VFP9 Functions (unchanged)
72local functions = {
73 'abs', 'aclass', 'acopy', 'acos', 'adatabases', 'adbobjects', 'addbs', 'adel', 'adir', 'aelement', 'aerror',
74 'afields', 'afont', 'agetclass', 'agetfileversion', 'ains', 'ainstance', 'alen', 'alias', 'alines', 'alltrim',
75 'amembers', 'amouseobj', 'anetresources', 'ansitooem', 'aprinters', 'asc', 'ascan', 'aselobj', 'asin', 'asort',
76 'asubscript', 'at', 'at_c', 'atan', 'atc', 'atcc', 'atcline', 'atline', 'atn2', 'aused', 'avcxclasses', 'avg',
77 'bar', 'barcount', 'barprompt', 'between', 'bintoc', 'bitand', 'bitclear', 'bitlshift', 'bitnot', 'bitor',
78 'bitrshift', 'bitset', 'bittest', 'bitxor', 'bof', 'candidate', 'capslock', 'cdow', 'cdx', 'ceiling', 'chr',
79 'chrsaw', 'chrtran', 'chrtranc', 'cmonth', 'cntbar', 'cntpad', 'col', 'comarray', 'comclassinfo', 'compobj',
80 'comreturnerror', 'count', 'cos', 'cpconvert', 'cpcurrent', 'cpdbf', 'createbinary', 'createobject',
81 'createobjectex', 'createoffline', 'ctobin', 'ctod', 'ctot', 'curdir', 'cursorgetprop', 'cursorsetprop',
82 'curval', 'date', 'datetime', 'day', 'dbc', 'dbf', 'dbgetprop', 'dbsetprop', 'dbused', 'ddeaborttrans',
83 'ddeadvise', 'ddeenabled', 'ddeexecute', 'ddeinitiate', 'ddelasterror', 'ddepoke', 'dderequest', 'ddesetoption',
84 'ddesetservice', 'ddesettopic', 'ddeterminate', 'defaulttext', 'deleted', 'descending', 'difference', 'directory',
85 'diskspace', 'dmy', 'dodefault', 'dow', 'drivetype', 'dropoffline', 'dtoc', 'dtor', 'dtos', 'dtot', 'empty',
86 'eof', 'error', 'evaluate', 'exp', 'fchsize', 'fclose', 'fcount', 'fcreate', 'fdate', 'feof', 'ferror', 'fflush',
87 'fgets', 'field', 'file', 'filetostr', 'filter', 'fklabel', 'fkmax', 'fldlist', 'flock', 'floor', 'fontmetric',
88 'fopen', 'for', 'forceext', 'forcepath', 'found', 'fputs', 'fread', 'fseek', 'fsize', 'ftime', 'fullpath', 'fv',
89 'fwrite', 'getbar', 'getcolor', 'getcp', 'getdir', 'getenv', 'getfile', 'getfldstate', 'getfont', 'gethost',
90 'getnextmodified', 'getobject', 'getpad', 'getpem', 'getpict', 'getprinter', 'gomonth', 'header', 'home', 'hour',
91 'idxcollate', 'iif', 'imestatus', 'indbc', 'indexseek', 'inkey', 'inlist', 'insmode', 'int', 'isalpha', 'isblank',
92 'iscolor', 'isdigit', 'isexclusive', 'isflocked', 'ishosted', 'isleadbyte', 'islower', 'ismouse', 'isnull',
93 'isreadonly', 'isrlocked', 'isupper', 'justdrive', 'justext', 'justfname', 'justpath', 'juststem', 'key',
94 'keymatch', 'lastkey', 'left', 'leftc', 'len', 'lenc', 'like', 'likec', 'lineno', 'loadpicture', 'locfile',
95 'lock', 'log', 'log10', 'lookup', 'lower', 'ltrim', 'lupdate', 'max', 'mcol', 'mdown', 'mdx', 'mdy', 'memlines',
96 'memory', 'menu', 'message', 'messagebox', 'min', 'minute', 'mline', 'mod', 'month', 'mrkbar', 'mrkpad', 'mrow',
97 'mton', 'mwindow', 'ndx', 'newobject', 'normalize', 'ntom', 'numlock', 'nvl', 'objnum', 'objtoclient', 'objvar',
98 'occurs', 'oemtoansi', 'oldval', 'on', 'order', 'os', 'pad', 'padc', 'padl', 'padr', 'parameters', 'payment',
99 'pcol', 'pcount', 'pemstatus', 'pi', 'popup', 'primary', 'printstatus', 'prmbar', 'prmpad', 'program', 'prompt',
100 'proper', 'prow', 'prtinfo', 'putfile', 'pv', 'rand', 'rat', 'ratc', 'ratline', 'rdlevel', 'readkey', 'reccount',
101 'recno', 'recsize', 'refresh', 'relation', 'replicate', 'requery', 'rgb', 'rgbscheme', 'right', 'rightc',
102 'rlock', 'round', 'row', 'rtod', 'rtrim', 'savepicture', 'scheme', 'scols', 'sec', 'seconds', 'seek', 'select',
103 'set', 'setfldstate', 'sign', 'sin', 'skpbar', 'skppad', 'soundex', 'space', 'sqlcancel', 'sqlcolumns',
104 'sqlcommit', 'sqlconnect', 'sqldisconnect', 'sqlexec', 'sqlgetprop', 'sqlmoreresults', 'sqlrollback',
105 'sqlsetprop', 'sqlstringconnect', 'sqltables', 'sqrt', 'srows', 'str', 'strconv', 'strtofile', 'strtran',
106 'stuff', 'stuffc', 'substr', 'substrc', 'sum', 'sys', 'sysmetric', 'tablerevert', 'tableupdate', 'tag',
107 'tagcount', 'tagno', 'tan', 'target', 'time', 'transform', 'trim', 'ttoc', 'ttod', 'txnlevel', 'txtwidth',
108 'type', 'unique', 'updated', 'upper', 'used', 'val', 'varread', 'vartype', 'version', 'wborder', 'wchild',
109 'wcols', 'week', 'wexist', 'wfont', 'wlast', 'wlcol', 'wlrow', 'wmaximum', 'wminimum', 'wontop', 'woutput',
110 'wparent', 'wread', 'wrows', 'wtitle', 'wvisible', 'year',
111}
113-- Define VFP9 System Variables (unchanged)
114local sysvars = {
115 '_alignment', '_asciicols', '_asciirows', '_assist', '_beautify', '_box', '_browser', '_builder', '_calcmem',
116 '_calcvalue', '_cliptext', '_converter', '_coverage', '_curobj', '_datetimeformat', '_dblclick', '_diarydate',
117 '_dos', '_fontclass', '_foxbaseclass', '_foxdoc', '_foxdragdrop', '_foxdroptarget', '_foxgraph', '_gallery',
118 '_gengraph', '_genhtml', '_genmenu', '_genpd', '_genscrn', '_genxtab', '_getexpr', '_helpwebdevonly',
119 '_helpwebdirectory', '_helpwebfiller1', '_helpwebfiller2', '_helpwebmsdnonline', '_helpwebmsfthomepage',
120 '_helpwebsearch', '_helpwebtutorial', '_helpwebvfpfaq', '_helpwebvfpfreestuff', '_helpwebvfphomepage',
121 '_helpwebvfponlinesupport', '_helpwebvfpsendfeedback', '_helpwebvsprodnews', '_include', '_indent', '_lmargin',
122 '_mac', '_mbr_appnd', '_mbr_cpart', '_mbr_delet', '_mbr_font', '_mbr_goto', '_mbr_grid', '_mbr_link', '_mbr_mode',
123 '_mbr_mvfld', '_mbr_mvprt', '_mbr_seek', '_mbr_sp100', '_mbr_sp200', '_mbr_szfld', '_mbrowse', '_mda_appnd',
124 '_mda_avg', '_mda_brow', '_mda_calc', '_mda_copy', '_mda_count', '_mda_label', '_mda_pack', '_mda_reprt',
125 '_mda_rindx', '_mda_setup', '_mda_sort', '_mda_sp100', '_mda_sp200', '_mda_sp300', '_mda_sum', '_mda_total',
126 '_mdata', '_mdiary', '_med_beaut', '_med_bldex', '_med_clear', '_med_copy', '_med_cut', '_med_cvtst',
127 '_med_exblk', '_med_find', '_med_finda', '_med_goto', '_med_insob', '_med_link', '_med_obj', '_med_paste',
128 '_med_pref', '_med_pstlk', '_med_redo', '_med_repl', '_med_repla', '_med_slcta', '_med_sp100', '_med_sp200',
129 '_med_sp300', '_med_sp400', '_med_sp500', '_med_sp600', '_med_undo', '_medit', '_mfi_clall', '_mfi_close',
130 '_mfi_export', '_mfi_import', '_mfi_new', '_mfi_open', '_mfi_pgset', '_mfi_prevu', '_mfi_print',
131 '_mfi_printonecopy', '_mfi_quit', '_mfi_revrt', '_mfi_savas', '_mfi_save', '_mfi_saveashtml', '_mfi_send',
132 '_mfi_setup', '_mfi_sp100', '_mfi_sp200', '_mfi_sp300', '_mfi_sp400', '_mfi_sysprint', '_mfile', '_mfiler',
133 '_mfirst', '_mlabel', '_mlast', '_mline', '_mmacro', '_mmb_delet', '_mmb_gener', '_mmb_gopts', '_mmb_insbr',
134 '_mmb_insrt', '_mmb_mopts', '_mmb_prevu', '_mmb_quick', '_mmb_sp100', '_mmb_sp200', '_mmb_sp300', '_mmbldr',
135 '_mouseevents', '_mouseeventsnodbl', '_mpr_beaut', '_mpr_cancl', '_mpr_compl', '_mpr_do', '_mpr_docum',
136 '_mpr_formwz', '_mpr_gener', '_mpr_graph', '_mpr_resum', '_mpr_sp100', '_mpr_sp200', '_mpr_sp300', '_mpr_suspend',
137 '_mprog', '_mproj', '_mrc_appnd', '_mrc_chnge', '_mrc_cont', '_mrc_delet', '_mrc_goto', '_mrc_locat',
138 '_mrc_recal', '_mrc_repl', '_mrc_seek', '_mrc_sp100', '_mrc_sp200', '_mrecord', '_mreport', '_mrqbe', '_mscreen',
139 '_msm_data', '_msm_edit', '_msm_file', '_msm_format', '_msm_prog', '_msm_recrd', '_msm_systm', '_msm_text',
140 '_msm_tools', '_msm_view', '_msm_windo', '_mst_about', '_mst_ascii', '_mst_calcu', '_mst_captr', '_mst_dbase',
141 '_mst_diary', '_mst_docum', '_mst_filer', '_mst_help', '_mst_hphow', '_mst_hpsch', '_mst_macro', '_mst_msdnc',
142 '_mst_msdni', '_mst_msdns', '_mst_office', '_mst_puzzl', '_mst_samp', '_mst_sp100', '_mst_sp200', '_mst_sp300',
143 '_mst_specl', '_mst_techs', '_msysmenu', '_msystem', '_mtable', '_mtb_appnd', '_mtb_cpart', '_mtb_delet',
144 '_mtb_delrc', '_mtb_goto', '_mtb_link', '_mtb_mvfld', '_mtb_mvprt', '_mtb_props', '_mtb_recal', '_mtb_sp100',
145 '_mtb_sp200', '_mtb_sp300', '_mtb_sp400', '_mtb_szfld', '_mti_callstack', '_mti_dbgout', '_mti_locals',
146 '_mti_runactivedoc', '_mti_trace', '_mti_watch', '_mtl_browser', '_mtl_coverage', '_mtl_debugger', '_mtl_gallery',
147 '_mtl_macro', '_mtl_optns', '_mtl_sp100', '_mtl_sp200', '_mtl_sp300', '_mtl_sp400', '_mtl_spell', '_mtl_wzrds',
148 '_mtools', '_mvi_toolb', '_mview', '_mwi_arran', '_mwi_clear', '_mwi_cmd', '_mwi_color', '_mwi_debug',
149 '_mwi_hide', '_mwi_hidea', '_mwi_min', '_mwi_move', '_mwi_rotat', '_mwi_showa', '_mwi_size', '_mwi_sp100',
150 '_mwi_sp200', '_mwi_toolb', '_mwi_trace', '_mwi_view', '_mwi_zoom', '_mwindow', '_mwizards', '_mwz_all',
151 '_mwz_applic', '_mwz_application', '_mwz_database', '_mwz_form', '_mwz_foxdoc', '_mwz_import', '_mwz_label',
152 '_mwz_mail', '_mwz_pivot', '_mwz_query', '_mwz_reprt', '_mwz_setup', '_mwz_table', '_mwz_upsizing',
153 '_mwz_webpublishing', '_netware', '_olebasecontrol', '_oledragdrop', '_oracle', '_padvance', '_pageno',
154 '_pbpage', '_pcolno', '_pcopies', '_pdparms', '_pdriver', '_pdsetup', '_pecode', '_peject', '_pepage', '_pform',
155 '_plength', '_plineno', '_ploffset', '_ppitch', '_pquality', '_pretext', '_pscode', '_pspacing', '_pwait',
156 '_rectclass', '_rmargin', '_runactivedoc', '_samples', '_scctext', '_screen', '_shell', '_spellchk', '_sqlserver',
157 '_startup', '_tabs', '_tally', '_text', '_throttle', '_transport', '_triggerlevel', '_unix', '_vfp', '_viewport',
158 '_webdevonly', '_webmenu', '_webmsfthomepage', '_webvfphomepage', '_webvfponlinesupport', '_windows', '_wizard',
159 '_wrap',
160}
162-- Define Highlight Groups
163local function set_highlights()
164 api.nvim_set_hl( 0, 'vfpSpecial', { link = 'Special' } )
165 api.nvim_set_hl( 0, 'vfpPreProc', { link = 'PreProc' } )
166 api.nvim_set_hl( 0, 'vfpCmd', { link = 'Statement' } )
167 api.nvim_set_hl( 0, 'vfpFunc', { link = 'Identifier' } )
168 api.nvim_set_hl( 0, 'vfpSysVar', { link = 'String' } )
169 api.nvim_set_hl( 0, 'vfpString', { link = 'String' } )
170 api.nvim_set_hl( 0, 'vfpConst', { link = 'Constant' } )
171 api.nvim_set_hl( 0, 'vfpNumber', { link = 'Number' } )
172 api.nvim_set_hl( 0, 'vfpFloat', { link = 'Float' } )
173 api.nvim_set_hl( 0, 'vfpOperator', { link = 'Operator' } )
174 api.nvim_set_hl( 0, 'vfpComment', { link = 'Comment' } )
175 api.nvim_set_hl( 0, 'vfpError', { link = 'Error' } )
176 api.nvim_set_hl( 0, 'vfpXmlFunc', { link = 'Function' } )
177 api.nvim_set_hl( 0, 'vfpOop', { link = 'Type' } )
178end
180set_highlights()
182-- Define Syntax Patterns with proper matchadd
183local function define_syntax()
184 local buf = api.nvim_get_current_buf()
185 local priority = 10 -- Standard priority for syntax matches
186 local id_base = 1000 -- Unique ID base to avoid collisions
188 -- Helper to apply matchadd with consistent args
189 local function add_match( group, pattern, pri, id )
190 fn.matchadd( group, pattern )
191 end
193 -- Special Characters
194 local specials = {
195 [[^\s*!]], '&', [[;\s*$]], [[^\s*=]], [[^\s*\\]], [[^\s*\\\\]],
196 [[^\s*?]], [[^\s*??]], [[^\s*???]], [[\<m\>\.]], [[\<this\>\.]],
197 [[\<thisform\>\.]], [[\<thisformset\>\.]],
198 }
199 for i, pat in ipairs( specials ) do
200 add_match( 'vfpSpecial', pat, priority, id_base + i )
201 end
203 -- Preprocessor Directives
204 local preprocs = {
205 [[^\s*#\s*\(if\|elif\|else\|endif\)]],
206 [[^\s*#\s*\(ifdef\|ifndef\|endif\)]],
207 [[^\s*#\s*\(define\|undef\)]],
208 [[^\s*#\s*\<region\>]], [[^\s*#\s*\<include\>]],
209 [[^\s*#\s*\<itsexpression\>]], [[^\s*#\s*\<readclauses\>]],
210 [[^\s*#\s*\<section\>]], [[^\s*#\s*\<wname\>]],
211 }
212 for i, pat in ipairs( preprocs ) do
213 add_match( 'vfpPreProc', pat, priority, id_base + 100 + i )
214 end
216 -- Commands
217 local cmd_pattern = [[\<]] .. table.concat( commands, [[\>\|\<]] ) .. [[\>]]
218 add_match( 'vfpCmd', cmd_pattern, priority, id_base + 200 )
220 -- Functions (with paren)
221 local func_pattern = [[\<]] .. table.concat( functions, [[\>\|\<]] ) .. [[\>\s*(]]
222 add_match( 'vfpFunc', func_pattern, priority, id_base + 300 )
224 -- System Variables
225 local sysvar_pattern = [[\<]] .. table.concat( sysvars, [[\>\|\<]] ) .. [[\>]]
226 add_match( 'vfpSysVar', sysvar_pattern, priority, id_base + 400 )
228 -- Strings
229 -- Strings section from define_syntax()
230 add_match( 'vfpString', [["[^"]*"]], priority, id_base + 500 ) -- Double-quoted
231 add_match( 'vfpString', [['[^']*']], priority, id_base + 501 ) -- Single-quoted
232 add_match( 'vfpString', '\\[[^\\]]*\\]', priority, id_base + 502 ) -- Bracketed
234 -- Constants
235 add_match( 'vfpConst', [[\.\(t\|f\|y\|n\|null\)\.]], priority, id_base + 600 )
236 add_match( 'vfpConst', [[\<null\>]], priority, id_base + 601 )
238 -- Numbers and Floats
239 add_match( 'vfpNumber', [[\<[0-9]\+\>]], priority, id_base + 700 )
240 add_match( 'vfpFloat', [[\<[0-9]\+\.[0-9]*\(e[-+]\=[0-9]\+\)\=\>]], priority, id_base + 701 )
241 add_match( 'vfpFloat', [[\.[0-9]\+\(e[-+]\=[0-9]\+\)\=\>]], priority, id_base + 702 )
242 add_match( 'vfpFloat', [[\<[0-9]\+e[-+]\=[0-9]\+\>]], priority, id_base + 703 )
244 -- Operators
245 local operators = {
246 [[\$]], [[%]], [[&]], [[+]], [[-]], [[->]], [[!]],
247 [[\.\(and\|not\|or\)\.]], [[\<and\>]], [[\<or\>]], [[\<not\>]],
248 [[<]], [[<=]], [[<>]], [[!=]], [[#]], [[=]], [[==]], [[>]], [[>=]], [[@]], [[\*]],
249 [[\<like\>]],
250 }
251 for i, op in ipairs( operators ) do
252 add_match( 'vfpOperator', op, priority, id_base + 800 + i )
253 end
255 -- Comments
256 add_match( 'vfpComment', [[^\s*\*.*]], priority, id_base + 900 )
257 add_match( 'vfpComment', [[&&.*]], priority, id_base + 901 )
258 add_match( 'vfpComment', [[\<note\>.*]], priority, id_base + 902 )
260 -- VFP9-Specific: XML Functions
261 local xml_functions = { 'xmltocursor', 'cursortoxml', 'xmlupdategram' }
262 local xml_pattern = [[\<]] .. table.concat( xml_functions, [[\>\|\<]] ) .. [[\>\s*(]]
263 add_match( 'vfpXmlFunc', xml_pattern, priority, id_base + 1000 )
265 -- VFP9-Specific: OOP Properties
266 add_match( 'vfpOop', [[\<thisform\>\.]], priority, id_base + 1100 )
268 -- Syntax Syncing
269 vim.cmd 'syntax sync minlines=1 maxlines=3'
270end
272-- Apply it
273define_syntax()
275-- Mark as loaded
276vim.b.current_syntax = 'vfp'

neovim/init.lua

Modified

+5 / −0 text lines

6868--[[ MY STUFF ]]
6969require 'bugabinga.options'
70require 'bugabinga.mise'
7071defer_on_naked 'bugabinga.treesitter'
7172defer_on_naked 'bugabinga.lsp'
73defer 'bugabinga.otter'
7274defer_on_naked 'bugabinga.bigfile'
75defer_on_naked 'bugabinga.file_changed'
7376defer_on_naked 'bugabinga.editorconfig'
7477defer 'bugabinga.sessions'
7578defer 'bugabinga.statusline'
8285defer 'bugabinga.terminal'
8386defer 'bugabinga.inlay'
8487defer 'bugabinga.d2'
88defer 'bugabinga.pivi'
8690-- Plugins handle deferred loading via puk.
8791-- No need to use `defer(...)`
9397defer 'bugabinga.diff'
9498require 'bugabinga.file_explorer'
9599require 'bugabinga.format'
100require 'bugabinga.image'
96101defer 'bugabinga.fuzzy_find'
97102defer 'bugabinga.jump2d'
98103defer 'bugabinga.key_preview'

neovim/justfile

Modified

+65 / −42 text lines

1set shell := ['nu', '--commands']
2
3# List available recipes.
4default:
5 @just --list
6
7# Reproduce some neovim issue
8repro:
9 nvim -u repro.lua
10
11puk:
12 nu puk.nu
13
14puke:
15 @nu puk.nu update
16 @if ( "puk.plugins.updated.nuon" | path exists ) { mv puk.plugins.updated.nuon puk.plugins.nuon }
17
18# DANGER NEVER CALL! delete all current neovim state, cache and other ephemeral data. does NOT delete the configs
19nuke:
20 rm --interactive --recursive --force (nvim "--headless" "--clean" +'lua print(vim.fn.stdpath[[data]])' +q | complete | get stderr)
21 rm --interactive --recursive --force (nvim "--headless" "--clean" +'lua print(vim.fn.stdpath[[cache]])' +q | complete | get stderr)
22 rm --interactive --recursive --force (nvim "--headless" "--clean" +'lua print(vim.fn.stdpath[[state]])' +q | complete | get stderr)
23
24# run all tests, or only the ones in the directory of file given
25test path="tests":
26 timeit { nvim --headless --noplugin -u tests/minimal_init.lua -c "PlenaryBustedDirectory {{ path }} {minimal_init = 'tests/minimal_init.lua'}" +q }
27
28# run manual tests
29test-manual:
30 nvim -c "set rtp^=." -c "luafile tests/manual/input.lua"
31
32# lint the nvim lua config code
33lint:
34 lua-language-server --check=. --checklevel=Warning
35
36# run nvim healthcheck in console
37checkhealth:
38 @nvim --headless -c "luafile print_checkhealth.lua"
39
40# run ast-grep refactoring on the neovim configuration
41refac:
42 ast-grep scan --interactive
1set shell := ['nu', '--commands']
2
3# List available recipes.
4default:
5 @just --list
6
7# Reproduce some neovim issue
8repro:
9 nvim -u repro.lua
11puk:
12 nu puk.nu
14puke:
15 @nu puk.nu update
16 @if ( "puk.plugins.updated.nuon" | path exists ) { mv --force puk.plugins.updated.nuon puk.plugins.nuon }
17 @if ( "puk.parsers.updated.nuon" | path exists ) { mv --force puk.parsers.updated.nuon puk.parsers.nuon }
19# DANGER NEVER CALL! delete all current neovim state, cache and other ephemeral data. does NOT delete the configs
20nuke:
21 rm --interactive --recursive --force (nvim "--headless" "--clean" +'lua print(vim.fn.stdpath[[data]])' +q | complete | get stderr)
22 rm --interactive --recursive --force (nvim "--headless" "--clean" +'lua print(vim.fn.stdpath[[cache]])' +q | complete | get stderr)
23 rm --interactive --recursive --force (nvim "--headless" "--clean" +'lua print(vim.fn.stdpath[[state]])' +q | complete | get stderr)
25# run all tests, or only the ones in the directory of file given
26test path="tests":
27 timeit { nvim --headless --noplugin -u tests/minimal_init.lua -c "PlenaryBustedDirectory {{ path }} {minimal_init = 'tests/minimal_init.lua', sequential = true}" +q }
29test-puk:
30 nu --no-config-file tests/puk.nu
32# drive a live neovim and mutate its files from the outside
33drive-file-changed:
34 nvim --headless --clean -l tests/drive/file_changed.lua
36# drive a real neovide window over rpc, without touching mouse or keyboard
37drive-neovide:
38 nvim --headless --clean -l tests/drive/neovide.lua
40pivi-install:
41 npm --prefix pivi ci --ignore-scripts --no-audit --no-fund
43test-pivi:
44 npm --prefix pivi test
45 just test tests/bugabinga/pivi
46 just test-pivi-input
48test-pivi-input:
49 nvim --headless --clean -l tests/drive/pivi.lua
51# run manual tests
52test-manual:
53 nvim -c "set rtp^=." -c "luafile tests/manual/input.lua"
55# lint the nvim lua config code
56lint:
57 with-env { VIMRUNTIME: (nvim --headless --clean +"lua io.stdout:write(vim.env.VIMRUNTIME)" +q | complete | get stdout) } { lua-language-server --check=. --checklevel=Warning }
59# run nvim healthcheck in console
60checkhealth:
61 @nvim --headless -c "luafile print_checkhealth.lua"
63# run ast-grep refactoring on the neovim configuration
64refac:
65 ast-grep scan --interactive

neovim/lsp/bashls.lua

Added
new file mode 100644

+5 / −0 text lines

1return {
2 cmd = { 'bash-language-server', 'start' },
3 filetypes = { 'bash', 'sh' },
4 root_markers = { '.git' },
5}

neovim/lsp/denols.lua

Modified

+3 / −3 text lines

2626 uri = uri,
2727 },
2828 }
29 local result = client.request_sync('deno/virtualTextDocument', params)
29 local result = client:request_sync('deno/virtualTextDocument', params)
3030 virtual_text_document_handler(uri, result, client)
3131end
5555 command = 'deno.cache',
5656 arguments = { {}, vim.uri_from_bufnr(bufnr) },
5757 }
58 client.request('workspace/executeCommand', params, function(err, _result, ctx)
58 client:request('workspace/executeCommand', params, function(err, _result, ctx)
5959 if err then
6060 local uri = ctx.params.arguments[2]
61 vim.api.nvim_err_writeln('cache command failed for ' .. vim.uri_to_fname(uri))
61 vim.notify('cache command failed for ' .. vim.uri_to_fname(uri), vim.log.levels.ERROR)
6262 end
6363 end, bufnr)
6464end

neovim/lsp/html.lua

Modified

+6 / −1 text lines

88 filetypes = { 'html' },
99 root_markers = { 'package.json', '.git' },
1010 init_options = {
11 provideFormatter = true,
11 provideFormatter = false,
1212 embeddedLanguages = { css = true, javascript = true },
1313 configurationSection = { 'html', 'css', 'javascript' },
1414 },
15 settings = {
16 html = {
17 validate = false,
18 },
19 },

neovim/lsp/jdtls.lua

Modified

+1 / −2 text lines

8181 } )
8282 end,
8383 filetypes = { 'java' },
84 root_markers = vim.fn.has 'nvim-0.11.3' == 1 and { root_markers1, root_markers2 }
85 or vim.list_extend( root_markers1, root_markers2 ),
84 root_markers = { root_markers1, root_markers2 },
8685 init_options = {},

neovim/lsp/lua_ls.lua

Modified

+0 / −38 text lines

11local project = require 'std.project'
2local normalize = vim.fs.normalize
3local realpath = vim.uv.fs_realpath
53return {
64 cmd = { 'lua-language-server' },
1513 hint = { enable = true, setType = true },
1614 },
1715 },
18 on_init = function ( client )
19 if client.workspace_folders then
20 local root = client.workspace_folders[1].name
21 local abs_root = assert( realpath( root ) )
22 local path = normalize( abs_root )
23 local abs_config = assert( realpath( vim.fn.stdpath 'config' ) )
24 local config_path = normalize( abs_config )
25 if path ~= config_path then
26 return
27 end
28 end
30 client.config.settings.Lua = vim.tbl_deep_extend( 'force', client.config.settings.Lua, {
31 runtime = {
32 version = 'LuaJIT',
33 path = {
34 'lua/?.lua',
35 'lua/?/init.lua',
36 },
37 },
38 diagnostics = {
39 globals = {
40 'vim',
41 'describe',
42 'it',
43 },
44 },
45 workspace = {
46 checkThirdParty = false,
47 library = {
48 vim.env.VIMRUNTIME,
49 '${3rd}/luv/library',
50 },
51 },
52 } )
53 end,

neovim/lsp/marksman.lua

Modified

+1 / −1 text lines

44return {
55 cmd = cmd,
6 filetypes = { 'markdown', 'markdown.mdx' },
6 filetypes = { 'markdown' },
77 root_markers = { '.marksman.toml', '.git' },
88}

neovim/lsp/qmlls.lua

Added
new file mode 100644

+11 / −0 text lines

1---@brief
2---
3--- Qt QML language server.
4--- Uses the same Qt 6 toolchain as Nuguland's justfile.
5
6---@type vim.lsp.Config
7return {
8 cmd = { 'qmlls' },
9 filetypes = { 'qml' },
10 root_markers = { 'justfile', 'qmldir', '.git' },
11}

neovim/lua/bugabinga/cmdline/format.lua

Modified

+2 / −1 text lines

6868 if not prompt or prompt == '' then
6969 return {}
7070 end
71 vim.validate({ prompt = { prompt, 'string' }, max_width = { max_width, 'number' } })
71 vim.validate('prompt', prompt, 'string')
72 vim.validate('max_width', max_width, 'number')
7273 local lines = {}
7374 for line in (prompt .. '\n'):gmatch('([^\n]*)\n') do
7475 table.insert(lines, line)

neovim/lua/bugabinga/cmdline/popupmenu.lua

Modified

+1 / −2 text lines

102102 row = anchor.row,
103103 col = anchor.col,
104104 style = 'minimal',
105 border = vim.g.border_style,
106105 focusable = false,
107106 zindex = 201,
108107 })
293292 on_show = on_show,
294293 on_select = on_select,
295294 on_hide = on_hide,
296}No final newline
295}

neovim/lua/bugabinga/cmdline/render.lua

Modified

+0 / −3 text lines

3838 row = screen_pos.row,
3939 col = 0,
4040 style = 'minimal',
41 border = vim.g.border_style,
4241 focusable = false,
4342 zindex = 50,
4443 } )
107106 if prompt_is_single_line and prompt_fits then
108107 local title_text = ' ' .. prompt .. ' '
109108 vim.api.nvim_win_set_config( win, {
110 border = vim.g.border_style,
111109 title = { { title_text, 'CmdlineBorderInput' } },
112110 title_pos = 'left',
113111 } )
123121 virt_lines_above = true,
124122 } )
125123 vim.api.nvim_win_set_config( win, {
126 border = vim.g.border_style,
127124 title = { { ' ', 'Normal' } },
128125 title_pos = 'left',
129126 height = #prompt_chunks + 1,

neovim/lua/bugabinga/cmdline/state.lua

Modified

+6 / −8 text lines

33local M = {}
55local function new(content, pos, firstc, prompt, indent, level)
6 vim.validate({
7 content = { content, 'table' },
8 pos = { pos, 'number' },
9 firstc = { firstc, 'string' },
10 prompt = { prompt, 'string' },
11 indent = { indent, 'number' },
12 level = { level, 'number' },
13 })
6 vim.validate('content', content, 'table')
7 vim.validate('pos', pos, 'number')
8 vim.validate('firstc', firstc, 'string')
9 vim.validate('prompt', prompt, 'string')
10 vim.validate('indent', indent, 'number')
11 vim.validate('level', level, 'number')
1412 return setmetatable({
1513 content = content,
1614 pos = pos,

neovim/lua/bugabinga/code_action.lua

Modified

+5 / −4 text lines

6363 local encoding = clients[1].offset_encoding or 'utf-16'
6464 local params = vim.lsp.util.make_range_params(0, encoding)
65 ---@cast params lsp.CodeActionParams
6566 params.context = { diagnostics = get_line_diagnostics(bufnr) }
6768 if vim.b[bufnr].bugabinga_code_action_cancel then
111112 vim.api.nvim_create_autocmd({ 'CursorHold', 'TextChanged', 'DiagnosticChanged' }, {
112113 group = group,
113 buffer = bufnr,
114 buf = bufnr,
114115 callback = function() update(bufnr) end,
115116 })
117118 vim.api.nvim_create_autocmd('InsertEnter', {
118119 group = group,
119 buffer = bufnr,
120 buf = bufnr,
120121 callback = function()
121122 vim.api.nvim_buf_clear_namespace(bufnr, NS, 0, -1)
122123 end,
125126 vim.api.nvim_create_autocmd('InsertLeave', {
126127 group = group,
127 buffer = bufnr,
128 buf = bufnr,
128129 callback = function() update(bufnr) end,
129130 })
131132 vim.api.nvim_create_autocmd('LspDetach', {
132133 group = group,
133 buffer = bufnr,
134 buf = bufnr,
134135 callback = function()
135136 vim.api.nvim_buf_clear_namespace(bufnr, NS, 0, -1)
136137 end,

neovim/lua/bugabinga/cycle.lua

Modified

+11 / −7 text lines

180180local function apply_highlights(bufnr, hl_ns, highlights)
181181 for _, h in ipairs(highlights) do
182182 if h.icon_hl then
183 local icon_end = 3
184 vim.api.nvim_buf_add_highlight(bufnr, hl_ns, h.icon_hl, h.line_idx, 0, 2)
183 vim.hl.range(bufnr, hl_ns, h.icon_hl, { h.line_idx, 0 }, { h.line_idx, 2 })
185184 end
186 vim.api.nvim_buf_add_highlight(bufnr, hl_ns, 'CycleBufferFileName', h.line_idx, h.name_start - 1, h.name_end_exclusive - 1)
185 vim.hl.range(
186 bufnr,
187 hl_ns,
188 'CycleBufferFileName',
189 { h.line_idx, h.name_start - 1 },
190 { h.line_idx, h.name_end_exclusive - 1 }
191 )
187192 end
188193end
190195local function clear_highlights()
191196 if state.hl_ns and state.popup_buf and vim.api.nvim_buf_is_valid(state.popup_buf) then
192 vim.api.nvim_buf_clear_highlight(state.popup_buf, state.hl_ns, 0, -1)
197 vim.api.nvim_buf_clear_namespace(state.popup_buf, state.hl_ns, 0, -1)
193198 end
194199end
223228 row = row,
224229 col = col,
225230 style = 'minimal',
226 border = vim.g.border_style,
227231 focusable = false,
228232 }
229233 state.popup_win = vim.api.nvim_open_win(state.popup_buf, true, opts)
260264 if state.selecting_idx < 1 then state.selecting_idx = #state.buffers
261265 elseif state.selecting_idx > #state.buffers then state.selecting_idx = 1 end
262266 if state.popup_buf and vim.api.nvim_buf_is_valid(state.popup_buf) then
263 local width = math.min(55, vim.o.columns - 4)
267 local width = math.min(55, vim.o.columns - 4)
264268 local lines, highlights = render_list(state.buffers, state.selecting_idx, width)
265269 clear_highlights()
266270 local was_modifiable = vim.bo[state.popup_buf].modifiable
272276 end
273277 end
275 local timer = vim.uv.new_timer()
279 local timer = assert(vim.uv.new_timer())
276280 timer:start(SETTLE_MS, 0, vim.schedule_wrap(function()
277281 timer:stop()
278282 timer:close()

neovim/lua/bugabinga/d2.lua

Modified

+4 / −6 text lines

8787 preview_winnr = winnr
8888 vim.api.nvim_set_option_value('number', false, { win = winnr })
8989 vim.api.nvim_set_option_value('wrap', false, { win = winnr })
90 vim.api.nvim_set_option_value('spell', false, { win = winnr })
9190end
9392local preview_toggle = function()
166165local validate = function(args)
167166 if not check_d2_binary() then return end
168 local bufnr = (args and args.bufnr) or vim.api.nvim_get_current_buf()
167 local bufnr = (args and args.buf) or vim.api.nvim_get_current_buf()
169168 local file = vim.api.nvim_buf_get_name(bufnr)
170169 if file == '' then
171170 return
255254 pattern = PREVIEW_BUF_NAME,
256255 description = 'D2 preview buffer keymaps',
257256 command = function(args)
258 local preview_buf = args.bufnr
259 map.normal { keys = '<leader>dp', command = preview_toggle, buffer = preview_buf, description = 'Toggle D2 preview' }
260 map.normal { keys = '<leader>du', command = preview_update, buffer = preview_buf, description = 'Update D2 preview' }
261 map.normal { keys = 'q', command = close_preview_window, buffer = preview_buf, description = 'Close D2 preview' }
257 map.normal { keys = '<leader>dp', command = preview_toggle, buffer = args.buf, description = 'Toggle D2 preview' }
258 map.normal { keys = '<leader>du', command = preview_update, buffer = args.buf, description = 'Update D2 preview' }
259 map.normal { keys = 'q', command = close_preview_window, buffer = args.buf, description = 'Close D2 preview' }
262260 end,

neovim/lua/bugabinga/devicons.lua

Modified

+4 / −4 text lines

11local puk = require 'std.puk'
2puk.defer('mini.icons')(function(icons)
3 icons.setup {}
4 icons.mock_nvim_web_devicons()
5end)
2local icons = puk 'mini.icons'
3
4icons.setup {}
5icons.mock_nvim_web_devicons()

neovim/lua/bugabinga/diagnostic.lua

Modified

+7 / −9 text lines

1919local diagnostic = vim.diagnostic
20diagnostic.enable(false)
22auto 'disable_diagnostic_initially' {
23 description = 'Disable Diagnostics initially, when attaching an LSP client to a buffer',
24 events = 'LspAttach',
25 command = function() diagnostic.enable(false, { bufnr = 0 }) end,
26}
2821local diagnostic_format = function(context)
2922 return string.format('%s: %s', display_name[context.severity], context.message)
3528 'DiagnosticVirtualText' .. display_name[context.severity]
3629end
31-- ERROR-only visibility: only errors render inline (underline/sign/virtual text);
32-- WARN/HINT stay hidden but remain available via H (float) and <leader>HH (quickfix)
33local error_only = { min = diagnostic.severity.ERROR }
3835diagnostic.config {
39 underline = true,
36 underline = { severity = error_only },
4037 virtual_text = {
41 severity = { min = diagnostic.severity.WARN },
38 severity = error_only,
4239 source = false,
4340 spacing = 2,
4441 prefix = '⦿ ',
5350 },
5451 update_in_insert = false,
5552 signs = {
53 severity = error_only,
5654 text = {
5755 [vim.diagnostic.severity.ERROR] = diagnostic_icons.error,
5856 [vim.diagnostic.severity.WARN] = diagnostic_icons.warn,

neovim/lua/bugabinga/editorconfig.lua

Modified

+0 / −1 text lines

2121 end
2222end
24expose_option( 'spell', tobool )
2524expose_option( 'number', tobool )
2625expose_option( 'relativenumber', tobool )
2726expose_option( 'cursorline', tobool )

neovim/lua/bugabinga/file_changed.lua

Added
new file mode 100644

+319 / −0 text lines

1-- Sane handling of files that change on disk while loaded in neovim.
2--
3-- Neovim already has `autoread` on by default, but it only ever looks at the
4-- filesystem after a shell command, after `:checktime` and on `FocusGained`
5-- ( see `:help timestamp` ). So a formatter, a git checkout or an agent can
6-- rewrite a file and neovim happily keeps showing stale text for minutes.
7--
8-- Three layers, from fastest to most reliable:
9--
10-- 1. `uv.fs_event` on the *parent directory* of every loaded file
11-- -> push notification, millisecond latency, but unreliable
12-- ( network shares, WSL interop, watcher limits ).
13-- 2. a plain repeating timer
14-- -> the floor. always works, independent of terminal focus reporting
15-- and of `updatetime`.
16-- 3. `FocusGained` and friends
17-- -> zero latency for the common "alt tab back into neovim" case.
18--
19-- All three funnel into `:checktime`, which decides nothing by itself. The
20-- actual policy lives in the `FileChangedShell` handler below.
21--
22-- Note on the directory watch: tools write files by creating a temporary file
23-- and renaming it over the target. That replaces the inode, so an `fs_event`
24-- registered on the *file* goes deaf after the first write. Watching the
25-- containing directory survives this.
27local auto = require 'std.auto'
28local uv = vim.uv
30-- reading a file again must stay undoable, also for big files.
31-- see `:help 'undoreload'`
32vim.opt.undoreload = 100000
33-- global value. plugins may still set a local one, that is their business.
34vim.opt.autoread = true
36--[[ POLICY ]]
38-- `FileChangedShell` only fires for the cases neovim can not decide on its
39-- own. A clean buffer whose file changed is reloaded silently by `autoread`
40-- and never reaches this handler.
41--
42-- Defining this autocommand suppresses the built in W11/W12/W16/E211 warnings
43-- and dialogs entirely, so it owns the whole user experience.
45--- remembers which buffers we already complained about, to not repeat
46--- ourselves on every check. keyed by buffer number.
47--- deliberately not a buffer local variable: `FileChangedShell` runs with the
48--- buffer list locked.
49---@type table<integer, string>
50local warned = {}
52local relative_name = function ( path ) return vim.fn.fnamemodify( path, ':~:.' ) end
54local warn_once = function ( buffer, reason, message )
55 if warned[buffer] == reason then return end
56 warned[buffer] = reason
57 vim.notify( message, vim.log.levels.WARN, { title = 'file changed', } )
58end
60auto 'file_changed_policy' {
61 {
62 description = 'decide what to do with a file that changed outside of neovim',
63 events = 'FileChangedShell',
64 command = function ( event )
65 local reason = vim.v.fcs_reason
66 local name = relative_name( event.file )
68 if reason == 'mode' or reason == 'time' then
69 -- permissions or timestamp only, contents are identical.
70 -- typical for version control checkouts. nothing to lose.
71 vim.v.fcs_choice = 'reload'
72 elseif reason == 'changed' then
73 -- contents differ and the buffer is clean.
74 -- 'edit' instead of 'reload' so that 'fileformat', 'fileencoding' and
75 -- 'binary' are detected again. a formatter or a `dos2unix` run may
76 -- have changed them.
77 vim.v.fcs_choice = 'edit'
78 elseif reason == 'conflict' then
79 -- changed on disk AND in the buffer. never pick a winner.
80 vim.v.fcs_choice = ''
81 warn_once( event.buf, reason,
82 ( '`%s` changed on disk **and** in the buffer.\n' ..
83 '`:DiffDisk` compare · `:e!` take disk · `:w!` take buffer' ):format( name ) )
84 elseif reason == 'deleted' then
85 -- keep the text. it may be the only copy left.
86 vim.v.fcs_choice = ''
87 warn_once( event.buf, reason, ( '`%s` is gone from disk.' ):format( name ) )
88 end
89 end,
90 },
91 {
92 description = 'report a file that was reloaded from disk',
93 events = 'FileChangedShellPost',
94 command = function ( event )
95 warned[event.buf] = nil
96 if vim.wo.diff then vim.cmd.diffupdate() end
97 vim.notify( ( 'reloaded `%s`' ):format( relative_name( event.file ) ),
98 vim.log.levels.INFO, { title = 'file changed', } )
99 end,
100 },
101 {
102 -- writing, or reading the file again ( `:e!`, `:edit` ), means buffer and
103 -- disk agree again. without this the next conflict would be swallowed by
104 -- the latch of the previous one.
105 description = 'forget complaints once the buffer is in sync again',
106 events = { 'BufWritePost', 'BufReadPost', 'BufWipeout', },
107 command = function ( event ) warned[event.buf] = nil end,
108 },
109}
111--[[ BUFFERS ]]
113--- the file a buffer is backed by, or nil if it is not a plain file buffer.
114---@param buffer integer
115---@return string? path, string? directory, string? file
116local file_of = function ( buffer )
117 if not vim.api.nvim_buf_is_valid( buffer ) then return end
118 if vim.bo[buffer].buftype ~= '' then return end
119 -- reloading these costs more than the staleness does
120 if vim.bo[buffer].filetype == 'bigfile' then return end
122 local name = vim.api.nvim_buf_get_name( buffer )
123 -- `oil://`, `fugitive://`, ... are not files
124 if name == '' or name:match '^%a[%w+.-]*://' then return end
126 local path = vim.fs.normalize( vim.fn.fnamemodify( name, ':p' ) )
127 return path, vim.fs.dirname( path ), vim.fs.basename( path )
128end
130--[[ TRIGGERS ]]
132-- Everything funnels through one debounced, quiescence gated `:checktime`.
133--
134-- The gate matters: a lot of tools truncate a file and only then write it,
135-- and on windows the gap between the two can be hundreds of milliseconds.
136-- Reading in that window loads an empty file, the cursor gets clamped to
137-- line 1, and the next read restores the contents but no longer knows where
138-- the cursor was. So wait until size and mtime of every watched file stopped
139-- moving before looking at them.
141local settle_delay = 150
142local settle_attempts = 8
144local timer = assert( uv.new_timer() )
145---@type table<string, string>?
146local previous_fingerprint = nil
147local attempt = 0
149--- size and modification time of every file a loaded buffer is backed by.
150--- The second return value marks a file that is almost certainly half written:
151--- it is empty while its buffer still holds text. Waiting for the fingerprint
152--- to stop moving does not catch this, because a truncated file sits there
153--- perfectly stable until the writer gets around to producing its bytes.
154---@return table<string, string> fingerprints, boolean half_written
155local fingerprint = function ()
156 local prints = {}
157 local half_written = false
158 for _, buffer in ipairs( vim.api.nvim_list_bufs() ) do
159 if vim.api.nvim_buf_is_loaded( buffer ) then
160 local path = file_of( buffer )
161 if path then
162 local stat = uv.fs_stat( path )
163 prints[path] = stat
164 and ( '%d:%d:%d' ):format( stat.size, stat.mtime.sec, stat.mtime.nsec )
165 or 'gone'
166 if stat and stat.size == 0 and vim.api.nvim_buf_line_count( buffer ) > 1 then
167 half_written = true
168 end
169 end
170 end
171 end
172 return prints, half_written
173end
175local settle
177local function arm ( delay )
178 timer:stop()
179 timer:start( delay, 0, vim.schedule_wrap( settle ) )
180end
182settle = function ()
183 -- the reload is postponed by neovim until it is harmless anyway, but
184 -- checking while typing or selecting only produces noise.
185 if vim.fn.getcmdwintype() ~= '' then return end -- E11
186 if vim.api.nvim_get_mode().mode ~= 'n' then return end
188 local current, half_written = fingerprint()
189 local moved = not vim.deep_equal( previous_fingerprint, current )
190 if attempt < settle_attempts and ( moved or half_written ) then
191 -- somebody is still writing. look again in a moment.
192 -- after `settle_attempts` we give up and read whatever is there: the file
193 -- may really have been emptied on purpose.
194 previous_fingerprint = current
195 attempt = attempt + 1
196 arm( settle_delay )
197 return
198 end
200 previous_fingerprint = nil
201 attempt = 0
202 pcall( vim.cmd.checktime )
203end
205local check = function ( delay )
206 previous_fingerprint = nil
207 attempt = 0
208 arm( delay )
209end
211auto 'file_changed_triggers' {
212 description = 'check timestamps whenever attention returns to neovim',
213 events = { 'FocusGained', 'BufEnter', 'TermLeave', 'TermClose', 'VimResume', 'InsertLeave', },
214 command = function () check( 50 ) end,
215}
217-- The floor. Deliberately not `CursorHold`: that event is edge triggered, it
218-- fires once per idle period and never again until the cursor moves. Sitting
219-- still and reading is exactly when an external change would be missed.
220local poll_interval = 2000
221local poll = assert( uv.new_timer() )
222poll:start( poll_interval, poll_interval, vim.schedule_wrap( function ()
223 -- do not interrupt a debounce that is already running
224 if timer:is_active() then return end
225 check( 0 )
226end ) )
228--[[ DIRECTORY WATCHERS ]]
230-- one `uv_fs_event_t` per directory, shared by all buffers in it.
231local max_directories = 64
233---@type table<string, { handle: uv.uv_fs_event_t, files: table<string, true> }>
234local watchers = {}
236--- plain lua, no `vim.*`: this also runs inside libuv callbacks.
237local basename = function ( path ) return path:match '[^/\\]*$' end
239local watch = function ( buffer )
240 local _, directory, file = file_of( buffer )
241 if not directory or not file then return end
243 local watcher = watchers[directory]
244 if watcher then
245 watcher.files[file] = true
246 return
247 end
249 if vim.tbl_count( watchers ) >= max_directories then return end
251 local handle = assert( uv.new_fs_event() )
252 local _, error_message = handle:start( directory, {}, function ( error, changed )
253 if error then return end
254 local current = watchers[directory]
255 if not current then return end
256 -- `changed` is nil on some platforms. then we can not tell which file it
257 -- was and have to check them all, which `:checktime` does anyway.
258 if changed and not current.files[basename( changed )] then return end
259 check( 100 )
260 end )
262 if error_message then
263 -- unwatchable directory ( network share, permissions, ... ).
264 -- the poll timer still covers this buffer.
265 handle:close()
266 return
267 end
269 watchers[directory] = { handle = handle, files = { [file] = true, }, }
270end
272local unwatch = function ( buffer )
273 local _, directory, file = file_of( buffer )
274 if not directory or not file then return end
276 local watcher = watchers[directory]
277 if not watcher then return end
279 watcher.files[file] = nil
280 if next( watcher.files ) == nil then
281 watcher.handle:stop()
282 watcher.handle:close()
283 watchers[directory] = nil
284 end
285end
287auto 'file_changed_watchers' {
288 {
289 description = 'watch the directory of every file backed buffer',
290 events = { 'BufReadPost', 'BufNewFile', 'BufFilePost', 'BufWritePost', },
291 command = function ( event ) watch( event.buf ) end,
292 },
293 {
294 description = 'release the directory watcher when a buffer goes away',
295 events = { 'BufWipeout', 'BufFilePre', },
296 command = function ( event ) unwatch( event.buf ) end,
297 },
298}
300-- buffers that were already loaded before this module ran
301for _, buffer in ipairs( vim.api.nvim_list_bufs() ) do
302 if vim.api.nvim_buf_is_loaded( buffer ) then watch( buffer ) end
303end
305--[[ COMMANDS ]]
307vim.api.nvim_create_user_command( 'DiffDisk', function ()
308 local filetype = vim.bo.filetype
309 vim.cmd 'vertical new'
310 vim.opt_local.buftype = 'nofile'
311 vim.opt_local.bufhidden = 'wipe'
312 vim.opt_local.swapfile = false
313 vim.cmd 'read ++edit #'
314 vim.cmd '0d_'
315 vim.bo.filetype = filetype
316 vim.cmd 'diffthis'
317 vim.cmd 'wincmd p'
318 vim.cmd 'diffthis'
319end, { desc = 'diff the current buffer against the file on disk', } )

neovim/lua/bugabinga/file_explorer.lua

Modified

+0 / −5 text lines

5454 float = {
5555 max_width = 69,
5656 min_width = 69,
57 border = vim.g.border_style,
5857 padding = 2,
5958 },
6059 -- Configuration for the floating action confirmation window
6160 confirmation = {
62 border = vim.g.border_style,
6361 },
6462 -- Configuration for the floating progress window
6563 progress = {
66 border = vim.g.border_style,
6764 },
6865 -- Configuration for the floating SSH window
6966 ssh = {
70 border = vim.g.border_style,
7167 },
7268 -- Configuration for the floating keymaps help window
7369 keymaps_help = {
74 border = vim.g.border_style,
7570 },
7671 view_options = {
7772 show_hidden = true,

neovim/lua/bugabinga/format.lua

Modified

+48 / −44 text lines

33local map = require 'std.map'
44local user_command = require 'std.user_command'
6local has_treesitter_parser = function ( _, ctx )
7 local filetype = vim.bo[ctx.buf].filetype
8 if filetype == '' then return true end
9 local language = vim.treesitter.language.get_lang( filetype )
10 local ok = pcall( vim.treesitter.get_string_parser, '', language )
11 return ok
12end
6local conform = puk 'conform'
148local format = function ( async )
15 require 'conform'.format( {
9 conform.format( {
1610 async = async,
1711 lsp_format = 'fallback',
1812 }, function ( err )
3327map.N {
3428 description = 'Format buffer',
3529 category = 'format',
36 keys = '=',
30 keys = '<leader>=',
3731 command = format_async,
4337vim.o.formatexpr = "v:lua.require'conform'.formatexpr()"
45puk.defer 'conform' ( function ( conform )
46 conform.setup {
47 formatters = {
48 injected = { condition = has_treesitter_parser },
49 sqruff = {
50 command = 'sqruff',
51 args = { 'fix', '-' },
52 stdin = true,
53 },
39conform.setup {
40 formatters = {
41 -- lenient JSON parsing so formatting repairs trailing commas instead of
42 -- refusing; applies to every repo, no biome.json needed. append_args keeps
43 -- the builtin args ($FILENAME, indent fallback) untouched
44 biome = {
45 append_args = { '--json-parse-allow-trailing-commas=true' },
5446 },
55 formatters_by_ft = {
56 toml = { 'taplo' },
57 sh = { 'shfmt' },
58 just = { 'just' },
59 go = { 'goimports', 'gofmt' },
60 kdl = { 'kdlfmt' },
61 nu = { 'nufmt' },
62 sql = { 'sqruff' },
63 d2 = { 'd2' },
64 markdown = { 'dprint', 'injected' },
65 ['markdown.mdx'] = { 'injected' },
66 html = { 'biome' },
67 javascript = { 'biome' },
68 javascriptreact = { 'biome' },
69 typescript = { 'biome' },
70 typescriptreact = { 'biome' },
71 json = { 'biome' },
72 jsonc = { 'biome' },
73 python = { 'ruff_format', 'ruff_fix', 'ruff_organize_imports' },
74 sass = { 'deno_fmt' },
75 -- Use the “_” file type to run formatters on file types that don't
76 -- have other formatters configured.
77 ['_'] = { 'trim_whitespace', 'trim_newlines' },
47 sqruff = {
48 command = 'sqruff',
49 args = { 'fix', '-' },
50 stdin = true,
7851 },
79 log_level = dbg.get() and vim.log.levels.TRACE or vim.log.levels.ERROR,
80 }
81end )
52 },
53 formatters_by_ft = {
54 toml = { 'taplo' },
55 sh = { 'shfmt' },
56 just = { 'just' },
57 go = { 'goimports', 'gofmt' },
58 zig = { 'zigfmt' },
59 ziggy = { 'ziggy' },
60 ziggy_schema = { 'ziggy_schema' },
61 kdl = { 'kdlfmt' },
62 nu = { 'nufmt' },
63 qml = { 'qmlformat' },
64 sql = { 'sqruff' },
65 d2 = { 'd2' },
66 markdown = { 'dprint', 'injected' },
67 html = { 'superhtml' },
68 shtml = { 'superhtml' },
69 superhtml = { 'superhtml' },
70 javascript = { 'biome' },
71 javascriptreact = { 'biome' },
72 typescript = { 'biome' },
73 typescriptreact = { 'biome' },
74 json = { 'biome' },
75 jsonc = { 'biome' },
76 -- jsonl must never be rewritten by a JSON formatter (one object per line)
77 jsonl = {},
78 python = { 'ruff_format', 'ruff_fix', 'ruff_organize_imports' },
79 sass = { 'deno_fmt' },
80 -- Use the “_” file type to run formatters on file types that don't
81 -- have other formatters configured.
82 ['_'] = { 'trim_whitespace', 'trim_newlines' },
83 },
84 log_level = dbg.get() and vim.log.levels.TRACE or vim.log.levels.ERROR,
85}

neovim/lua/bugabinga/fun.lua

Modified

+23 / −19 text lines

11local puk = require 'std.puk'
22local map = require 'std.map'
3local ignored = require 'std.ignored'
4local dbg = require 'std.dbg'
4-- explicit "where is my cursor" flash, on demand.
5-- pure neovim: vim.hl.range highlights linewise and clears itself after the
6-- timeout, no plugin, no leftover extmarks.
7local flash_ns = vim.api.nvim_create_namespace 'find_cursor_flash'
68map.normal {
79 description = 'Find cursor, for real!',
810 category = 'fun',
911 keys = '<leader><leader><leader>',
1012 command = function ()
11 local opts = { width = 69, delay_ms = 69, inc_ms = 42 }
12 dbg.kind( 'TRACE', 'Showing specs with {0}', opts )
13 require 'specs'.show_specs( opts )
13 local window = vim.api.nvim_get_current_win()
14 local buffer = vim.api.nvim_win_get_buf( window )
15 local row = vim.api.nvim_win_get_cursor( window )[1] - 1
16 vim.hl.range( buffer, flash_ns, 'IncSearch', { row, 0 }, { row, 0 }, {
17 regtype = 'V', -- linewise: flash the whole line regardless of column
18 timeout = 300,
19 } )
1420 end,
17puk.defer 'specs' ( function ( specs )
18 specs.setup {
19 show_jumps = false,
20 min_jump = 10,
21 popup = {
22 delay_ms = 10, -- delay before popup displays
23 inc_ms = 10, -- time increments used for fade/resize effects
24 blend = 10, -- starting blend, between 0-100 (fully transparent), see :h winblend
25 width = 10,
26 winhl = 'Cursor',
27 fader = specs.exp_fader,
28 resizer = specs.shrink_resizer,
23-- automatic cursor-trail animation on jumps, so the eye can follow a long
24-- motion to the new cursor position. this replaces specs.nvim.
25-- scroll animation is disabled on purpose: it fights fast navigation.
26puk.defer 'mini.animate' ( function ( animate )
27 animate.setup {
28 cursor = {
29 enable = true,
30 timing = animate.gen_timing.linear { duration = 100, unit = 'total' },
2931 },
30 ignore_filetypes = ignored.filetypes_kv,
31 ignore_buftypes = ignored.buftypes_kv,
32 scroll = { enable = false },
33 resize = { enable = true },
34 open = { enable = true },
35 close = { enable = true },
3236 }
3337end )

neovim/lua/bugabinga/fuzzy_find.lua

Modified

+0 / −7 text lines

5252 category = 'fuzzy'
5353 }
55 map.normal {
56 description = 'find spellsuggests',
57 command = extra.pickers.spellsuggest,
58 keys = '<leader>fz',
59 category = 'fuzzy'
60 }
6255 map.normal {
6356 description = 'find keymaps',
6457 command = extra.pickers.keymaps,

neovim/lua/bugabinga/health.lua

Modified

+3 / −5 text lines

33-- * i like to use with neovim.
44-- * plugins need.
6local programs_to_check = {}
6local executable = require 'std.executable'
8local function program_installed(name_of_executable)
9 return (vim.fn.executable(name_of_executable) ~= 0)
10end
8local programs_to_check = {}
1210local function check_program(name, name_of_executable)
1311 local display_name = name and (name .. '(' .. name_of_executable .. ')') or name_of_executable
1412 vim.health.start(display_name .. ' report')
15 if program_installed(name_of_executable) then
13 if executable(name_of_executable) then
1614 vim.health.ok(display_name .. ' found on system')
1715 else
1816 vim.health.error(display_name .. ' is not installed on the system')

neovim/lua/bugabinga/image.lua

Added
new file mode 100644

+246 / −0 text lines

1-- Modified from folke/snacks.nvim (Apache-2.0); see lua/bugabinga/image/NOTICE.
2local auto = require 'std.auto'
3local kitty = require 'bugabinga.image.kitty'
4local raster = require 'bugabinga.image.raster'
5local terminal = require 'bugabinga.image.terminal'
6local geometry = require 'bugabinga.image.geometry'
7
8local patterns = { '*.[pP][nN][gG]', '*.[jJ][pP][gG]', '*.[jJ][pP][eE][gG]', '*.[wW][eE][bB][pP]', '*.[gG][iI][fF]' }
9local buffers, resources, placements = {}, {}, {}
10local queued, measuring, suspended, exiting = false, false, false, false
11local redrawing = false
12local reconcile
14local function text(buf, message)
15 if not vim.api.nvim_buf_is_valid(buf) then return end
16 local readonly = vim.bo[buf].readonly
17 vim.bo[buf].readonly = false
18 vim.bo[buf].modifiable = true
19 local lines = message and vim.split(message:gsub('\r\n', '\n'), '\n', { plain = true }) or {}
20 vim.api.nvim_buf_set_lines(buf, 0, -1, false, lines)
21 vim.bo[buf].modified = false
22 vim.bo[buf].modifiable = false
23 vim.bo[buf].readonly = readonly
24end
26local function remove(win)
27 local placement = placements[win]
28 if placement then
29 kitty.delete(placement.image, placement.id)
30 placements[win] = nil
31 end
32end
34local function hide()
35 for win in pairs(placements) do remove(win) end
36end
38local function schedule()
39 if queued or exiting then return end
40 queued = true
41 vim.schedule(function()
42 queued = false
43 if not exiting then reconcile() end
44 end)
45end
47local function forget(resource)
48 if resource.uploaded then kitty.delete(resource.id); resource.uploaded = false end
49end
51local function refresh(invalidate)
52 if exiting or not next(buffers) then return end
53 hide()
54 if invalidate then for _, resource in pairs(resources) do forget(resource) end end
55 measuring = true
56 terminal.refresh(function(size, err)
57 if exiting then return end
58 measuring = false
59 for buf, state in pairs(buffers) do
60 if state.resource and not state.resource.failed then
61 if state.error ~= err then
62 state.error = err
63 text(buf, err and ('Image: ' .. err) or nil)
64 end
65 end
66 end
67 if size then schedule() end
68 end)
69end
71local function release(buf)
72 local state = buffers[buf]
73 if not state then return end
74 buffers[buf] = nil
75 if state.cancel then state.cancel() end
76 for win, placement in pairs(placements) do
77 if placement.buf == buf then remove(win) end
78 end
79 local resource = state.resource
80 if resource then
81 resource.references = resource.references - 1
82 if resource.references == 0 then
83 forget(resource)
84 resources[resource.key] = nil
85 end
86 end
87end
89local function response(ev)
90 local fields, message = ev.data.sequence:match('^\27_G([^;]+);(.+)')
91 local id = fields and tonumber((',' .. fields):match(',i=(%d+)'))
92 if not id or message == 'OK' then return end
93 for _, resource in pairs(resources) do
94 if resource.id == id then
95 if message:match('^ENOENT') and not resource.failed then
96 resource.uploaded = false
97 for win, placement in pairs(placements) do
98 if placement.image == id then remove(win) end
99 end
100 else
101 resource.failed = true
102 for buf, state in pairs(buffers) do
103 if state.resource == resource then state.error = message; text(buf, 'Image: ' .. message) end
104 end
105 end
106 schedule()
107 return
108 end
109 end
110end
112local function load(buf)
113 release(buf)
114 local state = {}
115 buffers[buf] = state
116 vim.bo[buf].swapfile = false
117 vim.bo[buf].readonly = true
118 vim.bo[buf].filetype = 'image'
119 text(buf, 'Loading image…')
120 if not terminal.available() then
121 state.error = 'Image viewing requires a Neovim terminal UI with Kitty graphics'
122 text(buf, state.error)
123 return
124 end
125 state.cancel = raster.prepare(vim.api.nvim_buf_get_name(buf), function(err, result)
126 if exiting or buffers[buf] ~= state or not vim.api.nvim_buf_is_valid(buf) then return end
127 state.cancel = nil
128 if err then
129 state.error = tostring(err)
130 text(buf, 'Image: ' .. state.error)
131 return
132 end
133 local resource = resources[result.key]
134 if not resource then
135 resource = vim.tbl_extend('force', result, { id = kitty.new_id(), references = 0 })
136 resources[result.key] = resource
137 end
138 resource.references = resource.references + 1
139 state.resource = resource
140 text(buf)
141 refresh(false)
142 end)
143end
145local function floating_rect(win, config)
146 local pos = vim.api.nvim_win_get_position(win)
147 local border = config.border and config.border ~= 'none' and 2 or 0
148 return { row = pos[1] + 1, col = pos[2] + 1,
149 cols = vim.api.nvim_win_get_width(win) + border, rows = vim.api.nvim_win_get_height(win) + border }
150end
152reconcile = function()
153 if not next(buffers) or suspended or measuring or not terminal.available() then return end
154 local cells = terminal.get()
155 if not cells then return end
156 local desired, floats = {}, {}
157 for _, win in ipairs(vim.api.nvim_tabpage_list_wins(0)) do
158 local config = vim.api.nvim_win_get_config(win)
159 if not config.hide and not config.external then
160 if config.relative ~= '' then
161 floats[#floats + 1] = floating_rect(win, config)
162 else
163 local buf = vim.api.nvim_win_get_buf(win)
164 local state = buffers[buf]
165 if state and state.resource and not state.error then
166 local info = vim.fn.getwininfo(win)[1]
167 local rect = geometry.rectangle(info, state.resource, cells)
168 if rect then desired[win] = { buf = buf, resource = state.resource, rect = rect } end
169 end
170 end
171 end
172 end
173 for win, wanted in pairs(desired) do
174 for _, rect in ipairs(floats) do
175 if geometry.overlaps(wanted.rect, rect) then desired[win] = nil; break end
176 end
177 end
178 for win, placement in pairs(placements) do
179 local wanted = desired[win]
180 if not wanted or placement.image ~= wanted.resource.id then remove(win) end
181 end
182 for win, wanted in pairs(desired) do
183 local resource = wanted.resource
184 if not resource.uploaded then
185 local ok, err = kitty.upload(resource.id, resource.path)
186 if not ok then
187 buffers[wanted.buf].error = tostring(err)
188 text(wanted.buf, 'Image: ' .. tostring(err))
189 remove(win)
190 break
191 end
192 resource.uploaded = true
193 end
194 local placement = placements[win]
195 if not placement then
196 placement = { id = kitty.new_id(), image = resource.id, buf = wanted.buf }
197 placements[win] = placement
198 end
199 if redrawing or not vim.deep_equal(placement.rect, wanted.rect) then
200 local ok, err = kitty.place(resource.id, placement.id, wanted.rect)
201 if ok then
202 placement.rect = wanted.rect
203 else
204 remove(win)
205 text(wanted.buf, 'Image: ' .. tostring(err))
206 end
207 end
208 end
209 local visible = {}
210 for _, placement in pairs(placements) do visible[placement.image] = true end
211 for _, resource in pairs(resources) do if not visible[resource.id] then forget(resource) end end
212 redrawing = false
213end
215local register = auto 'bugabinga_image'
216register {
217 { events = 'TermResponse', command = response },
218 { events = 'BufReadCmd', pattern = patterns, command = function(ev) load(ev.buf) end },
219 { events = 'BufWriteCmd', pattern = patterns, command = function() error('Image buffers are read-only') end },
220 { events = { 'BufUnload', 'BufWipeout' }, command = function(ev) release(ev.buf) end },
221 { events = { 'BufWinEnter', 'BufWinLeave', 'WinEnter', 'WinNew', 'WinClosed', 'WinResized', 'TabEnter',
222 'SessionLoadPost' }, command = schedule },
223 { events = 'OptionSet', pattern = { 'number', 'relativenumber', 'numberwidth', 'signcolumn', 'foldcolumn',
224 'statuscolumn', 'winbar', 'showtabline', 'laststatus', 'cmdheight' }, command = schedule },
225 { events = 'VimResized', command = function() refresh(false) end },
226 { events = { 'VimResume', 'FocusGained' }, command = function()
227 suspended = false
228 refresh(true)
229 end },
230 { events = 'VimSuspend', command = function() suspended = true; hide() end },
231 { events = 'VimLeavePre', command = function()
232 exiting = true
233 hide()
234 for buf in pairs(buffers) do release(buf) end
235 end },
236}
238local namespace = vim.api.nvim_create_namespace('bugabinga_image')
239vim.api.nvim_set_decoration_provider(namespace, {
240 on_end = function()
241 if next(buffers) then redrawing = true; schedule() end
242 end,
243})
245_G.BugabingaImage = { refresh = function() refresh(true) end }
246return BugabingaImage

neovim/lua/bugabinga/image/LICENSE

Added
new file mode 100644

+201 / −0 text lines

1 Apache License
2 Version 2.0, January 2004
3 http://www.apache.org/licenses/
4
5 TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
7 1. Definitions.
8
9 "License" shall mean the terms and conditions for use, reproduction,
10 and distribution as defined by Sections 1 through 9 of this document.
12 "Licensor" shall mean the copyright owner or entity authorized by
13 the copyright owner that is granting the License.
15 "Legal Entity" shall mean the union of the acting entity and all
16 other entities that control, are controlled by, or are under common
17 control with that entity. For the purposes of this definition,
18 "control" means (i) the power, direct or indirect, to cause the
19 direction or management of such entity, whether by contract or
20 otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 outstanding shares, or (iii) beneficial ownership of such entity.
23 "You" (or "Your") shall mean an individual or Legal Entity
24 exercising permissions granted by this License.
26 "Source" form shall mean the preferred form for making modifications,
27 including but not limited to software source code, documentation
28 source, and configuration files.
30 "Object" form shall mean any form resulting from mechanical
31 transformation or translation of a Source form, including but
32 not limited to compiled object code, generated documentation,
33 and conversions to other media types.
35 "Work" shall mean the work of authorship, whether in Source or
36 Object form, made available under the License, as indicated by a
37 copyright notice that is included in or attached to the work
38 (an example is provided in the Appendix below).
40 "Derivative Works" shall mean any work, whether in Source or Object
41 form, that is based on (or derived from) the Work and for which the
42 editorial revisions, annotations, elaborations, or other modifications
43 represent, as a whole, an original work of authorship. For the purposes
44 of this License, Derivative Works shall not include works that remain
45 separable from, or merely link (or bind by name) to the interfaces of,
46 the Work and Derivative Works thereof.
48 "Contribution" shall mean any work of authorship, including
49 the original version of the Work and any modifications or additions
50 to that Work or Derivative Works thereof, that is intentionally
51 submitted to Licensor for inclusion in the Work by the copyright owner
52 or by an individual or Legal Entity authorized to submit on behalf of
53 the copyright owner. For the purposes of this definition, "submitted"
54 means any form of electronic, verbal, or written communication sent
55 to the Licensor or its representatives, including but not limited to
56 communication on electronic mailing lists, source code control systems,
57 and issue tracking systems that are managed by, or on behalf of, the
58 Licensor for the purpose of discussing and improving the Work, but
59 excluding communication that is conspicuously marked or otherwise
60 designated in writing by the copyright owner as "Not a Contribution."
62 "Contributor" shall mean Licensor and any individual or Legal Entity
63 on behalf of whom a Contribution has been received by Licensor and
64 subsequently incorporated within the Work.
66 2. Grant of Copyright License. Subject to the terms and conditions of
67 this License, each Contributor hereby grants to You a perpetual,
68 worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 copyright license to reproduce, prepare Derivative Works of,
70 publicly display, publicly perform, sublicense, and distribute the
71 Work and such Derivative Works in Source or Object form.
73 3. Grant of Patent License. Subject to the terms and conditions of
74 this License, each Contributor hereby grants to You a perpetual,
75 worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 (except as stated in this section) patent license to make, have made,
77 use, offer to sell, sell, import, and otherwise transfer the Work,
78 where such license applies only to those patent claims licensable
79 by such Contributor that are necessarily infringed by their
80 Contribution(s) alone or by combination of their Contribution(s)
81 with the Work to which such Contribution(s) was submitted. If You
82 institute patent litigation against any entity (including a
83 cross-claim or counterclaim in a lawsuit) alleging that the Work
84 or a Contribution incorporated within the Work constitutes direct
85 or contributory patent infringement, then any patent licenses
86 granted to You under this License for that Work shall terminate
87 as of the date such litigation is filed.
89 4. Redistribution. You may reproduce and distribute copies of the
90 Work or Derivative Works thereof in any medium, with or without
91 modifications, and in Source or Object form, provided that You
92 meet the following conditions:
94 (a) You must give any other recipients of the Work or
95 Derivative Works a copy of this License; and
97 (b) You must cause any modified files to carry prominent notices
98 stating that You changed the files; and
100 (c) You must retain, in the Source form of any Derivative Works
101 that You distribute, all copyright, patent, trademark, and
102 attribution notices from the Source form of the Work,
103 excluding those notices that do not pertain to any part of
104 the Derivative Works; and
106 (d) If the Work includes a "NOTICE" text file as part of its
107 distribution, then any Derivative Works that You distribute must
108 include a readable copy of the attribution notices contained
109 within such NOTICE file, excluding those notices that do not
110 pertain to any part of the Derivative Works, in at least one
111 of the following places: within a NOTICE text file distributed
112 as part of the Derivative Works; within the Source form or
113 documentation, if provided along with the Derivative Works; or,
114 within a display generated by the Derivative Works, if and
115 wherever such third-party notices normally appear. The contents
116 of the NOTICE file are for informational purposes only and
117 do not modify the License. You may add Your own attribution
118 notices within Derivative Works that You distribute, alongside
119 or as an addendum to the NOTICE text from the Work, provided
120 that such additional attribution notices cannot be construed
121 as modifying the License.
123 You may add Your own copyright statement to Your modifications and
124 may provide additional or different license terms and conditions
125 for use, reproduction, or distribution of Your modifications, or
126 for any such Derivative Works as a whole, provided Your use,
127 reproduction, and distribution of the Work otherwise complies with
128 the conditions stated in this License.
130 5. Submission of Contributions. Unless You explicitly state otherwise,
131 any Contribution intentionally submitted for inclusion in the Work
132 by You to the Licensor shall be under the terms and conditions of
133 this License, without any additional terms or conditions.
134 Notwithstanding the above, nothing herein shall supersede or modify
135 the terms of any separate license agreement you may have executed
136 with Licensor regarding such Contributions.
138 6. Trademarks. This License does not grant permission to use the trade
139 names, trademarks, service marks, or product names of the Licensor,
140 except as required for reasonable and customary use in describing the
141 origin of the Work and reproducing the content of the NOTICE file.
143 7. Disclaimer of Warranty. Unless required by applicable law or
144 agreed to in writing, Licensor provides the Work (and each
145 Contributor provides its Contributions) on an "AS IS" BASIS,
146 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 implied, including, without limitation, any warranties or conditions
148 of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 PARTICULAR PURPOSE. You are solely responsible for determining the
150 appropriateness of using or redistributing the Work and assume any
151 risks associated with Your exercise of permissions under this License.
153 8. Limitation of Liability. In no event and under no legal theory,
154 whether in tort (including negligence), contract, or otherwise,
155 unless required by applicable law (such as deliberate and grossly
156 negligent acts) or agreed to in writing, shall any Contributor be
157 liable to You for damages, including any direct, indirect, special,
158 incidental, or consequential damages of any character arising as a
159 result of this License or out of the use or inability to use the
160 Work (including but not limited to damages for loss of goodwill,
161 work stoppage, computer failure or malfunction, or any and all
162 other commercial damages or losses), even if such Contributor
163 has been advised of the possibility of such damages.
165 9. Accepting Warranty or Additional Liability. While redistributing
166 the Work or Derivative Works thereof, You may choose to offer,
167 and charge a fee for, acceptance of support, warranty, indemnity,
168 or other liability obligations and/or rights consistent with this
169 License. However, in accepting such obligations, You may act only
170 on Your own behalf and on Your sole responsibility, not on behalf
171 of any other Contributor, and only if You agree to indemnify,
172 defend, and hold each Contributor harmless for any liability
173 incurred by, or claims asserted against, such Contributor by reason
174 of your accepting any such warranty or additional liability.
176 END OF TERMS AND CONDITIONS
178 APPENDIX: How to apply the Apache License to your work.
180 To apply the Apache License to your work, attach the following
181 boilerplate notice, with the fields enclosed by brackets "[]"
182 replaced with your own identifying information. (Don't include
183 the brackets!) The text should be enclosed in the appropriate
184 comment syntax for the file format. We also recommend that a
185 file or class name and description of purpose be included on the
186 same "printed page" as the copyright notice for easier
187 identification within third-party archives.
189 Copyright [yyyy] [name of copyright owner]
191 Licensed under the Apache License, Version 2.0 (the "License");
192 you may not use this file except in compliance with the License.
193 You may obtain a copy of the License at
195 http://www.apache.org/licenses/LICENSE-2.0
197 Unless required by applicable law or agreed to in writing, software
198 distributed under the License is distributed on an "AS IS" BASIS,
199 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 See the License for the specific language governing permissions and
201 limitations under the License.

neovim/lua/bugabinga/image/NOTICE

Added
new file mode 100644

+6 / −0 text lines

1Bugabinga image viewer includes modified code derived from folke/snacks.nvim.
2Upstream: https://github.com/folke/snacks.nvim/tree/e6fd58c82f2f3fcddd3fe81703d47d6d48fc7b9f/lua/snacks/image
3Upstream license: Apache License 2.0, reproduced in LICENSE.
4Modified files: ../image.lua, kitty.lua, raster.lua, geometry.lua, terminal.lua.
5Changes: standalone Neovim raster buffers, FFmpeg conversion, native PNG dimensions, direct Kitty transport, per-window placements, corrected geometry and lifecycle, isolated WezTerm measurements.
6Snacks configuration, UI utilities, document integrations, placeholder rendering, and general conversion pipelines are not included.

neovim/lua/bugabinga/image/README.md

Added
new file mode 100644

+43 / −0 text lines

1# Image buffers
2
3Opens local PNG, JPEG, WebP and GIF files in ordinary Neovim windows using the Kitty graphics protocol.
4PNG files are read directly.
5Other formats use FFmpeg from PATH to prepare a cached, first-frame RGBA PNG.
6No Snacks or ImageMagick dependency.
7
8## Requirements
9
10Neovim 0.12 terminal UI and a Kitty-graphics-capable terminal.
11FFmpeg is required only for non-PNG images.
12Unix cell dimensions come from the terminal's native window-size report.
13WezTerm uses its CLI and WEZTERM_PANE to obtain actual pane pixel dimensions on any OS.
14Its incomplete proportional-sizing support is handled with explicit cell rectangles and minimized cell-grid distortion.
15Missing or zero measurements produce an error instead of guessed geometry.
16Neovide and image buffers inside floating windows are outside this viewer's scope.
18## Behavior
20Images fit the text viewport without enlarging beyond their source dimensions, subject to a minimum terminal cell.
21Each window owns a separate placement; image data is shared while visible.
22Overlapping native floats temporarily hide the affected image.
23Hidden images release terminal storage; prepared raster files remain cached.
24Writes to image buffers are rejected.
26Window presentation settings live in after/ftplugin/image.lua.
27Incline's image exclusion lives in lua/bugabinga/winbar.lua.
28Neither policy is built into the renderer.
30The conversion cache is stdpath('cache')/bugabinga-image.
31Cache keys include source path, size, modification time and conversion version.
32Cache files persist without automatic size eviction.
33Conversions have a 30-second deadline, a 100-million-pixel limit and 100-MiB source/output checks.
34Large PNG uploads are streamed synchronously in bounded protocol chunks and can briefly occupy Neovim's event loop.
36Call :lua BugabingaImage.refresh() to remeasure and retransmit after an external terminal reset.
37Resize and focus/resume events refresh automatically.
38Owned terminal decoding errors are reported when the terminal forwards protocol replies.
40## Provenance
42Modified derivative of folke/snacks.nvim's image implementation.
43Upstream commit, changes and Apache-2.0 license are recorded in NOTICE and LICENSE.

neovim/lua/bugabinga/image/geometry.lua

Added
new file mode 100644

+51 / −0 text lines

1-- Modified from folke/snacks.nvim (Apache-2.0); see lua/bugabinga/image/NOTICE.
2local function rectangle(info, image, cells)
3 vim.validate('info', info, 'table')
4 vim.validate('image', image, 'table')
5 vim.validate('cells', cells, 'table')
6 local cols = info.width - info.textoff
7 local rows = info.height
8 if cols < 1 or rows < 1 then return end
9 local width_scale = math.min(1, cols * cells.cell_width / image.width)
10 local height_scale = math.min(1, rows * cells.cell_height / image.height)
11 local axis
12 if cells.explicit_size then
13 local scale = math.min(width_scale, height_scale)
14 local max_cols = math.min(cols, math.max(1, math.floor(image.width / cells.cell_width)))
15 local max_rows = math.min(rows, math.max(1, math.floor(image.height / cells.cell_height)))
16 local width = math.max(1, math.min(max_cols, math.floor(image.width * scale / cells.cell_width + 0.5)))
17 local height = math.max(1, math.min(max_rows, math.floor(image.height * scale / cells.cell_height + 0.5)))
18 local a = { cols = width,
19 rows = math.min(max_rows, math.max(1, math.floor(width * cells.cell_width * image.height
20 / image.width / cells.cell_height + 0.5))) }
21 local b = { rows = height,
22 cols = math.min(max_cols, math.max(1, math.floor(height * cells.cell_height * image.width
23 / image.height / cells.cell_width + 0.5))) }
24 local function aspect_error(candidate)
25 return math.abs(candidate.cols * cells.cell_width * image.height
26 / (candidate.rows * cells.cell_height * image.width) - 1)
27 end
28 local best = aspect_error(a) <= aspect_error(b) and a or b
29 cols, rows, axis = best.cols, best.rows, 'both'
30 elseif height_scale < width_scale then
31 axis = 'rows'
32 rows = math.max(1, math.floor(image.height * height_scale / cells.cell_height))
33 cols = math.min(cols, math.ceil(rows * cells.cell_height * image.width / image.height / cells.cell_width))
34 else
35 axis = 'cols'
36 cols = math.max(1, math.floor(image.width * width_scale / cells.cell_width))
37 rows = math.min(rows, math.ceil(cols * cells.cell_width * image.height / image.width / cells.cell_height))
38 end
39 return { row = info.winrow + (info.winbar or 0), col = info.wincol + info.textoff,
40 cols = cols, rows = rows, axis = axis }
42end
44local function overlaps(a, b)
45 vim.validate('a', a, 'table')
46 vim.validate('b', b, 'table')
47 return a.row < b.row + b.rows and b.row < a.row + a.rows
48 and a.col < b.col + b.cols and b.col < a.col + a.cols
49end
51return { rectangle = rectangle, overlaps = overlaps }

neovim/lua/bugabinga/image/kitty.lua

Added
new file mode 100644

+107 / −0 text lines

1-- Modified from folke/snacks.nvim (Apache-2.0); see lua/bugabinga/image/NOTICE.
2local MAX_ID = 0xFFFFFFFF
3local CHUNK_BYTES = 3072
4local next_image_id = tonumber(vim.fn.sha256(tostring(vim.uv.hrtime()) .. ':' .. vim.fn.getpid()):sub(1, 7), 16)
5
6local function valid_id(value, name)
7 vim.validate(name, value, 'number')
8 if value < 1 or value > MAX_ID or value % 1 ~= 0 then
9 error(name .. ' must be an integer between 1 and 4294967295')
10 end
11end
13local function send(command)
14 local ok, err = pcall(vim.api.nvim_ui_send, command)
15 if not ok then
16 return nil, err
17 end
18 return true
19end
21local function transfer_chunk(image_id, payload, first, more)
22 local fields
23 if first then
24 fields = ('a=t,f=100,t=d,i=%d,m=%d,q=1;'):format(image_id, more and 1 or 0)
25 else
26 fields = ('m=%d,q=1;'):format(more and 1 or 0)
27 end
28 return send('\27_G' .. fields .. payload .. '\27\\')
29end
31local function new_id()
32 if next_image_id == MAX_ID then
33 error('Kitty image ID space exhausted')
34 end
35 next_image_id = next_image_id + 1
36 return next_image_id
37end
39local function upload(image_id, path)
40 valid_id(image_id, 'image_id')
41 vim.validate('path', path, 'string')
42 local stat = vim.uv.fs_stat(path)
43 if not stat or stat.type ~= 'file' then
44 return nil, 'path must be a regular file'
45 end
46 local file, err = io.open(path, 'rb')
47 if not file then
48 return nil, err
49 end
50 local pending = file:read(CHUNK_BYTES)
51 if not pending then
52 file:close()
53 return nil, 'image file is empty'
54 end
55 local first = true
56 while true do
57 local current = pending
58 pending = file:read(CHUNK_BYTES)
59 local more = pending ~= nil
60 local ok, send_err = transfer_chunk(image_id, vim.base64.encode(current), first, more)
61 if not ok then
62 file:close()
63 return nil, send_err
64 end
65 first = false
66 if not more then
67 break
68 end
69 end
70 local closed, close_err = file:close()
71 if closed == nil then
72 return nil, close_err
73 end
74 return true
75end
77local function place(image_id, placement_id, rect)
78 valid_id(image_id, 'image_id')
79 valid_id(placement_id, 'placement_id')
80 vim.validate('rect', rect, 'table')
81 for _, field in ipairs({ 'row', 'col', 'cols', 'rows' }) do
82 vim.validate(field, rect[field], 'number')
83 if rect[field] < 1 or rect[field] % 1 ~= 0 then
84 error(field .. ' must be a positive integer')
85 end
86 end
87 local size = rect.axis == 'rows' and ('r=' .. rect.rows) or ('c=' .. rect.cols)
88 if rect.axis == 'both' then size = ('c=%d,r=%d'):format(rect.cols, rect.rows) end
89 local command = ('\27[s\27[%d;%dH\27_Ga=p,i=%d,p=%d,%s,C=1,q=1\27\\\27[u'):format(
90 rect.row, rect.col, image_id, placement_id, size
91 )
92 return send(command)
93end
95local function delete(image_id, placement_id)
96 valid_id(image_id, 'image_id')
97 local command
98 if placement_id ~= nil then
99 valid_id(placement_id, 'placement_id')
100 command = ('\27_Ga=d,d=i,i=%d,p=%d,q=1\27\\'):format(image_id, placement_id)
101 else
102 command = ('\27_Ga=d,d=I,i=%d,q=1\27\\'):format(image_id)
103 end
104 return send(command)
105end
107return { new_id = new_id, upload = upload, place = place, delete = delete }

neovim/lua/bugabinga/image/raster.lua

Added
new file mode 100644

+175 / −0 text lines

1-- Modified from folke/snacks.nvim (Apache-2.0); see lua/bugabinga/image/NOTICE.
2local uv = vim.uv
3
4local MAX_SOURCE_SIZE = 100 * 1024 * 1024
5local MAX_OUTPUT_SIZE = 100 * 1024 * 1024
6local MAX_PIXELS = 100000000
7
8local function stat(path)
9 local value = uv.fs_stat(path)
10 if not value or value.type ~= 'file' then
11 return nil, 'source is not a regular file'
12 end
13 if value.size > MAX_SOURCE_SIZE then
14 return nil, 'source exceeds size limit'
15 end
16 return value
17end
19local function fingerprint(path, value)
20 return table.concat({ path, value.size, value.mtime.sec, value.mtime.nsec or 0 }, '\0')
21end
23local function read_png(path)
24 local file, err = io.open(path, 'rb')
25 if not file then
26 return nil, err
27 end
28 local header = file:read(24)
29 file:close()
30 if not header or #header < 24 or header:sub(1, 8) ~= '\137PNG\r\n\26\n' then
31 return nil, 'invalid PNG signature or IHDR'
32 end
33 if header:sub(9, 12) ~= '\0\0\0\13' or header:sub(13, 16) ~= 'IHDR' then
34 return nil, 'invalid PNG IHDR'
35 end
36 local function uint32(offset)
37 local a, b, c, d = header:byte(offset, offset + 3)
38 return ((a * 256 + b) * 256 + c) * 256 + d
39 end
40 local width, height = uint32(17), uint32(21)
41 if width == 0 or height == 0 or width * height > MAX_PIXELS then
42 return nil, 'invalid PNG dimensions'
43 end
44 return width, height
45end
47local function dimensions(path)
48 vim.validate('path', path, 'string')
49 local value, err = stat(path)
50 if not value then
51 return nil, err
52 end
53 return read_png(path)
54end
56local function cache_paths(key)
57 local directory = vim.fs.joinpath(vim.fn.stdpath('cache'), 'bugabinga-image')
58 return directory, vim.fs.joinpath(directory, key .. '.png')
59end
61local function prepare(path, callback)
62 vim.validate('path', path, 'string')
63 vim.validate('callback', callback, 'function')
64 local canceled = false
65 local job
66 local partial
67 local function finish(err, result)
68 if not canceled then
69 vim.schedule(function()
70 if not canceled then
71 callback(err, result)
72 end
73 end)
74 end
75 end
76 local function cancel()
77 canceled = true
78 if job then
79 job:kill(15)
80 end
81 if partial then
82 uv.fs_unlink(partial)
83 end
84 end
85 local source, source_err = stat(path)
86 if not source then
87 finish(source_err)
88 return cancel
89 end
90 local identity = 'ffmpeg-rgba-v2\0' .. fingerprint(path, source)
91 local key = vim.fn.sha256(identity)
92 local directory, cached = cache_paths(key)
93 local function result_for(file)
94 local width, height = read_png(file)
95 local output = uv.fs_stat(file)
96 if not width or not output or output.size > MAX_OUTPUT_SIZE then
97 return nil
98 end
99 return { path = file, width = width, height = height, key = key }
100 end
101 local cached_result = result_for(cached)
102 if cached_result then
103 finish(nil, cached_result)
104 return cancel
105 end
106 local extension = path:lower():match('%.([^.]+)$')
107 if extension == 'png' then
108 local width, height = read_png(path)
109 if not width then
110 finish(height)
111 return cancel
112 end
113 finish(nil, { path = path, width = width, height = height, key = key })
114 return cancel
115 end
116 if extension ~= 'jpg' and extension ~= 'jpeg' and extension ~= 'webp' and extension ~= 'gif' then
117 finish('unsupported image format')
118 return cancel
119 end
120 local mkdir_status = vim.fn.mkdir(directory, 'p')
121 if mkdir_status ~= 1 and not uv.fs_stat(directory) then
122 finish('unable to create image cache directory')
123 return cancel
124 end
125 partial = vim.fs.joinpath(
126 directory,
127 key .. '.' .. tostring(uv.os_getpid()) .. '.' .. string.format('%.0f', uv.hrtime()) .. '.partial.png'
128 )
129 local args = { 'ffmpeg', '-nostdin', '-v', 'error', '-threads', '1', '-max_pixels', tostring(MAX_PIXELS),
130 '-i', path, '-frames:v', '1' }
131 vim.list_extend(args, { '-threads', '1', '-f', 'image2', '-vcodec', 'png', '-pix_fmt', 'rgba',
132 '-fs', tostring(MAX_OUTPUT_SIZE), '-y', partial })
133 local ok, system_job = pcall(vim.system, args, { text = true, timeout = 30000 }, function(response)
134 if canceled then
135 if partial then uv.fs_unlink(partial) end
136 return
137 end
138 job = nil
139 if response.code ~= 0 then
140 uv.fs_unlink(partial)
141 finish(response.stderr and response.stderr ~= '' and response.stderr or 'ffmpeg conversion failed')
142 return
143 end
144 local current = stat(path)
145 if not current or 'ffmpeg-rgba-v2\0' .. fingerprint(path, current) ~= identity then
146 uv.fs_unlink(partial)
147 finish('source changed during conversion')
148 return
149 end
150 local output = uv.fs_stat(partial)
151 local width, height = read_png(partial)
152 if not output or output.size > MAX_OUTPUT_SIZE or not width then
153 uv.fs_unlink(partial)
154 finish('ffmpeg produced invalid PNG')
155 return
156 end
157 local renamed, rename_err = uv.fs_rename(partial, cached)
158 if not renamed then
159 uv.fs_unlink(partial)
160 finish(rename_err or 'unable to commit image cache entry')
161 return
162 end
163 partial = nil
164 finish(nil, { path = cached, width = width, height = height, key = key })
165 end)
166 if not ok then
167 uv.fs_unlink(partial)
168 finish(system_job)
169 else
170 job = system_job
171 end
172 return cancel
173end
175return { dimensions = dimensions, prepare = prepare }

neovim/lua/bugabinga/image/terminal.lua

Added
new file mode 100644

+110 / −0 text lines

1-- Modified from folke/snacks.nvim (Apache-2.0); see lua/bugabinga/image/NOTICE.
2local metrics
3local pending
4local dirty = false
5local callbacks = {}
6
7local function available()
8 for _, ui in ipairs(vim.api.nvim_list_uis()) do
9 local channel = vim.api.nvim_get_chan_info(ui.chan)
10 if channel.client and channel.client.name == 'nvim-tui' then return true end
11 end
12 return false
13end
15local function valid(width, height)
16 return type(width) == 'number' and type(height) == 'number'
17 and width > 0 and height > 0 and width < math.huge and height < math.huge
18end
20local function ioctl_metrics()
21 local request = ({ Linux = 0x5413, OSX = 0x40087468, BSD = 0x40087468 })[jit.os]
22 if not request then return end
23 local ok, result = pcall(function()
24 local ffi = require 'ffi'
25 if not pcall(ffi.typeof, 'bugabinga_image_winsize') then
26 ffi.cdef [[
27 typedef struct { unsigned short row, col, xpixel, ypixel; } bugabinga_image_winsize;
28 int ioctl(int, unsigned long, ...);
29 ]]
30 end
31 local size = ffi.new('bugabinga_image_winsize')
32 if ffi.C.ioctl(1, request, size) ~= 0 or size.row == 0 or size.col == 0 then return end
33 if not valid(tonumber(size.xpixel), tonumber(size.ypixel)) then return end
34 return { cell_width = size.xpixel / size.col, cell_height = size.ypixel / size.row }
35 end)
36 if ok then return result end
37end
39local function decode(panes)
40 vim.validate('panes', panes, 'table')
41 for _, pane in ipairs(panes) do
42 if type(pane) == 'table' and tostring(pane.pane_id) == vim.env.WEZTERM_PANE then
43 local size = type(pane.size) == 'table' and pane.size or {}
44 if valid(size.cols, size.rows) and valid(size.pixel_width, size.pixel_height) then
45 return { cell_width = size.pixel_width / size.cols, cell_height = size.pixel_height / size.rows,
46 explicit_size = true }
47 end
48 return nil, 'WezTerm did not report valid pane pixel dimensions'
49 end
50 end
51 return nil, 'Current pane was not found in WezTerm'
52end
54local function get()
55 if not vim.env.WEZTERM_PANE then return ioctl_metrics() end
56 return metrics
57end
59local function refresh(callback)
60 vim.validate('callback', callback, 'function')
61 if not available() then
62 vim.schedule(function() callback(nil, 'Image viewing requires a Neovim terminal UI') end)
63 return
64 end
65 if not vim.env.WEZTERM_PANE then
66 local size = ioctl_metrics()
67 vim.schedule(function()
68 callback(size, not size and 'Terminal did not provide valid cell pixel dimensions' or nil)
69 end)
70 return
71 end
72 callbacks[#callbacks + 1] = callback
73 if pending then dirty = true; return end
74 local function finish(result, err)
75 vim.schedule(function()
76 pending = nil
77 local waiting = callbacks
78 callbacks = {}
79 if dirty then
80 dirty = false
81 refresh(function(size, failure)
82 for _, cb in ipairs(waiting) do cb(size, failure) end
83 end)
84 return
85 end
86 metrics = result
87 for _, cb in ipairs(waiting) do cb(result, err) end
88 end)
89 end
90 local ok, job = pcall(vim.system, { 'wezterm', 'cli', 'list', '--format', 'json' },
91 { text = true, timeout = 2000 }, vim.schedule_wrap(function(result)
92 if result.code ~= 0 then
93 finish(nil, 'Cannot measure WezTerm pane: ' .. vim.trim(result.stderr or 'command failed'))
94 return
95 end
96 local parsed, panes = pcall(vim.json.decode, result.stdout)
97 if not parsed or type(panes) ~= 'table' then
98 finish(nil, 'Invalid WezTerm pane response')
99 return
100 end
101 finish(decode(panes))
102 end))
103 if ok then
104 pending = job
105 else
106 finish(nil, tostring(job))
107 end
108end
110return { available = available, get = get, refresh = refresh, decode = decode }

neovim/lua/bugabinga/key_preview.lua

Modified

+2 / −1 text lines

5353 { mode = 'n', keys = '<Leader>d', desc = '+D2' },
5454 { mode = 'n', keys = '<Leader>x', desc = '+Neovim' },
5555 { mode = 'n', keys = '<Leader>m', desc = '+Marks' },
56 { mode = 'n', keys = '<Leader>o', desc = '+OpenCode' },
56 { mode = 'n', keys = '<Leader>p', desc = '+Pi' },
57 { mode = 'x', keys = '<Leader>p', desc = '+Pi' },
5758 { mode = 'n', keys = 'grw', desc = '+Workspace' },
5859 { mode = 'n', keys = 'grp', desc = '+Peek' },
5960 clue.gen_clues.builtin_completion(),

neovim/lua/bugabinga/lsp/attach.lua

Modified

+1 / −7 text lines

112112 keys = 'grl',
113113 command = vim.lsp.codelens.run,
114114 }
115 auto( 'lsp_codelens_refresh_' .. bufnr ) {
116 events = { 'BufEnter', 'CursorHold', 'InsertLeave' },
117 buffer = bufnr,
118 command = function()
119 vim.lsp.codelens.refresh { bufnr = bufnr }
120 end,
121 }
115 vim.lsp.codelens.enable(true, { bufnr = bufnr })
122116 end
124118 if client:supports_method 'textDocument/documentHighlight' then

neovim/lua/bugabinga/lsp/commands.lua

Modified

+12 / −28 text lines

11local user_command = require 'std.user_command'
3local function client_names( clients )
4 return vim.iter( clients )
5 :map( function( client ) return client.name end )
6 :unique()
7 :totable()
8end
9
310local restart_clients = function( opts )
411 local server = opts.args
512 if server and server ~= '' then
815 return
916 end
1017 local clients = opts.bang and vim.lsp.get_clients() or vim.lsp.get_clients { bufnr = 0 }
11 local names = {}
12 local seen = {}
13 for _, client in ipairs( clients ) do
14 if not seen[client.name] then
15 seen[client.name] = true
16 names[#names + 1] = client.name
17 end
18 end
18 local names = client_names( clients )
1919 if #names == 0 then return end
2020 vim.lsp.enable( names, false )
2121 vim.lsp.enable( names, true )
2525 nargs = '?',
2626 bang = true,
2727 complete = function()
28 local clients = vim.lsp.get_clients()
29 local seen = {}
30 local names = {}
31 for _, client in ipairs( clients ) do
32 if not seen[client.name] then
33 seen[client.name] = true
34 names[#names + 1] = client.name
35 end
36 end
37 return names
28 return client_names( vim.lsp.get_clients() )
3829 end,
3930})( restart_clients )
4132user_command.LspReload 'Reload current lsp server and buffer' ( function()
4233 local clients = vim.lsp.get_clients { bufnr = 0 }
43 local names = {}
44 local seen = {}
45 for _, client in ipairs( clients ) do
46 if not seen[client.name] then
47 seen[client.name] = true
48 names[#names + 1] = client.name
49 end
50 end
34 local names = client_names( clients )
5135 if #names == 0 then return end
5236 vim.lsp.enable( names, false )
5337 vim.lsp.enable( names, true )
7559 vim.notify( vim.inspect( client.settings ) )
7660end )
78user_command.LspInfo 'Show basic info about running LSP servers in a popup' ( function()
79 require 'bugabinga.lsp.info'.show( vim.lsp.get_clients() )
62user_command.LspInfo 'Show LSP health' ( function()
63 vim.cmd.checkhealth 'vim.lsp'
8064end )No final newline

neovim/lua/bugabinga/lsp/info.lua

Deleted
deleted file mode 100644

+0 / −106 text lines

1local icon = require 'std.icon'
2local table = require 'std.table'
3
4local cap_fields = {
5 hoverProvider = 'Hover',
6 definitionProvider = 'Go to Definition',
7 referencesProvider = 'References',
8 completionProvider = 'Completion',
9 renameProvider = 'Rename',
10 codeActionProvider = 'Code Actions',
11 documentFormattingProvider = 'Formatting',
12 documentSymbolProvider = 'Document Symbols',
13 workspaceSymbolProvider = 'Workspace Symbols',
14 inlayHintProvider = 'Inlay Hints',
15 semanticTokensProvider = 'Semantic Tokens',
16 signatureHelpProvider = 'Signature Help',
17 declarationProvider = 'Go to Declaration',
18 typeDefinitionProvider = 'Go to Type Definition',
19 implementationProvider = 'Go to Implementation',
20 documentHighlightProvider = 'Document Highlight',
21 codeLensProvider = 'Code Lens',
22 documentLinkProvider = 'Document Links',
23 foldingRangeProvider = 'Folding Range',
24 selectionRangeProvider = 'Selection Range',
25 callHierarchyProvider = 'Call Hierarchy',
26 documentRangeFormattingProvider = 'Range Formatting',
27 documentOnTypeFormattingProvider = 'On-Type Formatting',
28 diagnosticProvider = 'Pull Diagnostics',
29 executeCommandProvider = 'Execute Command',
30}
32local show = function( clients )
33 if #clients == 0 then
34 vim.notify( 'No active LSP clients', vim.log.levels.INFO )
35 return
36 end
38 local buf = vim.api.nvim_create_buf( false, true )
40 local width = math.floor( vim.o.columns * 0.8 )
41 local height = math.floor( vim.o.lines * 0.8 )
42 local row = math.floor( (vim.o.lines - height) / 2 )
43 local col = math.floor( (vim.o.columns - width) / 2 )
44 local win = vim.api.nvim_open_win( buf, true, {
45 relative = 'editor',
46 width = width,
47 height = height,
48 row = row,
49 col = col,
50 style = 'minimal',
51 border = 'rounded',
52 title = icon.lsp .. ' LSP Info',
53 title_pos = 'center',
54 } )
56 local lines = {}
57 for i, client in ipairs( clients ) do
58 if i > 1 then table.insert( lines, '' ) end
59 table.insert( lines, string.format( '# %s %s', icon.lsp, client.name ) )
61 local root = client.config.root_dir or 'No root'
62 table.insert( lines, string.format( '**Root:** %s', root ) )
64 if client.config.filetypes then
65 table.insert( lines, string.format( '**Filetypes:** %s', table.concat( client.config.filetypes, ', ' ) ) )
66 end
68 table.insert( lines, string.format( '**ID:** %d', client.id ) )
69 local cmd = client.config.cmd
70 if type( cmd ) == 'table' and cmd[1] then
71 table.insert( lines, string.format( '**Binary:** %s', cmd[1] ) )
72 end
74 if client.workspace_folders and #client.workspace_folders > 0 then
75 table.insert( lines, '**Workspace Folders:**' )
76 for _, wf in ipairs( client.workspace_folders ) do
77 table.insert( lines, string.format( ' - %s', wf.name ) )
78 end
79 end
81 local caps = client.server_capabilities
82 local cap_list = {}
83 for field, name in pairs( cap_fields ) do
84 if caps[field] then cap_list[#cap_list + 1] = name end
85 end
86 table.insert( lines, string.format( '**Capabilities (%d):**', #cap_list ) )
87 table.insert( lines, ' ' .. table.concat( cap_list, ', ' ) )
89 if client.server_info and client.server_info.version then
90 table.insert( lines, string.format( '**Version:** %s', client.server_info.version ) )
91 end
92 end
94 vim.api.nvim_buf_set_lines( buf, 0, -1, false, lines )
95 vim.api.nvim_buf_set_lines( buf, 0, -1, false, lines )
96 vim.api.nvim_set_option_value( 'filetype', 'markdown', { buf = buf } )
97 vim.api.nvim_set_option_value( 'spell', false, { win = win } )
98 vim.api.nvim_set_option_value( 'wrap', true, { win = win } )
99 vim.api.nvim_set_option_value( 'readonly', true, { buf = buf } )
100 vim.api.nvim_set_option_value( 'modifiable', false, { buf = buf } )
101 vim.keymap.set( 'n', 'q', '<cmd>close<CR>', { buffer = buf, noremap = true, silent = true } )
102 vim.keymap.set( 'n', '<Esc>', '<cmd>close<CR>', { buffer = buf, noremap = true, silent = true } )
103 vim.api.nvim_set_current_win( win )
104end
106return { show = show }No final newline

neovim/lua/bugabinga/lsp/init.lua

Modified

+4 / −10 text lines

11local dbg = require 'std.dbg'
22local icon = require 'std.icon'
3local table = require 'std.table'
54require 'bugabinga.lsp.attach'
65require 'bugabinga.lsp.commands'
7require 'bugabinga.lsp.info'
97if dbg.get() then
10 vim.lsp.set_log_level 'debug'
8 vim.lsp.log.set_level 'debug'
119end
1311vim.lsp.config( '*', {
2523 },
2624} )
28local lsp_configs = vim.api.nvim_get_runtime_file( 'lsp/*.lua', true )
29local servers = {}
30for _, path in ipairs( lsp_configs ) do
31 local server_name = vim.fn.fnamemodify( path, ':t:r' )
32 table.insert( servers, server_name )
33end
26local servers = vim.iter( vim.lsp.get_configs() )
27 :map( function ( config ) return config.name end )
28 :totable()
3529vim.lsp.enable( servers )
3731local completion_icons = {

neovim/lua/bugabinga/mise.lua

Added
new file mode 100644

+36 / −0 text lines

1local function is_mise(path)
2 vim.validate('path', path, 'string')
3 path = vim.fs.normalize(path)
4 local name = vim.fs.basename(path)
5 return name:match('^%.?mise.*%.toml$') ~= nil
6 or path:match('/%.?mise/config%.toml$') ~= nil
7 or path:match('/%.?mise/config%.[^/]+%.toml$') ~= nil
8 or path:match('/%.?mise/conf%.d/[^/]+%.toml$') ~= nil
9end
11vim.treesitter.query.add_predicate('is-mise?', function(_, _, source)
12 return type(source) == 'number' and is_mise(vim.api.nvim_buf_get_name(source))
13end, { force = true })
15vim.treesitter.query.add_directive('mise-run!', function(match, _, source, directive, metadata)
16 local id = directive[2]
17 local node = match[id][1]
18 local text = vim.treesitter.get_node_text(node, source)
19 local delimiter = (text:sub(1, 3) == '"""' or text:sub(1, 3) == "'''") and 3 or 1
20 local content = text:sub(delimiter + 1, -delimiter - 1)
21 local shebang = content:match('^\r?\n?#!([^\r\n]+)')
22 local language = 'bash'
23 if shebang then
24 local interpreter, args = shebang:match('^%s*(%S+)%s*(.*)')
25 interpreter = interpreter and interpreter:match('([^/\\]+)$')
26 if interpreter == 'env' then
27 if args:match('^%-S%s+') then args = args:gsub('^%-S%s+', '') end
28 interpreter = args:match('^(%S+)')
29 end
30 language = interpreter and (vim.treesitter.language.get_lang(interpreter) or interpreter) or ''
31 end
32 metadata['injection.language'] = language
33 metadata[id] = { offset = { 0, delimiter, 0, -delimiter } }
34end, { force = true })
36return { is_mise = is_mise }

neovim/lua/bugabinga/nugu/init.lua

Modified

+14 / −7 text lines

7878_.NonText { fg = P.content_unfocus }
7979_.Whitespace = _.NonText
8080_.SpecialKey { fg = P.error, bg = P.content_unfocus, bold = true }
81_.Visual { bg = P.content_unfocus }
82_.VisualNOS { bg = P.ui_unfocus }
83_.Search { fg = P.content_backdrop, bg = P.content_focus }
84_.IncSearch { fg = P.content_backdrop, bg = P.content_unfocus }
85_.CurSearch { fg = P.content_backdrop, bg = P.content_important_local }
81_.Visual { fg = P.content_normal, bg = P.selection_backdrop }
82_.VisualNOS = _.Visual
83_.Search { fg = P.search_foreground, bg = P.search_backdrop }
84_.CurSearch { fg = P.search_current_foreground, bg = P.search_current_backdrop, bold = true }
85_.IncSearch = _.CurSearch
8686_.QuickFixLine = _.PmenuSel
8787_.Folded = _.Conceal
209209_.BugabingaCodeActionSourceImports = _.DiagnosticHint
210210_.BugabingaCodeActionDefault = _.DiagnosticHint
212_.PiviUser { bg = P.ui_backdrop }
213_.PiviHeading { fg = P.content_important_local, bold = true }
214_.PiviTool { fg = P.content_minor }
215_.PiviError { fg = P.error }
216_.PiviCode { bg = P.ui_backdrop }
212218-- bugabinga debug viewer
213219_.DbgViewerKind = _.Title
214220_.DbgViewerTime = _.Comment
306312_['@preproc'] = _.PreProc
307313_['@property'] = _.Identifier
308314_['@punctuation'] = _.Delimiter
315_['@error'] = _.DiagnosticError
309316_['@repeat'] = _.Repeat
310317_['@storageclass'] = _.StorageClass
311318_['@string'] = _.String
372379 local opts = {}
373380 local gui = gui_palette()
374381 if group.fg then
375 opts.ctermfg = group.fg
382 opts.ctermfg = gui.cterm[group.fg] or group.fg
376383 opts.fg = gui[group.fg]
377384 end
378385 if group.bg then
379 opts.ctermbg = group.bg
386 opts.ctermbg = gui.cterm[group.bg] or group.bg
380387 opts.bg = gui[group.bg]
381388 end
382389 if group.fg and ( group.undercurl or group.underdashed or group.underdotted or group.underdouble ) then

neovim/lua/bugabinga/nugu/palette.lua

Modified

+17 / −0 text lines

1212 content_unfocus = 22,
1313 content_important_global = 12,
1414 content_important_local = 4,
15 selection_backdrop = 23,
16 search_backdrop = 24,
17 search_foreground = 25,
18 search_current_backdrop = 26,
19 search_current_foreground = 27,
1520 ui_normal = 17,
1621 ui_backdrop = 18,
1722 ui_accent = 13,
2227 ui_important_local = 14,
2328 },
2429 dark = {
30 cterm = { [23] = 60, [24] = 23, [25] = 152, [26] = 60, [27] = 255 },
2531 [0] = '#121212',
2632 [1] = '#ec6376',
2733 [2] = '#7ba1aa',
4248 [20] = '#9aabae',
4349 [21] = '#6f6f6f',
4450 [22] = '#5d5d5d',
51 [23] = '#40344f',
52 [24] = '#263c42',
53 [25] = '#b7d9df',
54 [26] = '#614879',
55 [27] = '#f3effb',
4556 },
4657 light = {
58 cterm = { [23] = 189, [24] = 152, [25] = 23, [26] = 182, [27] = 53 },
4759 [0] = '#ededed',
4860 [1] = '#bd172e',
4961 [2] = '#184e5b',
6476 [20] = '#15333b',
6577 [21] = '#5d5d5d',
6678 [22] = '#6f6f6f',
79 [23] = '#ddd2ee',
80 [24] = '#cce1e4',
81 [25] = '#184e5b',
82 [26] = '#c4addf',
83 [27] = '#30203f',
6784 },

neovim/lua/bugabinga/options/behaviour.lua

Modified

+9 / −0 text lines

2929local restore_cursor_handler = function(ev)
30 -- BufReadPost fires on every read of this buffer, not just the first one.
31 -- Reloading a file that changed on disk ( `:checktime`, 'autoread' ) reads
32 -- it again with READ_NEW and therefore triggers this too.
33 -- Restoring the last known position is a once per buffer action, so latch
34 -- it. Buffer local variables survive a reload, the buffer object stays the
35 -- same and only its lines are replaced.
36 if vim.b[ev.buf].cursor_restored then return end
37 vim.b[ev.buf].cursor_restored = true
3039 if dbg.get() then
3140 vim.notify(string.format('RCP stage1: buf=%d cursor_line=%d mark_line=%d',
3241 ev.buf, vim.fn.line('.'), vim.fn.line([['"]])), vim.log.levels.DEBUG)

neovim/lua/bugabinga/options/core.lua

Modified

+63 / −68 text lines

88vim.g.loaded_node_provider = 0
99vim.g.loaded_perl_provider = 0
11-- disable bundled vimscript runtime plugins.
12-- none of these are used, each one sources a .vim file at startup.
13-- the guard variable differs from the plugin name in several cases
14-- ( netrw needs loaded_netrwPlugin, not loaded_netrw ), so set the
15-- full set explicitly.
16for _, plugin in ipairs {
17 'gzip',
18 'matchit',
19 'matchparen',
20 'netrw',
21 'netrwPlugin',
22 'netrwSettings',
23 'netrwFileHandlers',
24 'tar',
25 'tarPlugin',
26 'zip',
27 'zipPlugin',
28 'tutor',
29 'tutor_mode_plugin',
30 'remote_plugins',
31 '2html_plugin',
32 'logipat',
33 'rrhelper',
34 'vimball',
35 'vimballPlugin',
36 'spellfile_plugin',
37} do
38 vim.g['loaded_' .. plugin] = 1
39end
41-- disable the builtin vim regex syntax engine. treesitter only.
42-- this stops per-filetype syntax/*.vim files from sourcing.
43-- consequence: any filetype without a treesitter parser gets no
44-- highlighting at all. accepted tradeoff.
45vim.cmd.syntax 'off'
47-- drop the system vim directory from the runtime and pack paths.
48-- it leaks vimscript into neovim: fzf.vim, skim.vim and package ftdetect
49-- files ( PKGBUILD, SRCINFO, ghostty ) all live here.
50vim.opt.runtimepath:remove '/usr/share/vim/vimfiles'
51vim.opt.runtimepath:remove '/usr/share/vim/vimfiles/after'
52vim.opt.packpath:remove '/usr/share/vim/vimfiles'
53vim.opt.packpath:remove '/usr/share/vim/vimfiles/after'
1155-- Disable builtin statusline of qf window
1256vim.g.qf_disable_statusline = 1
1458-- NEOVIM EDITOR OPTIONS
16-- Keep track of file changes outside of vim
17vim.opt.autoread = true
1960-- encode files in UTF-8
2061vim.opt.fileencoding = 'utf-8'
3071-- collisions.
3172vim.opt.backupdir = vim.fn.stdpath 'state' .. '/backup//'
33-- do not make a backup before writing to a file
34vim.opt.writebackup = true
36-- save a swap file after every 100 typed characters.
37vim.opt.swapfile = true
3874vim.opt.updatecount = 100
4076-- enable persistent undo. save undo history across neovim instances
4177vim.opt.undofile = true
43-- How many milliseconds must pass before neovim decides I was "idle"
44vim.opt.updatetime = 50
79-- How many milliseconds must pass before neovim decides I was "idle".
80-- Drives the swap file flush and the CursorHold event. Below ~100ms nothing
81-- feels faster to a human, but every CursorHold consumer ( lsp document
82-- highlight, code action signs ) fires another round of requests.
83vim.opt.updatetime = 150
4584-- How long to wait between key sequences in order to chain them. e.g. <LEADER>b
4685vim.opt.timeoutlen = 250
87126vim.opt.iskeyword:append '-'
89128-- Tabs and Spaces, i like 'em 2 spaces wide
90-- only insert spaces for tabs if language configuration explicitly declares so
91vim.opt.expandtab = false
92129local tab_size = 2
93130vim.opt.tabstop = tab_size
94131vim.opt.shiftwidth = tab_size
95132vim.opt.softtabstop = tab_size
96133vim.opt.shiftround = true
97-- insert whitespace type based on whitespace on previous line
98vim.opt.smarttab = true
100135vim.opt.wrap = false
101136-- wrapped lines will continue on indentation
102137vim.opt.breakindent = true
104-- do not keep distance to borders while scrolling
105vim.opt.scrolloff = 0
106vim.opt.sidescrolloff = 0
108-- try to guess indentation based on context
109vim.opt.smartindent = true
110-- Keep indentation of new lines in line with previous lines
111vim.opt.autoindent = true
139-- keep the structure of the existing indentation when copying lines.
140-- note: 'smartindent' is intentionally absent, our global treesitter
141-- 'indentexpr' overrides it anyway.
112142vim.opt.copyindent = true
114144-- open splits to the right and below
119149-- enable mouse
120150vim.opt.mouse = 'a'
121-- disable popup menu on right click
122vim.opt.mousemodel = 'popup_setpos'
124-- highlight all search matches
125vim.opt.hlsearch = true
126152-- enable smart case in searches
127153vim.opt.ignorecase = true
128154vim.opt.smartcase = true
129vim.opt.incsearch = true
130155vim.opt.showmatch = true
131vim.opt.hidden = true
133-- Show the effects of substitutions incrementally
134vim.opt.inccommand = 'nosplit'
136157-- ask me to force failed commands
137158vim.opt.confirm = true
139-- show trailing whitespace
140vim.opt.list = false
141160vim.opt.listchars = {
142161 space = icon.space,
143162 eol = icon.eol,
153172vim.opt.showcmd = false
155174-- autocomplete menu in command buffer
156vim.opt.wildmode = 'full'
157175vim.opt.wildignorecase = true
158176vim.opt.wildoptions = 'fuzzy,pum'
160-- completion popup in buffer
161vim.opt.completeopt:append 'menu'
162vim.opt.completeopt:append 'menuone'
163vim.opt.completeopt:append 'popup'
164vim.opt.completeopt:append 'noinsert'
178-- completion popup in buffer.
179-- set explicitly instead of appending to the default ( menu,popup ) to avoid
180-- relying on + duplicating defaults.
181vim.opt.completeopt = { 'menu', 'menuone', 'popup', 'noinsert' }
166-- control completion options for <c-n> and <c-p>
167vim.opt.complete:append 'kspell' -- scans spell dict, only used, when 'spell' is set
169184-- always display the signcolumn to avoid jitter
170185vim.opt.signcolumn = 'yes:2'
191206 verthoriz = '┼',
194vim.opt.winborder = 'shadow'
196-- better have no syntax highlighting than regex based, treesitter will take over later
197vim.opt.syntax = 'off'
199211-- hide output of insert completion popup in status
200212-- vim.opt.shortmess:append 'c'
203215-- truncate messages at end
204216-- vim.opt.shortmess:append 't'
206-- show cmd window to prevent jitter UI
207vim.opt.cmdheight = 1
209-- do not conceal special characters by default. ftplugin can enable this on demand.
210vim.opt.conceallevel = 0
212218-- I do not care for folding
213219vim.opt.foldenable = false
215221-- show visual indicators for lines too long
216222vim.opt.colorcolumn = { '80', '120', '140' }
218-- highlight the current line
219vim.opt.cursorline = false
221224-- pop up menu height
222225vim.opt.pumheight = 10
224-- no transparent popups and floating windows
225vim.opt.pumblend = 0
226vim.opt.winblend = 0
228-- use this in various places for consistent border style
229vim.g.border_style = {
230 { '🬷', 'FloatBorderCorner' }, -- top left
231 { '▔', 'FloatBorder' }, -- top
232 { '🬲', 'FloatBorderCorner' }, -- top right
233 { '🮈', 'FloatBorder' }, -- right
234 { '🬕', 'FloatBorderCorner' }, -- bottom right
235 { '▁', 'FloatBorder' }, -- bottom
236 { '🬨', 'FloatBorderCorner' }, -- bottom left
237 { '▍', 'FloatBorder' }, -- left
238}
227-- consistent, simple float borders everywhere ( lsp hover, pickers, my own
228-- popups ). single source of truth: the global 'winborder'. every float that
229-- does not pass an explicit border inherits this one.
230-- plain box drawing ( U+2500 ) on purpose: the sextants from "Symbols for
231-- Legacy Computing" ( U+1FBxx ) render as tofu in almost every font/frontend
232-- except wezterm, which draws them itself.
233vim.o.winborder = '┌,─,┐,│,┘,─,└,│'
240235-- hide the mode indicator in status
241236vim.opt.showmode = false

neovim/lua/bugabinga/options/filetypes.lua

Modified

+12 / −1 text lines

55 nuon = 'nu',
66 d2 = 'd2',
77 gotmpl = 'gotmpl',
8 mdx = 'markdown.mdx',
98 shtml = 'shtml',
109 superhtml = 'superhtml',
1110 tf = 'terraform',
1211 tofu = 'opentofu',
1312 tofuvars = 'opentofu-vars',
13 service = 'systemd',
14 socket = 'systemd',
15 timer = 'systemd',
16 target = 'systemd',
17 mount = 'systemd',
18 automount = 'systemd',
19 path = 'systemd',
1420 },
1521 pattern = {
22 ['.*%.container'] = 'quadlet', -- podman quadlet units
23 ['.*%.volume'] = 'quadlet',
24 ['.*%.network'] = 'quadlet',
25 ['.*%.pod'] = 'quadlet',
26 ['.*%.kube'] = 'quadlet',
1627 ['.*/%.vscode/.*%.json'] = 'json5', -- These json files frequently have comments
1728 ['.*%.tftpl'] = function(path)
1829 -- 1. Strip the '.tftpl' from the end of the path

neovim/lua/bugabinga/options/ftplugin.lua

Added
new file mode 100644

+63 / −0 text lines

1-- replace the vimscript filetype machinery with pure lua.
2--
3-- what neovim does by default:
4-- filetype on -> detection ( lua, vim.filetype )
5-- filetype plugin on -> sources $VIMRUNTIME/ftplugin/<ft>.vim ( vimscript )
6-- filetype indent on -> sources $VIMRUNTIME/indent/<ft>.vim ( vimscript )
7--
8-- we keep detection ( lua ) and kill the two vimscript loaders.
9-- this also stops our own after/ftplugin/*.lua from loading, because they
10-- ride the same builtin autocmd. so we reimplement that loader below.
12-- keep detection, drop the vimscript plugin + indent sourcing.
13vim.cmd 'filetype plugin indent off'
15-- indentation: delegate to treesitter ( pure lua ).
16-- nvim-treesitter main ships an experimental indent module + indents.scm queries.
17-- get_indent returns -1 when no parser is available, which makes neovim fall
18-- back to 'autoindent'. wrapped in pcall so a not-yet-loaded treesitter or a
19-- query error never spams indentexpr errors.
20function _G.BugabingaIndent()
21 local ok, indent = pcall( function()
22 return require( 'nvim-treesitter.indent' ).get_indent( vim.v.lnum )
23 end )
24 return ok and indent or -1
25end
26vim.o.indentexpr = 'v:lua.BugabingaIndent()'
28-- our own filetype loader, replacing the builtin vimscript one.
29-- sets commentstring from a lua table ( native gc reads vim.bo.commentstring )
30-- and sources our after/ftplugin/<ft>.lua files. mirrors neovim by splitting
31-- compound filetypes into their dotted components.
32local commentstring = require 'std.commentstring'
33local ftoptions = require 'std.ftoptions'
34local config_dir = vim.fn.stdpath 'config'
35local group = vim.api.nvim_create_augroup( 'bugabinga_ftplugin', { clear = true } )
37vim.api.nvim_create_autocmd( 'FileType', {
38 group = group,
39 desc = 'pure-lua ftplugin: commentstring + user after/ftplugin',
40 callback = function ( args )
41 for ft in vim.gsplit( args.match, '.', { plain = true } ) do
42 if ft ~= '' then
43 local cs = commentstring[ft]
44 if cs then vim.bo[args.buf].commentstring = cs end
46 -- pure-data per-ft options ( comments, define, include, path, … )
47 -- that the killed vimscript ftplugins used to set.
48 local opts = ftoptions[ft]
49 if opts then
50 for name, value in pairs( opts ) do
51 vim.bo[args.buf][name] = value
52 end
53 end
55 local file = config_dir .. '/after/ftplugin/' .. ft .. '.lua'
56 if vim.uv.fs_stat( file ) then
57 local chunk = loadfile( file )
58 if chunk then chunk() end
59 end
60 end
61 end
62 end,
63} )

neovim/lua/bugabinga/options/grep.lua

Modified

+3 / −1 text lines

1if vim.fn.executable 'rg' then
1local executable = require 'std.executable'
2
3if executable 'rg' then
24 -- use ripgrep instead of grep
35 vim.opt.grepprg = 'rg --hidden --vimgrep --no-heading --smart-case -- '
46 vim.opt.grepformat = '%f:%l:%c:%m'

neovim/lua/bugabinga/options/init.lua

Modified

+7 / −2 text lines

1-- TODO: check which options are default by now and remove them here
1-- reviewed against nvim 0.12 defaults: the options in core.lua are intentional
2-- non-defaults ( backup, undofile, confirm, smartcase, mouse=a, winborder, etc ).
3-- nothing to strip here.
24--
35-- keymaps sets leader key. needs to be early
46require 'bugabinga.options.keymaps'
57require 'bugabinga.options.filetypes'
68require 'bugabinga.options.core'
9-- ftplugin kill must load synchronously too: it disables the vimscript
10-- filetype loaders and registers our lua replacement before the first
11-- FileType event fires during startup.
12require 'bugabinga.options.ftplugin'
814-- behaviour must load synchronously so its BufReadPost autocmds are registered
915-- before the first file is loaded ( BufReadPost fires during startup, not after )
1016require 'bugabinga.options.behaviour'
1218vim.schedule( function ()
13 require 'bugabinga.options.spelling'
1419 require 'bugabinga.options.commands'
1520 require 'bugabinga.options.menus'
1621 require 'bugabinga.options.shell'

neovim/lua/bugabinga/options/neovide.lua

Modified

+31 / −3 text lines

11if vim.g.neovide then
2 -- Neovide has no bundled fallback font, unlike wezterm, which also draws
3 -- box and block glyphs itself instead of asking the font for them.
4 -- So the chain has to be spelled out, and every link earns its place:
5 -- JetBrains Mono the text, same as wezterm uses
6 -- Symbols Nerd Font Mono every `nf-*` icon in `std.icon`
7 -- Cascadia Code braille ( the spinner ) and block elements
8 -- Segoe UI Symbol ↴ ⦿ 🔭 and friends, win32 only
9 -- DejaVu Sans Mono the same job on linux
10 -- Missing families are skipped, so listing both platforms is harmless.
11 local font_size = vim.fn.hostname() == 'x230' and 11 or 13
12 vim.opt.guifont = ( '%s:h%d' ):format( table.concat( {
13 'JetBrains Mono',
14 'Symbols Nerd Font Mono',
15 'Cascadia Code',
16 'Segoe UI Symbol',
17 'DejaVu Sans Mono',
18 }, ',' ), font_size )
20 vim.opt.pumblend = 15
21 vim.opt.winblend = 15
222 vim.g.neovide_profiler = false
23 vim.g.neovide_opacity = 0.84
24 vim.g.neovide_floating_blur_amount_x = 4.0
25 vim.g.neovide_floating_blur_amount_y = 4.0
26 vim.g.neovide_floating_corner_radius = 0.42
27 vim.g.neovide_position_animation_length = 0.12
28 vim.g.neovide_scroll_animation_length = 0.2
29 vim.g.neovide_cursor_animation_length = 0.1
30 vim.g.neovide_cursor_trail_size = 0.8
31 vim.g.neovide_cursor_vfx_mode = 'railgun'
332 -- interpret all touch events as scroll events
433 vim.g.neovide_touch_deadzone = 0.0
534 -- after this timeout, start a visual selection
736 vim.g.neovide_touch_drag_timeout = 0.69
837 vim.g.neovide_padding_top = 8
938 vim.g.neovide_padding_left = 8
10 vim.g.neovide_padding_bottom = 0
11 vim.g.neovide_padding_right = 0
39 vim.g.neovide_padding_bottom = 8
40 vim.g.neovide_padding_right = 8
1241 vim.g.neovide_hide_mouse_when_typing = true
1342 vim.g.neovide_refresh_rate_idle = 5
1443 vim.g.neovide_theme = 'auto'
15 vim.g.experimental_layer_grouping = true
1644end

neovim/lua/bugabinga/options/shell.lua

Modified

+3 / −9 text lines

1if vim.fn.executable 'nu' then
1local executable = require 'std.executable'
2
3if executable 'nu' then
24 -- integrate Nushell with nvim
35 vim.opt.shell = 'nu --error-style plain --table-mode none'
46 -- flags for nu:
1719 -- NOTE: `ansi strip` removes all ansi coloring from nushell errors
1820 vim.opt.shellpipe =
1921 '| complete | get stderr stdout | str join (char nl) | ansi strip | tee { save --force --raw "%s" }'
20 -- WARN: disable the usage of temp files for shell commands
21 -- because Nu doesn't support `input redirection` which Neovim uses to send buffer content to a command:
22 -- `{shell_command} < {temp_file_with_selected_buffer_content}`
23 -- When set to `false` the stdin pipe will be used instead.
24 -- NOTE: some info about `shelltemp`: https://github.com/neovim/neovim/issues/1008
25 vim.opt.shelltemp = false
2622 vim.opt.shellxquote = ''
27 vim.opt.shellxescape = ''
28 vim.opt.shellquote = ''
2923end
3125require 'bugabinga.health'.add_dependency

neovim/lua/bugabinga/options/spelling.lua

Deleted
deleted file mode 100644

+0 / −28 text lines

1local table = require 'std.table'
2local joinpath = vim.fs.joinpath
3
4-- disable spell checking initially
5vim.opt.spell = false
6vim.opt.spelloptions:append 'camel'
7vim.opt.spellcapcheck = ''
8-- English, German, Polish and tech words
9vim.opt.spelllang:append 'en'
10vim.opt.spelllang:append 'de'
11vim.opt.spelllang:append 'pl'
12vim.opt.spelllang:append 'nerd'
13local config_dir = vim.fn.stdpath 'config'
14---@diagnostic disable-next-line: param-type-mismatch
15local spell_dir = joinpath(config_dir, 'spell')
16vim.opt.spellfile = table.concat(
17 {
18 joinpath(spell_dir, 'nerd.utf-8.add'),
19 joinpath(spell_dir, 'en.utf-8.add'),
20 joinpath(spell_dir, 'de.utf-8.add'),
21 joinpath(spell_dir, 'pl.utf-8.add'),
22 }, ',')
24-- create new spl file with:
25-- mkspell ~/.config/nvim/spell/[lang] ~/Downloads/[lang]
26-- update nerd words with
27-- vim.cmd [[ mkspell! ~/.config/nvim/spell/nerd ~/.config//nvim/spell/nerd.words ]]
28-- vim.cmd [[ mkspell! ~/.config/nvim/spell/nerd.utf-8.add ]]

neovim/lua/bugabinga/options/win32.lua

Modified

+1 / −12 text lines

66 name = 'win32yank',
77 name_of_executable = 'win32yank.exe',
88 }
9 vim.g.clipboard = {
10 name = 'win32yank-wsl',
11 copy = {
12 ['+'] = 'win32yank.exe -i --crlf',
13 ['*'] = 'win32yank.exe -i --crlf',
14 },
15 paste = {
16 ['+'] = 'win32yank.exe -o --lf',
17 ['*'] = 'win32yank.exe -o --lf',
18 },
19 cache_enabled = true,
20 }
9 vim.g.clipboard = 'win32yank'
2110end

neovim/lua/bugabinga/otter.lua

Added
new file mode 100644

+91 / −0 text lines

1local auto = require 'std.auto'
2local mise = require 'bugabinga.mise'
3local otter = require('std.puk') 'otter'
4local keeper = require 'otter.keeper'
5local pending = {}
6
7require('bugabinga.health').add_dependency { name_of_executable = 'bash-language-server' }
8
9otter.setup { extensions = { nu = 'nu', toml = 'toml', kdl = 'kdl' } }
11local function eligible(buffer)
12 if not vim.api.nvim_buf_is_loaded(buffer) or vim.bo[buffer].buftype ~= '' then return false end
13 local name = vim.api.nvim_buf_get_name(buffer)
14 if name:match('%.otter%.[^/\\]+$') then return false end
15 local ft = vim.bo[buffer].filetype
16 return ft == 'markdown' or (ft == 'toml' and mise.is_mise(name))
17end
19local function languages(buffer, parser)
20 local found, unsafe = {}, {}
21 parser:for_each_tree(function(concrete, tree)
22 local lang = tree:lang()
23 if lang == parser:lang() or not OtterConfig.extensions[lang] then return end
24 found[lang] = true
25 if vim.bo[buffer].filetype ~= 'toml' then return end
26 for _, range in ipairs(concrete:included_ranges()) do
27 local sr, sc, er, ec = unpack(range)
28 if sc > 0 then
29 local line = vim.api.nvim_buf_get_lines(buffer, sr, sr + 1, false)[1] or ''
30 local first = line:sub(sc + 1, sr == er and ec or #line)
31 if first:find('%S') then unsafe[lang] = true end
32 end
33 end
34 end)
35 for lang in pairs(unsafe) do
36 found[lang] = nil
37 end
38 return found
39end
41local function reconcile(buffer)
42 if pending[buffer] or (not eligible(buffer) and not keeper.rafts[buffer]) then return end
43 pending[buffer] = true
44 vim.schedule(function()
45 pending[buffer] = nil
46 if not eligible(buffer) then
47 if keeper.rafts[buffer] and vim.api.nvim_buf_is_valid(buffer) then
48 vim.api.nvim_buf_call(buffer, otter.deactivate)
49 end
50 return
51 end
52 local ok, parser = pcall(vim.treesitter.get_parser, buffer)
53 if not ok or not parser then return end
54 parser:parse(true)
55 local wanted = languages(buffer, parser)
56 local raft = keeper.rafts[buffer]
57 local changed = raft and raft.parser ~= parser or false
58 local prefix = vim.api.nvim_buf_get_name(buffer) .. '.otter.'
59 for lang in pairs(wanted) do
60 local generated = raft and raft.buffers[lang]
61 if not generated or not vim.api.nvim_buf_is_valid(generated)
62 or not vim.startswith(vim.api.nvim_buf_get_name(generated), prefix)
63 then
64 changed = true
65 end
66 end
67 for lang in pairs(raft and raft.buffers or {}) do
68 if not wanted[lang] then changed = true end
69 end
70 if not changed then return end
71 if raft and next(raft.buffers) then
72 pending[buffer] = true
73 vim.api.nvim_buf_call(buffer, otter.deactivate)
74 vim.schedule(function()
75 pending[buffer] = nil
76 reconcile(buffer)
77 end)
78 elseif next(wanted) then
79 vim.api.nvim_buf_call(buffer, function() otter.activate(vim.tbl_keys(wanted)) end)
80 end
81 end)
82end
84auto 'otter_embedded_languages' {
85 events = { 'FileType', 'BufEnter', 'BufFilePost', 'TextChanged', 'TextChangedI', 'TextChangedP', 'InsertLeave' },
86 command = function(args) reconcile(args.buf) end,
87}
89for _, buffer in ipairs(vim.api.nvim_list_bufs()) do
90 reconcile(buffer)
91end

neovim/lua/bugabinga/pivi/auth.lua

Added
new file mode 100644

+244 / −0 text lines

1local view = require 'bugabinga.pivi.view'
2
3local panel
4
5local function info(message)
6 vim.notify(message, vim.log.levels.INFO, { title = 'pivi' })
7end
8
9local function fail(message)
10 vim.notify(tostring(message), vim.log.levels.ERROR, { title = 'pivi' })
11end
13local function draw()
14 if not panel or not vim.api.nvim_win_is_valid(panel.window) then return end
15 local hints = {}
16 if panel.url then hints[#hints + 1] = 'o open browser' end
17 if panel.url then hints[#hints + 1] = 'y copy ' .. (panel.code and 'code' or 'link') end
18 if panel.manual then hints[#hints + 1] = 'p paste code' end
19 hints[#hints + 1] = 'q cancel'
20 local lines = { '# Sign in · ' .. panel.title, '' }
21 vim.list_extend(lines, panel.body)
22 vim.list_extend(lines, { panel.progress, '', table.concat(hints, ' ') })
23 local buffer = vim.api.nvim_win_get_buf(panel.window)
24 vim.bo[buffer].modifiable = true
25 vim.api.nvim_buf_set_lines(buffer, 0, -1, false, lines)
26 vim.bo[buffer].modifiable = false
27 local height = vim.api.nvim_win_text_height(panel.window, {}).all
28 vim.api.nvim_win_set_height(panel.window, math.max(1, math.min(height, vim.o.lines - 6)))
29end
31local function browse()
32 local _, failure = vim.ui.open(panel.url)
33 if failure then table.insert(panel.body, 'No browser could be opened. Open the link yourself.') end
34end
36local function copy()
37 vim.fn.setreg('"', panel.code or panel.url)
38 pcall(vim.fn.setreg, '+', panel.code or panel.url)
39 info(panel.code and 'Code copied.' or 'Link copied.')
40end
42local function show(event)
43 local body = panel.body
44 if event.type == 'progress' then
45 panel.progress = event.message
46 elseif event.type == 'info' then
47 body[#body + 1] = event.message
48 for _, link in ipairs(event.links or {}) do
49 body[#body + 1] = (link.label and link.label .. ': ' or '') .. link.url
50 panel.url = panel.url or link.url
51 end
52 body[#body + 1] = ''
53 elseif event.type == 'auth_url' then
54 panel.url, panel.progress = event.url, 'Waiting for the browser…'
55 vim.list_extend(body, { event.instructions or 'Finish signing in in your browser.', '', event.url, '' })
56 browse()
57 elseif event.type == 'device_code' then
58 panel.url, panel.code, panel.progress = event.verificationUri, event.userCode, 'Waiting for the browser…'
59 vim.list_extend(
60 body,
61 { 'Enter this code in your browser:', '', ' ' .. event.userCode, '', event.verificationUri, '' }
62 )
63 copy()
64 browse()
65 end
66 draw()
67end
69local function ask(state, id, prompt)
70 local function answer(value)
71 if value == nil or value == '' then
72 state.transport.reply(id, false, 'Sign-in cancelled.')
73 else
74 state.transport.reply(id, true, value)
75 end
76 end
77 local message = prompt.message .. (prompt.placeholder and ' (' .. prompt.placeholder .. ')' or '') .. ': '
78 if prompt.type == 'manual_code' and panel then
79 panel.manual = { id = id, message = message, answer = answer }
80 draw()
81 elseif prompt.type == 'select' then
82 local format = function(option)
83 return option.description and option.label .. ' · ' .. option.description or option.label
84 end
85 vim.ui.select(
86 prompt.options,
87 { prompt = prompt.message, format_item = format },
88 function(option)
89 answer(option and option.id)
90 end
91 )
92 elseif prompt.type == 'secret' then
93 vim.schedule(function() answer(vim.fn.inputsecret(message)) end)
94 else
95 vim.ui.input({ prompt = message }, answer)
96 end
97end
99local function paste()
100 local manual = panel.manual
101 if not manual then return end
102 vim.ui.input({ prompt = manual.message }, function(value)
103 if not value or value == '' or not panel or panel.manual ~= manual then return end
104 panel.manual = nil
105 manual.answer(value)
106 draw()
107 end)
108end
110local function receive(state, record)
111 if record.type == 'prompt' then
112 ask(state, record.id, record.prompt)
113 elseif record.type == 'auth' and panel then
114 show(record.event)
115 elseif record.type == 'cancel' and panel and panel.manual and panel.manual.id == record.id then
116 panel.manual = nil
117 draw()
118 end
119end
121local function start(state, provider, method, done)
122 local window = view.float('sign-in', { '' }, 'pivi sign in')
123 local cancelled = false
124 local function cancel()
125 if cancelled or not panel then return end
126 cancelled = true
127 state.transport.request('cancel', nil, function() end)
128 end
129 local progress = method.type == 'api_key' and 'Waiting for the API key…' or 'Starting…'
130 panel = { window = window, title = provider.name, body = {}, progress = progress }
131 local function key(lhs, action, needs_link)
132 vim.keymap.set('n', lhs, function()
133 if not panel or (needs_link and not panel.url) then return end
134 action()
135 draw()
136 end, { buffer = 0, nowait = true })
137 end
138 key('o', browse, true)
139 key('y', copy, true)
140 key('p', paste)
141 key('q', cancel)
142 key('<Esc>', cancel)
143 vim.api.nvim_create_autocmd('WinClosed', { pattern = tostring(window), once = true, callback = cancel })
144 draw()
145 state.transport.request('login', { provider = provider.id, method = method.type }, function(ok, failure)
146 panel = nil
147 if vim.api.nvim_win_is_valid(window) then vim.api.nvim_win_close(window, true) end
148 if ok then
149 info('Signed in to ' .. provider.name .. '.')
150 done(provider)
151 elseif cancelled then
152 info('Sign-in cancelled.')
153 else
154 fail(failure)
155 end
156 end)
157end
159local function providers(state, done)
160 state.transport.request('providers', nil, function(ok, list)
161 if ok then
162 done(list)
163 else
164 fail(list)
165 end
166 end)
167end
169local function rank(provider)
170 return provider.stored and 1 or provider.source and 2 or 3
171end
173local function describe(provider)
174 local status = provider.stored and 'signed in · ' .. (provider.stored == 'oauth' and 'account' or 'API key')
175 or provider.source and 'ready · ' .. provider.source
176 or 'not set up'
177 return ('%s %-30s %s'):format(({ '●', '◐', '○' })[rank(provider)], provider.name, status)
178end
180local function login(state, id, done)
181 if panel then
182 fail('A sign-in is already in progress.')
183 return
184 end
185 providers(state, function(list)
186 local function with(provider)
187 if not provider then return end
188 local methods = provider.methods
189 if #methods == 1 then
190 start(state, provider, methods[1], done)
191 return
192 end
193 local format = function(method)
194 return (method.type == 'oauth' and 'Account · ' or 'API key · ') .. method.label
195 end
196 vim.ui.select(
197 methods,
198 { prompt = 'Sign in to ' .. provider.name .. ' with', format_item = format },
199 function(method)
200 if method then start(state, provider, method, done) end
201 end
202 )
203 end
204 list = vim.tbl_filter(function(provider) return #provider.methods > 0 end, list)
205 if id ~= '' then
206 local provider = vim.iter(list):find(function(item) return item.id == id end)
207 if not provider then fail('Unknown provider: ' .. id) end
208 with(provider)
209 return
210 end
211 table.sort(list, function(a, b)
212 if rank(a) ~= rank(b) then return rank(a) < rank(b) end
213 return a.name < b.name
214 end)
215 vim.ui.select(list, { prompt = 'Sign in to', format_item = describe }, with)
216 end)
217end
219local function logout(state, id)
220 providers(state, function(list)
221 local function with(provider)
222 if not provider then return end
223 state.transport.request('logout', { provider = provider.id }, function(ok, failure)
224 if ok then
225 info('Signed out of ' .. provider.name .. '.')
226 else
227 fail(failure)
228 end
229 end)
230 end
231 list = vim.tbl_filter(function(provider) return provider.stored ~= nil end, list)
232 if id ~= '' then
233 local provider = vim.iter(list):find(function(item) return item.id == id end)
234 if not provider then fail('Not signed in to: ' .. id) end
235 with(provider)
236 elseif #list == 0 then
237 info('No stored sign-ins.')
238 else
239 vim.ui.select(list, { prompt = 'Sign out of', format_item = describe }, with)
240 end
241 end)
242end
244return { login = login, logout = logout, receive = receive }

neovim/lua/bugabinga/pivi/buffer.lua

Added
new file mode 100644

+11 / −0 text lines

1return function(buffer, lines)
2 local old = vim.api.nvim_buf_get_lines(buffer, 0, -1, false)
3 local before, after = table.concat(old, '\n') .. '\n', table.concat(lines, '\n') .. '\n'
4 local hunks = vim.diff(before, after, { result_type = 'indices' })
5 for index = #hunks, 1, -1 do
6 local start, count, new_start, new_count = unpack(hunks[index])
7 local first = count == 0 and start or start - 1
8 local replacement = vim.list_slice(lines, new_start, new_start + new_count - 1)
9 vim.api.nvim_buf_set_lines(buffer, first, first + count, false, replacement)
10 end
11end

neovim/lua/bugabinga/pivi/draft.lua

Added
new file mode 100644

+69 / −0 text lines

1return function(buffer, directory)
2 local path = directory .. '/draft.txt'
3 local temporary = path .. '.' .. vim.fn.getpid() .. '.tmp'
4 local blocked, pending, reported
5 local stat, failure, code = vim.uv.fs_stat(path)
6 if stat then
7 local ok, lines = pcall(vim.fn.readfile, path)
8 if ok then
9 vim.api.nvim_buf_set_lines(buffer, 0, -1, false, lines)
10 else
11 blocked = 'Cannot restore draft; original file left untouched: ' .. tostring(lines)
12 end
13 elseif code ~= 'ENOENT' then
14 blocked = 'Cannot inspect saved draft: ' .. tostring(failure)
15 end
17 local function save()
18 if not vim.api.nvim_buf_is_valid(buffer) then return end
19 local file
20 local ok, err = pcall(function()
21 if blocked then error(blocked) end
22 vim.fn.mkdir(directory, 'p', 448)
23 file = assert(vim.uv.fs_open(temporary, 'w', 384))
24 local text = table.concat(vim.api.nvim_buf_get_lines(buffer, 0, -1, false), '\n')
25 assert(vim.uv.fs_write(file, text, 0) == #text, 'Incomplete draft write')
26 assert(vim.uv.fs_fsync(file))
27 assert(vim.uv.fs_close(file))
28 file = nil
29 assert(vim.uv.fs_rename(temporary, path))
30 end)
31 if file then vim.uv.fs_close(file) end
32 if not ok then
33 vim.uv.fs_unlink(temporary)
34 vim.bo[buffer].modified = true
35 if reported ~= tostring(err) then
36 reported = tostring(err)
37 vim.notify('Pivi draft not saved: ' .. reported, vim.log.levels.ERROR)
38 end
39 return false
40 end
41 reported = nil
42 vim.bo[buffer].modified = false
43 return true
44 end
46 vim.bo[buffer].buftype = 'acwrite'
47 vim.bo[buffer].modified = blocked ~= nil
48 vim.api.nvim_buf_attach(buffer, false, {
49 on_lines = function()
50 -- the draft is saved on its own: the modified flag would flash in the
51 -- status line on every keystroke
52 vim.bo[buffer].modified = false
53 if pending then return end
54 pending = true
55 vim.defer_fn(function()
56 pending = false
57 save()
58 end, 250)
59 end,
60 })
61 vim.api.nvim_create_autocmd({ 'BufLeave', 'BufWriteCmd' }, { buffer = buffer, callback = function() save() end })
62 local leave = vim.api.nvim_create_autocmd('VimLeavePre', { callback = function() save() end })
63 vim.api.nvim_create_autocmd('BufWipeout', {
64 buffer = buffer,
65 callback = function() vim.api.nvim_del_autocmd(leave) end,
66 })
67 if blocked then vim.notify(blocked, vim.log.levels.ERROR) end
68 return save
69end

neovim/lua/bugabinga/pivi/init.lua

Added
new file mode 100644

+651 / −0 text lines

1local auto = require 'std.auto'
2local map = require 'std.map'
3local view = require 'bugabinga.pivi.view'
4local connect = require 'bugabinga.pivi.transport'
5local auth = require 'bugabinga.pivi.auth'
6local review = require 'bugabinga.pivi.review'
7
8local root = vim.fn.fnamemodify(debug.getinfo(1, 'S').source:sub(2), ':h:h:h:h') .. '/pivi'
9local current
11local function notify(message)
12 vim.notify(tostring(message), vim.log.levels.ERROR, { title = 'pivi' })
13end
15local function request(state, method, params, done, settled)
16 if not state.transport.running() then
17 if settled then settled() end
18 notify('Pivi is disconnected.')
19 return
20 end
21 state.transport.request(method, params, function(ok, result)
22 if settled then settled() end
23 if not ok then
24 notify(result)
25 elseif done then
26 done(result)
27 end
28 end)
29end
31local function menu(prompt, choices)
32 vim.ui.select(choices, { prompt = prompt, format_item = function(choice) return choice[1] end }, function(choice)
33 if choice then choice[2]() end
34 end)
35end
37local function label(buffer)
38 local name = vim.api.nvim_buf_get_name(buffer)
39 return name ~= '' and vim.fn.fnamemodify(name, ':~:.') or '[No Name]'
40end
42local function is_workspace(buffer)
43 return vim.api.nvim_buf_is_valid(buffer) and not vim.api.nvim_buf_get_name(buffer):match('^pivi://')
44end
46local function recent_buffer()
47 local recent
48 for _, info in ipairs(vim.fn.getbufinfo({ buflisted = 1 })) do
49 local workspace = vim.bo[info.bufnr].buftype == '' and is_workspace(info.bufnr)
50 if
51 workspace
52 and (
53 not recent
54 or info.lastused > recent.lastused
55 or (info.lastused == recent.lastused and info.bufnr > recent.bufnr)
56 )
57 then
58 recent = info
59 end
60 end
61 return recent and recent.bufnr
62end
64-- a short trail of where the person has been, so the agent knows what they were
65-- doing without asking
66local trail = {}
68local function note_trail()
69 local buffer = vim.api.nvim_get_current_buf()
70 if not is_workspace(buffer) then return end
71 local line = vim.api.nvim_win_get_cursor(0)[1]
72 local last = trail[#trail]
73 if last and last.buffer == buffer and math.abs(last.line - line) < 20 then return end
74 trail[#trail + 1] = { buffer = buffer, line = line }
75 while #trail > 4 do
76 table.remove(trail, 1)
77 end
78end
80local function trail_text()
81 local parts = {}
82 for _, step in ipairs(trail) do
83 if vim.api.nvim_buf_is_valid(step.buffer) then
84 local name = vim.fn.fnamemodify(vim.api.nvim_buf_get_name(step.buffer), ':.')
85 parts[#parts + 1] = ('%s:%d'):format(name, step.line)
86 end
87 end
88 return #parts > 0 and table.concat(parts, ' → ') or nil
89end
91local function editor_context()
92 local buffer = recent_buffer()
93 local where = trail_text()
94 if not buffer then return ('[editor: cwd %s%s]'):format(vim.fn.getcwd(), where and (' · recent ' .. where) or '') end
95 local window = vim.fn.bufwinid(buffer)
96 local line = window ~= -1 and vim.api.nvim_win_get_cursor(window)[1] or vim.api.nvim_buf_get_mark(buffer, '"')[1]
97 return ('[editor: cwd %s · buffer %d %s · line %d · %s%s]'):format(
98 vim.fn.getcwd(),
99 buffer,
100 vim.api.nvim_buf_get_name(buffer),
101 math.max(line, 1),
102 vim.bo[buffer].modified and 'unsaved changes' or 'saved',
103 where and (' · recent ' .. where) or ''
104 )
105end
107-- where the agent works, shown in the buffer itself: the person never has to
108-- look at the conversation
109local activity_namespace = vim.api.nvim_create_namespace('pivi_activity')
110local activity = {}
112local function mark_activity(state, buffer, line)
113 local mark = activity[buffer] or {}
114 mark.line = line
115 mark.started = vim.uv.now()
116 mark.id = vim.api.nvim_buf_set_extmark(activity_namespace, buffer, line - 1, 0, {
117 id = mark.id,
118 virt_text = { { ' ⟳ pivi', 'PiviTool' } },
119 virt_text_pos = 'eol',
120 hl_mode = 'combine',
121 })
122 activity[buffer] = mark
123 state.on_tick = function()
124 for target, entry in pairs(activity) do
125 if not vim.api.nvim_buf_is_valid(target) then
126 activity[target] = nil
127 else
128 local elapsed = vim.uv.now() - entry.started
129 local text = state.busy and (' ⟳ pivi %s · %s'):format(state.activity or 'working', span(elapsed))
130 or (' ✓ pivi · %s'):format(span(elapsed))
131 vim.api.nvim_buf_set_extmark(activity_namespace, target, entry.line - 1, 0, {
132 id = entry.id,
133 virt_text = { { text, state.busy and 'PiviTool' or 'PiviHeading' } },
134 virt_text_pos = 'eol',
135 hl_mode = 'combine',
136 })
137 if not state.busy and entry.done ~= true then
138 entry.done = true
139 vim.notify('Pivi finished here. :Pivi review shows the changes.', vim.log.levels.INFO, { title = 'pivi' })
140 end
141 end
142 end
143 end
144end
146local function it(state)
147 local buffer = vim.api.nvim_get_current_buf()
148 if not is_workspace(buffer) then
149 notify('PiviIt works in a workspace buffer.')
150 return
151 end
152 local cursor = vim.api.nvim_win_get_cursor(0)
153 local lines = vim.api.nvim_buf_get_lines(buffer, 0, -1, false)
154 local first = math.max(1, cursor[1] - 40)
155 local last = math.min(#lines, cursor[1] + 40)
156 local excerpt = table.concat(vim.list_slice(lines, first, last), '\n')
157 local path = vim.api.nvim_buf_get_name(buffer)
158 local content = ('%s\n\n%s\n\n%s'):format(
159 ('Finish the work at %s:%d. What I wrote may be documentation, incomplete code, pseudo code or prose: complete my intent as locally and as completely as possible. Work through the editor tools, keep the change small, and leave the buffer unsaved for review.'):format(
160 path,
161 cursor[1]
162 ),
163 ('Here is the buffer around that place:'),
164 excerpt
165 )
166 mark_activity(state, buffer, cursor[1])
167 request(state, 'submit', { content = editor_context() .. '\n' .. content, mode = 'submit' }, function()
168 vim.notify('Pivi is working on ' .. vim.fn.fnamemodify(path, ':.'), vim.log.levels.INFO, { title = 'pivi' })
169 end, function()
170 activity[buffer] = nil
171 notify('Pivi could not start the work.')
172 end)
173end
175local function select_attachment(state, prompt, done)
176 vim.ui.select(
177 state.attachments,
178 { prompt = prompt, format_item = function(item) return item.label end },
179 function(item)
180 if item then done(item) end
181 end
182 )
183end
185local function attach(state)
186 local function add(kind, buffer)
187 if not buffer or not is_workspace(buffer) then
188 notify('No workspace buffer to attach.')
189 return
190 end
191 vim.fn.bufload(buffer)
192 table.insert(state.attachments, { kind = kind, buffer = buffer, label = kind .. ': ' .. label(buffer) })
193 view.winbar(state)
194 end
195 menu('Attach to draft', {
196 {
197 'Buffer',
198 function()
199 local buffers = vim.tbl_filter(
200 function(buffer) return vim.bo[buffer].buflisted and is_workspace(buffer) end,
201 vim.api.nvim_list_bufs()
202 )
203 local format = function(buffer) return buffer .. ': ' .. label(buffer) end
204 vim.ui.select(buffers, { prompt = 'Buffer', format_item = format }, function(buffer)
205 if buffer then add('buffer', buffer) end
206 end)
207 end,
208 },
209 {
210 'File',
211 function()
212 vim.ui.input({ prompt = 'File: ', completion = 'file' }, function(path)
213 if path and path ~= '' then add('file', vim.fn.bufadd(vim.fn.fnamemodify(path, ':p'))) end
214 end)
215 end,
216 },
217 { 'Diagnostics', function() add('diagnostics', recent_buffer()) end },
218 })
219end
221local function detach(state)
222 select_attachment(state, 'Remove attachment', function(selected)
223 state.attachments = vim.tbl_filter(function(item) return item ~= selected end, state.attachments)
224 view.winbar(state)
225 end)
226end
228local function attachment_text(attachment)
229 local buffer = attachment.buffer
230 local name = vim.api.nvim_buf_get_name(buffer)
231 if attachment.kind ~= 'diagnostics' then
232 local content = table.concat(vim.api.nvim_buf_get_lines(buffer, 0, -1, false), '\n')
233 return ('<buffer number="%d" name="%s">\n%s\n</buffer>'):format(buffer, name, content)
234 end
235 local lines = vim.tbl_map(function(diagnostic)
236 local severity = vim.diagnostic.severity[diagnostic.severity]
237 return ('%d:%d %s %s'):format(diagnostic.lnum + 1, diagnostic.col + 1, severity, diagnostic.message)
238 end, vim.diagnostic.get(buffer))
239 return ('<diagnostics buffer="%d" name="%s">\n%s\n</diagnostics>'):format(buffer, name, table.concat(lines, '\n'))
240end
242local function submit(state, mode)
243 if state.submitting then return end
244 local text = view.draft(state)
245 if text:match('^%s*$') then
246 notify('Draft is empty.')
247 return
248 end
249 local sent = vim.list_slice(state.attachments)
250 local parts = { editor_context() .. '\n' .. text }
251 for _, attachment in ipairs(sent) do
252 if not vim.api.nvim_buf_is_valid(attachment.buffer) then
253 notify('Attached buffer no longer exists: ' .. attachment.label)
254 return
255 end
256 parts[#parts + 1] = attachment_text(attachment)
257 end
258 state.submitting = true
259 view.winbar(state)
260 request(state, 'submit', { content = table.concat(parts, '\n\n'), mode = mode }, function()
261 if view.draft(state) == text then view.set_draft(state, '') end
262 state.attachments = vim.tbl_filter(function(item) return not vim.tbl_contains(sent, item) end, state.attachments)
263 view.winbar(state)
264 for _, window in ipairs(vim.fn.win_findbuf(state.buffer)) do
265 view.follow(state, window)
266 end
267 end, function()
268 state.submitting = false
269 view.winbar(state)
270 end)
271end
273local function fork(state, id)
274 if not id then
275 notify('Place cursor on a committed entry.')
276 return
277 end
278 local previous, prompt
279 for _, item in ipairs(state.view.items) do
280 local entry = item.entry
281 if entry and entry.id == id then
282 local lines = view.entry_lines(state, id)
283 if entry.kind == 'pi.user' then
284 prompt = table.concat(lines, '\n', 2, #lines - 1):gsub('^%[editor: [^\n]*%]\n', '')
285 end
286 break
287 end
288 previous = entry and entry.id or previous
289 end
290 if not prompt then
291 request(state, 'fork', { entry = id })
292 elseif not view.draft(state):match('^%s*$') then
293 notify('Draft is not empty. Submit or clear it before forking at a prompt.')
294 else
295 request(state, previous and 'fork' or 'new', { entry = previous }, function()
296 view.set_draft(state, prompt)
297 vim.api.nvim_set_current_buf(state.draft_buffer)
298 end)
299 end
300end
302local function inspect_entry(state, entry)
303 if not entry then
304 notify('No entry at cursor.')
305 return
306 end
307 view.page('entry', view.entry_lines(state, entry))
308end
310local function open_attachment(state)
311 if #state.attachments == 0 then
312 notify('No attachments.')
313 return
314 end
315 select_attachment(state, 'Open attachment', function(item)
316 if vim.api.nvim_buf_is_valid(item.buffer) then vim.api.nvim_set_current_buf(item.buffer) end
317 end)
318end
320local function goblin(state, first, last)
321 local buffer = vim.api.nvim_get_current_buf()
322 if buffer == state.buffer or buffer == state.draft_buffer then
323 notify('Goblin works from a code buffer.')
324 return
325 end
326 local name = vim.api.nvim_buf_get_name(buffer)
327 local cursor = vim.api.nvim_win_get_cursor(vim.fn.bufwinid(buffer))[1]
328 local lines = vim.api.nvim_buf_get_lines(buffer, first - 1, last, false)
329 local selection = first ~= 1 or last ~= vim.api.nvim_buf_line_count(buffer)
330 local position = selection and ('lines %d-%d of'):format(first, last) or ('cursor at line %d of'):format(cursor)
331 local attachment = ('<buffer number="%d" name="%s" %s>' .. '\n' .. table.concat(lines, '\n') .. '\n</buffer>'):format(buffer, name, position)
332 local prompt = vim.g.pivi_goblin_prompt
333 or 'The attached buffer holds a rough sketch or pseudo-code. Finish it into working code at the marked position: '
334 .. 'complete the sketch, keep intent, naming and surroundings, and keep the edit unsaved for review.'
335 request(state, 'submit', {
336 content = editor_context() .. '\n' .. prompt .. '\n\n' .. attachment,
337 mode = state.busy and 'followUp' or 'submit',
338 })
339end
341local function goblin_keys(state)
342 vim.keymap.set('x', 'gb', function() goblin(state, vim.fn.line('v'), vim.fn.line('.')) end, {
343 desc = 'pivi goblin: send the selection to the agent',
344 })
345 vim.keymap.set('n', 'gb', function()
346 vim.go.operatorfunc = function() goblin(state, vim.fn.line("'['"), vim.fn.line("]")) end
347 return 'g@'
348 end, { expr = true, desc = 'pivi goblin: send a motion to the agent (gb with no motion sends the whole buffer)' })
349end
351local actions = {
352 help = function(state) view.help(state, false) end,
353 toggle = function(state)
354 if vim.api.nvim_get_current_buf() == state.draft_buffer then
355 view.focus_conversation(state)
356 else
357 view.draft_split(state)
358 end
359 end,
360 submit = function(state) submit(state, 'submit') end,
361 steer = function(state) submit(state, 'steer') end,
362 followUp = function(state) submit(state, 'followUp') end,
363 review = review,
364 abort = function(state)
365 if state.stopping then return end
366 if not state.transport.running() then
367 notify('Pivi is disconnected. Run :Pivi to reconnect before stopping retained work.')
368 return
369 end
370 local inbox = state.view and state.view.docs['pi.inbox']
371 local queued = {}
372 for _, item in ipairs(inbox and inbox.items or {}) do
373 if type(item.content) == 'string' then queued[#queued + 1] = (item.content:gsub('^%[editor: [^\n]*%]\n', '')) end
374 end
375 if not state.view then return end
376 state.stopping = true
377 view.render(state, state.view)
378 state.transport.request('abort', nil, function(ok, failure)
379 state.stopping = false
380 view.render(state, state.view)
381 if not ok then
382 notify(failure)
383 elseif #queued > 0 then
384 local draft = view.draft(state)
385 if not draft:match('^%s*$') then table.insert(queued, 1, draft) end
386 view.set_draft(state, table.concat(queued, '\n\n'))
387 vim.notify('Queued messages are back in the draft.', vim.log.levels.INFO, { title = 'pivi' })
388 end
389 end)
390 end,
391 fork = function(state) fork(state, view.entry(state)) end,
392 inspect = function(state)
393 if view.context(state) == 'draft' then
394 open_attachment(state)
395 else
396 inspect_entry(state, view.entry(state))
397 end
398 end,
399 actions = function(state)
400 if view.context(state) ~= 'draft' then
401 local entry = view.entry(state)
402 menu('Pivi entry', {
403 { 'Inspect entry', function() inspect_entry(state, entry) end },
404 { 'Fork at entry', function() fork(state, entry) end },
405 })
406 elseif #state.attachments == 0 then
407 attach(state)
408 else
409 menu('Pivi draft', {
410 { 'Attach context', function() attach(state) end },
411 { 'Open attachment', function() open_attachment(state) end },
412 { 'Remove attachment', function() detach(state) end },
413 })
414 end
415 end,
416}
418local function dispatch(state, action)
419 if state ~= current then
420 notify('This pivi buffer is not connected. Run :Pivi.')
421 return
422 end
423 actions[action](state)
424end
426local function disconnected(state, message)
427 view.disconnected(state, message)
428end
430local function stop()
431 local state = current
432 if not state then return end
433 current = nil
434 state.transport.close()
435 disconnected(state)
436end
438local function start()
439 if current and not (current.transport.running() and vim.api.nvim_buf_is_valid(current.buffer)) then stop() end
440 if not current then
441 if vim.fn.isdirectory(root .. '/node_modules') == 0 then
442 notify('Pivi dependencies missing. Run `just pivi-install`.')
443 return
444 end
445 local id = vim.g.PiviSession
446 if type(id) ~= 'string' or not id:match('^[%w_-]+$') then
447 id = vim.fn.sha256(vim.uv.hrtime() .. ':' .. vim.fn.getpid()):sub(1, 8)
448 vim.g.PiviSession = id
449 end
450 vim.opt.sessionoptions:append('globals')
451 local argv = {
452 vim.g.pivi_node or 'node',
453 root .. '/worker.mjs',
454 vim.fn.stdpath('state') .. '/pivi/sessions/' .. id .. '/session.sqlite',
455 vim.fn.stdpath('state') .. '/pivi/auth.json',
456 vim.g.pivi_config,
457 }
458 local state = view.create(id, dispatch)
459 local ok, transport = pcall(connect, argv, function(record)
460 if current ~= state then return end
461 if record.type == 'exit' then
462 local message = (record.code ~= 0 or record.protocol_error or not state.ready)
463 and ('Pivi worker exited (%d). %s'):format(record.code, record.error)
464 or nil
465 disconnected(state, message)
466 if message then notify(message) end
467 elseif record.type == 'view' then
468 -- a view that cannot be drawn must not take the worker down
469 local drawn, failure = pcall(view.render, state, record.view)
470 if not drawn and failure ~= state.render_failure then
471 state.render_failure = failure
472 vim.notify('Pivi could not draw the conversation: ' .. tostring(failure), vim.log.levels.ERROR, {
473 title = 'pivi',
474 })
475 end
476 elseif record.type == 'ready' then
477 state.ready = true
478 elseif record.type == 'report' then
479 notify(record.error)
480 elseif record.type == 'notice' then
481 vim.notify(record.message, vim.log.levels.INFO, { title = 'pivi' })
482 else
483 auth.receive(state, record)
484 end
485 end)
486 if not ok then
487 view.disconnected(state, tostring(transport))
488 vim.api.nvim_set_current_buf(state.buffer)
489 notify(transport)
490 return
491 end
492 state.id, state.transport, state.ready = id, transport, false
493 current = state
494 goblin_keys(state)
495 end
496 return current
497end
499local function show()
500 local state = start()
501 if not state then return end
502 vim.api.nvim_set_current_buf(state.buffer)
503 view.draft_split(state)
504end
506local sign_in
508local function choose_model(state, value, only)
509 local function configure(provider, model)
510 request(state, 'configure', { model = { provider = provider, modelId = model } })
511 end
512 if value ~= '' then
513 local provider, model = value:match('^([^/]+)/(.+)$')
514 if not provider then
515 notify('Use provider/model-id.')
516 return
517 end
518 configure(provider, model)
519 return
520 end
521 request(state, 'models', nil, function(models)
522 if only then models = vim.tbl_filter(function(item) return item.provider == only end, models) end
523 if #models == 0 and only then
524 notify('Signed in, but ' .. only .. ' offers no models.')
525 return
526 elseif #models == 0 then
527 vim.notify('No usable models yet. Sign in to a provider first.', vim.log.levels.INFO, { title = 'pivi' })
528 sign_in(state, '')
529 return
530 end
531 local format = function(item) return item.provider .. '/' .. item.modelId end
532 vim.ui.select(models, { prompt = 'Pivi model', format_item = format }, function(choice)
533 if choice then configure(choice.provider, choice.modelId) end
534 end)
535 end)
536end
538sign_in = function(state, provider)
539 auth.login(state, provider, function(signed_in)
540 if state.model == 'no model' then choose_model(state, '', signed_in.id) end
541 end)
542end
544local commands = {
545 login = sign_in,
546 logout = auth.logout,
547 show = function(state)
548 vim.api.nvim_set_current_buf(state.buffer)
549 view.draft_split(state)
550 end,
551 draft = function(state) view.draft_split(state) end,
552 help = function(state) view.help(state, true) end,
553 model = choose_model,
554 attach = attach,
555 fork = actions.fork,
556 compact = function(state, instructions) request(state, 'compact', { instructions = instructions }) end,
557 new = function(state) request(state, 'new') end,
558 earlier = function(state) request(state, 'earlier') end,
559 resume = function(state) request(state, 'resume') end,
560 continue = function(state)
561 if state.busy then
562 notify('Work is still retained. Use :Pivi resume for suspended work, or :Pivi stop first.')
563 return
564 end
565 if not (state.view and state.view.docs['pi.live'].runFailure) then
566 notify('No stopped run to continue. Write a new draft instead.')
567 return
568 end
569 menu('Continue from retained history? Existing edits stay; the model may repeat actions.', {
570 { 'Keep stopped', function() end },
571 { 'Continue run', function() request(state, 'continue') end },
572 })
573 end,
574 review = review,
575 it = it,
576 goblin = function(state) goblin(state, 1, vim.api.nvim_buf_line_count(vim.api.nvim_get_current_buf())) end,
577 stop = function(state) actions.abort(state) end,
578 reload = function()
579 stop()
580 for _, buffer in ipairs(vim.api.nvim_list_bufs()) do
581 if vim.api.nvim_buf_get_name(buffer):match('^pivi://') then
582 pcall(vim.api.nvim_buf_delete, buffer, { force = true })
583 end
584 end
585 for name in pairs(package.loaded) do
586 if name:match('^bugabinga%.pivi') then package.loaded[name] = nil end
587 end
588 require('bugabinga.pivi').show()
589 end,
590}
591local names = vim.tbl_keys(commands)
592table.insert(names, 'close')
593table.sort(names)
595vim.api.nvim_create_user_command('Pivi', function(options)
596 local name, argument = options.args:match('^(%S*)%s*(.*)$')
597 if name == 'close' then
598 stop()
599 return
600 end
601 local command = commands[name == '' and 'show' or name]
602 if not command then
603 notify('Unknown Pivi command: ' .. name)
604 return
605 end
606 local state = start()
607 if state then command(state, argument) end
608end, {
609 nargs = '*',
610 complete = function(lead)
611 return vim.tbl_filter(function(name) return vim.startswith(name, lead) end, names)
612 end,
613 desc = 'Pivi: standalone Pi Durable harness',
614})
616map.normal { keys = view.prefix() .. 'p', description = 'Open pivi', category = 'pivi', command = show }
617map.normal {
618 keys = view.prefix() .. 'pi',
619 description = 'Let pivi finish the work here',
620 category = 'pivi',
621 command = function()
622 local state = start()
623 if state then it(state) end
624 end,
625}
627auto('pivi_lifecycle') {
628 { events = 'VimLeavePre', command = stop },
629 {
630 events = 'BufModifiedSet',
631 command = function()
632 if current then view.winbar(current) end
633 end,
634 },
635 {
636 events = 'SessionLoadPost',
637 command = function()
638 if current and current.id ~= vim.g.PiviSession then stop() end
639 if vim.api.nvim_buf_get_name(0):match('^pivi://') then show() end
640 end,
641 },
642}
644vim.api.nvim_create_autocmd({ 'CursorMoved', 'BufEnter' }, { callback = note_trail })
646_G.BugabingaPivi = {
647 show = show,
648 close = stop,
649 current = function() return current end,
650}
651return _G.BugabingaPivi

neovim/lua/bugabinga/pivi/lsp.lua

Added
new file mode 100644

+163 / −0 text lines

1local METHODS = {
2 definition = 'textDocument/definition',
3 references = 'textDocument/references',
4 implementation = 'textDocument/implementation',
5 type_definition = 'textDocument/typeDefinition',
6 hover = 'textDocument/hover',
7 rename = 'textDocument/rename',
8 symbols = 'textDocument/documentSymbol',
9 workspace_symbols = 'workspace/symbol',
10}
11local ATTACH_MS = 10000
12local RETRY_MS = 300
13local LIMIT = 100
15return function(helpers)
16 local function kind(symbol)
17 return (vim.lsp.protocol.SymbolKind[symbol.kind] or 'Symbol'):lower()
18 end
20 local function position(buffer, client, args)
21 local text = vim.api.nvim_buf_get_lines(buffer, args.line - 1, args.line, false)[1]
22 if not text then error(('Line %d does not exist in %s.'):format(args.line, args.path), 0) end
23 local column = (text:find('%S') or 1) - 1
24 if args.symbol then
25 local from = text:find(args.symbol, 1, true)
26 if not from then
27 error(
28 ('"%s" is not on line %d of %s, which reads: %s'):format(args.symbol, args.line, args.path, vim.trim(text)),
29 0
30 )
31 end
32 column = from - 1
33 end
34 return { line = args.line - 1, character = vim.str_utfindex(text, client.offset_encoding, column) }
35 end
37 local function locations(result)
38 local files, lines = {}, {}
39 for _, item in ipairs(vim.islist(result) and result or { result }) do
40 local path = vim.uri_to_fname(item.uri or item.targetUri)
41 local start = (item.range or item.targetSelectionRange).start
42 if not files[path] then
43 local buffer = vim.fn.bufnr(path)
44 local loaded = buffer ~= -1 and vim.api.nvim_buf_is_loaded(buffer)
45 files[path] = loaded and vim.api.nvim_buf_get_lines(buffer, 0, -1, false)
46 or vim.uv.fs_stat(path) and vim.fn.readfile(path)
47 or {}
48 end
49 local source = vim.trim(files[path][start.line + 1] or '')
50 lines[#lines + 1] = ('%s:%d:%d %s'):format(helpers.relative(path), start.line + 1, start.character + 1, source)
51 end
52 table.sort(lines)
53 return helpers.limited(vim.fn.uniq(lines), LIMIT, 'locations')
54 end
56 local function outline(symbols, indent, lines)
57 for _, symbol in ipairs(symbols) do
58 local range = symbol.selectionRange or symbol.range or symbol.location.range
59 lines[#lines + 1] = ('%s%s %s :%d'):format(indent, kind(symbol), symbol.name, range.start.line + 1)
60 outline(symbol.children or {}, indent .. ' ', lines)
61 end
62 return lines
63 end
65 local function present(operation, result, client, args)
66 if operation == 'hover' then
67 return table.concat(vim.lsp.util.convert_input_to_markdown_lines(result.contents), '\n')
68 elseif operation == 'symbols' then
69 return helpers.limited(outline(result, '', {}), 300, 'symbols')
70 elseif operation == 'workspace_symbols' then
71 local lines = vim.tbl_map(function(symbol)
72 local path = helpers.relative(vim.uri_to_fname(symbol.location.uri))
73 local line = symbol.location.range and symbol.location.range.start.line + 1 or 1
74 return ('%s:%d %s %s'):format(path, line, kind(symbol), symbol.name)
75 end, result)
76 table.sort(lines, function(a, b)
77 local outside_a, outside_b = vim.startswith(a, '/'), vim.startswith(b, '/')
78 if outside_a ~= outside_b then return outside_b end
79 return a < b
80 end)
81 return helpers.limited(lines, LIMIT, 'symbols')
82 elseif operation == 'rename' then
83 vim.lsp.util.apply_workspace_edit(result, client.offset_encoding)
84 local files = vim.tbl_keys(result.changes or {})
85 for _, change in ipairs(result.documentChanges or {}) do
86 if change.textDocument then files[#files + 1] = change.textDocument.uri end
87 end
88 files = vim.tbl_map(function(uri) return helpers.relative(vim.uri_to_fname(uri)) end, files)
89 table.sort(files)
90 local list = table.concat(vim.fn.uniq(files), ', ')
91 return ('Renamed to %s in: %s. These buffers have unsaved changes.'):format(args.newName, list)
92 end
93 return locations(result)
94 end
96 return function(args, done)
97 local operation, method = args.operation, METHODS[args.operation]
98 if not method then error('Unknown lsp operation: ' .. tostring(operation), 0) end
99 local positional = operation ~= 'symbols' and operation ~= 'workspace_symbols'
100 if operation ~= 'workspace_symbols' and not args.path then error(operation .. ' needs path.', 0) end
101 if positional and not args.line then error(operation .. ' needs line.', 0) end
102 if operation == 'rename' and not args.newName then error('rename needs newName.', 0) end
103 if operation == 'workspace_symbols' and not args.query then error('workspace_symbols needs query.', 0) end
105 local buffer = args.path and helpers.load(args.path)
106 local deadline = vim.uv.now() + ATTACH_MS
107 local timer, cancelled, waited
109 local function later(action, delay)
110 timer = vim.defer_fn(function()
111 if not cancelled then action() end
112 end, delay)
113 end
115 local function ask(client, params, retries)
116 client:request(method, params, function(failure, result)
117 if cancelled then return end
118 if failure then return done { text = failure.message or vim.inspect(failure), error = true } end
119 local empty = result == nil or (vim.islist(result) and #result == 0)
120 if empty and retries > 0 then
121 return later(function() ask(client, params, retries - 1) end, RETRY_MS)
122 end
123 if empty then return done { text = 'No results.' } end
124 local ok, text = pcall(present, operation, result, client, args)
125 done { text = text, error = not ok }
126 end, buffer)
127 end
129 local function start()
130 local client = vim.lsp.get_clients({ bufnr = buffer, method = method })[1]
131 if client and client.initialized then
132 local ok, params = pcall(function()
133 if operation == 'workspace_symbols' then return { query = args.query } end
134 local document = { uri = vim.uri_from_bufnr(buffer) }
135 if operation == 'symbols' then return { textDocument = document } end
136 local params = { textDocument = document, position = position(buffer, client, args) }
137 params.context = operation == 'references' and { includeDeclaration = true } or nil
138 params.newName = args.newName
139 return params
140 end)
141 if not ok then return done { text = params, error = true } end
142 return ask(client, params, waited and 20 or 2)
143 end
144 local configured, configs =
145 pcall(vim.lsp.get_configs, { enabled = true, filetype = buffer and vim.bo[buffer].filetype })
146 if buffer and vim.uv.now() < deadline and (not configured or #configs > 0) then
147 waited = true
148 return later(start, 100)
149 end
150 local where = buffer and ('%s (filetype %s)'):format(args.path, vim.bo[buffer].filetype) or 'this session'
151 done {
152 text = ('No language server offers %s for %s. Search with rg instead.'):format(operation, where),
153 error = true,
154 }
155 end
157 start()
158 return function()
159 cancelled = true
160 if timer and not timer:is_closing() then timer:close() end
161 end
162 end
163end

neovim/lua/bugabinga/pivi/review.lua

Added
new file mode 100644

+137 / −0 text lines

1local set_lines = require 'bugabinga.pivi.buffer'
2
3local function notify(message)
4 vim.notify(message, vim.log.levels.INFO, { title = 'pivi' })
5end
6
7local function collect()
8 local lines, targets, hunks = {}, {}, {}
9 local function add(line, buffer, row, hunk)
10 lines[#lines + 1] = line
11 targets[#lines] = { buffer = buffer, row = row, hunk = hunk }
12 end
13 add('pivi review · <CR> jump · s save change · r revert change · S save file · R revert file · q back')
14 for _, buffer in ipairs(vim.api.nvim_list_bufs()) do
15 local name = vim.api.nvim_buf_get_name(buffer)
16 if vim.bo[buffer].modified and vim.bo[buffer].buftype == '' and name ~= '' then
17 local saved = vim.uv.fs_stat(name) and table.concat(vim.fn.readfile(name), '\n') .. '\n' or ''
18 local current = table.concat(vim.api.nvim_buf_get_lines(buffer, 0, -1, false), '\n') .. '\n'
19 local path = vim.fn.fnamemodify(name, ':.')
20 add('--- ' .. (saved == '' and '/dev/null' or 'a/' .. path), buffer, 1)
21 add('+++ b/' .. path, buffer, 1)
22 local row, hunk = 1, nil
23 for _, line in ipairs(vim.split(vim.diff(saved, current, { ctxlen = 3 }), '\n', { trimempty = true })) do
24 local old_start, old_count, new_start, new_count = line:match('^@@ %-(%d+),?(%d*) %+(%d+),?(%d*) @@')
25 if old_start then
26 old_count, new_count = tonumber(old_count) or 1, tonumber(new_count) or 1
27 hunk = {
28 old_from = old_count == 0 and tonumber(old_start) or old_start - 1,
29 old_count = old_count,
30 new_from = new_count == 0 and tonumber(new_start) or new_start - 1,
31 new_count = new_count,
32 }
33 row = math.max(tonumber(new_start), 1)
34 hunks[#hunks + 1] = { bufnr = buffer, lnum = row, text = line }
35 end
36 add(line, buffer, row, hunk)
37 if not old_start and line:sub(1, 1) ~= '-' then row = row + 1 end
38 end
39 end
40 end
41 return lines, targets, hunks
42end
44local page, origin, targets
46local function refresh()
47 local lines, hunks
48 lines, targets, hunks = collect()
49 vim.bo[page].modifiable = true
50 vim.api.nvim_buf_set_lines(page, 0, -1, false, #lines > 1 and lines or { 'No unsaved changes.' })
51 vim.bo[page].modifiable = false
52 vim.fn.setqflist({}, 'r', { title = 'pivi review', items = hunks })
53 return #lines > 1
54end
56local function key(lhs, description, action)
57 vim.keymap.set('n', lhs, function()
58 local target = targets[vim.api.nvim_win_get_cursor(0)[1]]
59 if target and target.buffer and vim.api.nvim_buf_is_valid(target.buffer) then action(target) end
60 end, { buffer = page, nowait = true, desc = 'pivi: ' .. description })
61end
63local function create()
64 page = vim.api.nvim_create_buf(false, true)
65 vim.api.nvim_buf_set_name(page, 'pivi://review')
66 vim.bo[page].filetype = 'diff'
67 vim.bo[page].bufhidden = 'hide'
68 vim.api.nvim_create_autocmd('BufEnter', { buffer = page, callback = refresh })
69 vim.keymap.set('n', 'q', function()
70 if origin and vim.api.nvim_buf_is_valid(origin) then vim.api.nvim_set_current_buf(origin) end
71 end, { buffer = page, nowait = true, desc = 'pivi: Leave review' })
72 key('<CR>', 'Jump to this change', function(target)
73 vim.api.nvim_set_current_buf(target.buffer)
74 vim.api.nvim_win_set_cursor(0, { math.min(target.row, vim.api.nvim_buf_line_count(target.buffer)), 0 })
75 end)
76 local function on_change(action)
77 return function(target)
78 local name = vim.api.nvim_buf_get_name(target.buffer)
79 if not target.hunk then
80 notify('Place the cursor on a change. S and R act on the whole file.')
81 elseif not vim.uv.fs_stat(name) then
82 notify('This file is not on disk yet. S saves it, R discards it.')
83 else
84 action(target.buffer, target.hunk, name, vim.fn.readfile(name))
85 refresh()
86 end
87 end
88 end
89 key(
90 's',
91 'Save this change',
92 on_change(function(buffer, hunk, _, disk)
93 local full = vim.api.nvim_buf_get_lines(buffer, 0, -1, false)
94 local only = vim.list_slice(disk, 1, hunk.old_from)
95 vim.list_extend(only, full, hunk.new_from + 1, hunk.new_from + hunk.new_count)
96 vim.list_extend(only, disk, hunk.old_from + hunk.old_count + 1)
97 set_lines(buffer, only)
98 vim.api.nvim_buf_call(buffer, function() vim.cmd('silent write') end)
99 set_lines(buffer, full)
100 end)
101 )
102 key(
103 'r',
104 'Revert this change',
105 on_change(function(buffer, hunk, _, disk)
106 local original = vim.list_slice(disk, hunk.old_from + 1, hunk.old_from + hunk.old_count)
107 vim.api.nvim_buf_set_lines(buffer, hunk.new_from, hunk.new_from + hunk.new_count, false, original)
108 if vim.deep_equal(vim.api.nvim_buf_get_lines(buffer, 0, -1, false), disk) then vim.bo[buffer].modified = false end
109 end)
110 )
111 key('S', 'Save this file', function(target)
112 vim.fn.mkdir(vim.fs.dirname(vim.api.nvim_buf_get_name(target.buffer)), 'p')
113 vim.api.nvim_buf_call(target.buffer, function() vim.cmd('silent write') end)
114 refresh()
115 end)
116 key('R', 'Revert this file to disk', function(target)
117 local name = vim.api.nvim_buf_get_name(target.buffer)
118 local question = 'Discard unsaved changes in ' .. vim.fn.fnamemodify(name, ':.') .. '?'
119 if vim.fn.confirm(question, '&Discard\n&Keep', 2) ~= 1 then return end
120 if vim.uv.fs_stat(name) then
121 vim.api.nvim_buf_call(target.buffer, function() vim.cmd('silent edit!') end)
122 else
123 vim.api.nvim_buf_delete(target.buffer, { force = true })
124 end
125 refresh()
126 end)
127end
129return function()
130 if not page or not vim.api.nvim_buf_is_valid(page) then create() end
131 if not refresh() then
132 vim.notify('No unsaved changes.', vim.log.levels.INFO, { title = 'pivi' })
133 return
134 end
135 if vim.api.nvim_get_current_buf() ~= page then origin = vim.api.nvim_get_current_buf() end
136 vim.api.nvim_set_current_buf(page)
137end

neovim/lua/bugabinga/pivi/tools.lua

Added
new file mode 100644

+325 / −0 text lines

1local set_lines = require 'bugabinga.pivi.buffer'
2local LIST_LIMIT = 300
3
4local function absolute(path)
5 return vim.fs.normalize(vim.fn.fnamemodify(path, ':p'))
6end
7
8local function relative(path)
9 return vim.fn.fnamemodify(path, ':.')
10end
12local function is_workspace(buffer)
13 return vim.bo[buffer].buftype == '' and vim.api.nvim_buf_get_name(buffer) ~= ''
14end
16local function unsaved()
17 return vim.tbl_filter(
18 function(buffer) return vim.bo[buffer].modified and is_workspace(buffer) end,
19 vim.api.nvim_list_bufs()
20 )
21end
23local function load(path, create)
24 local name = absolute(path)
25 if not create and vim.fn.bufexists(name) == 0 and not vim.uv.fs_stat(name) then
26 error('No such file or buffer: ' .. path, 0)
27 end
28 local buffer = vim.fn.bufadd(name)
29 local shortmess = vim.o.shortmess
30 vim.o.shortmess = shortmess .. 'A'
31 local loaded, failure = pcall(vim.fn.bufload, buffer)
32 vim.o.shortmess = shortmess
33 if not loaded then error(failure, 0) end
34 return buffer, name
35end
37local function limited(lines, limit, what)
38 if #lines <= limit then return table.concat(lines, '\n') end
39 return table.concat(lines, '\n', 1, limit)
40 .. ('\n[%d more %s not shown; narrow the search]'):format(#lines - limit, what)
41end
43local function unsaved_text(args, done)
44 local name = absolute(args.path)
45 local number = vim.fn.bufnr(name)
46 local known = vim.fn.bufexists(name) == 1 and vim.api.nvim_buf_is_loaded(number) and is_workspace(number)
47 if not known or (not vim.bo[number].modified and vim.uv.fs_stat(name)) then return done(vim.empty_dict()) end
48 local text = table.concat(vim.api.nvim_buf_get_lines(number, 0, -1, false), '\n')
49 done { text = text .. (vim.bo[number].endofline and '\n' or '') }
50end
52local function set_text(args, done)
53 local number = load(args.path, true)
54 local lines = vim.split(args.content, '\n', { plain = true })
55 if lines[#lines] == '' then lines[#lines] = nil end
56 set_lines(number, lines)
57 vim.bo[number].buflisted = true
58 done(vim.empty_dict())
59end
61local SLICE_NS = 10 * 1e9
62local BLOCKING = '%s blocks the editor. Use await(), system() or sleep() instead.'
64local function refuse(name)
65 return function() error(BLOCKING:format(name), 2) end
66end
68local guarded = setmetatable({
69 wait = refuse('vim.wait'),
70 fn = setmetatable(
71 { system = refuse('vim.fn.system'), systemlist = refuse('vim.fn.systemlist') },
72 { __index = vim.fn }
73 ),
74 system = function(...)
75 return setmetatable({ wait = refuse('vim.system(...):wait') }, { __index = vim.system(...) })
76 end,
77}, { __index = vim })
79local function nvim_lua(args, done, progress)
80 local chunk, failure = loadstring(args.code, '=nvim_lua')
81 if not chunk then error(failure, 0) end
82 local thread, cancelled
83 local cancels = {}
85 local function resume(...)
86 if cancelled then return end
87 local started = vim.uv.hrtime()
88 debug.sethook(function()
89 if vim.uv.hrtime() - started > SLICE_NS then
90 error('nvim_lua ran for 10 s without yielding and was stopped. Use await(), system() or sleep().', 2)
91 end
92 end, '', 1000000)
93 local results = vim.F.pack_len(coroutine.resume(thread, ...))
94 debug.sethook()
95 if not results[1] then return done { text = tostring(results[2]), error = true } end
96 if coroutine.status(thread) ~= 'dead' then return end
97 local value = results[2]
98 if type(value) ~= 'string' then
99 local ok, encoded = pcall(vim.json.encode, value)
100 value = ok and encoded or vim.inspect(value)
101 if type(value) == 'table' then value = vim.inspect(value) end
102 end
103 done { text = value }
104 end
106 local function await(start)
107 local settled, cancel = false, nil
108 cancel = start(function(...)
109 if settled then return end
110 settled = true
111 local values = vim.F.pack_len(...)
112 vim.schedule(function()
113 cancels[cancel or false] = nil
114 resume(vim.F.unpack_len(values))
115 end)
116 end)
117 if type(cancel) == 'function' then cancels[cancel] = true end
118 return coroutine.yield()
119 end
121 local function sleep(milliseconds)
122 return await(function(resolve)
123 local timer = vim.defer_fn(resolve, milliseconds)
124 return function()
125 if not timer:is_closing() then timer:close() end
126 end
127 end)
128 end
130 local function plain(text)
131 return (tostring(text):gsub('\27%[[%d;]*%a', ''))
132end
134local function system(command, options)
135 options = options or {}
136 local hidden = vim.tbl_map(function(number) return relative(vim.api.nvim_buf_get_name(number)) end, unsaved())
137 if #hidden > 0 then
138 progress(('[unsaved buffers this command cannot see: %s]\n'):format(table.concat(hidden, ', ')))
139 end
140 return await(function(resolve)
141 local output = { stdout = {}, stderr = {} }
142 local function stream(name)
143 return function(_, data)
144 if not data then return end
145 table.insert(output[name], data)
146 vim.schedule(function() progress(data) end)
147 end
148 end
149 local process, timed_out, killed
150 local function kill(how)
151 killed = killed or how or 'sigterm'
152 pcall(vim.uv.kill, -process.pid, killed)
153 end
154 local seconds = options.timeout or 60
155 local timer = vim.defer_fn(function()
156 timed_out = true
157 kill('sigterm')
158 vim.defer_fn(function()
159 if timed_out and killed == 'sigterm' then kill('sigkill') end
160 end, 5000)
161 end, seconds * 1000)
162 local argv = type(command) == 'table' and command or { 'sh', '-c', command }
163 local started
164 started, process = pcall(vim.system, argv, {
165 cwd = options.cwd,
166 env = options.env,
167 stdin = options.stdin,
168 text = true,
169 detach = true,
170 stdout = stream('stdout'),
171 stderr = stream('stderr'),
172 }, function(result)
173 vim.schedule(function()
174 if not timer:is_closing() then timer:close() end
175 resolve {
176 code = result.code,
177 signal = result.signal,
178 timed_out = timed_out or false,
179 stdout = plain(table.concat(output.stdout)),
180 stderr = plain(table.concat(output.stderr)),
181 }
182 end)
183 end)
184 if not started then
185 timer:close()
186 error(process, 0)
187 end
188 return function()
189 if not timer:is_closing() then timer:close() end
190 kill()
191 end
192 end)
193 end
195 local environment = { vim = guarded, await = await, sleep = sleep, system = system }
196 jit.off(chunk, true)
197 thread = coroutine.create(setfenv(chunk, setmetatable(environment, { __index = _G })))
198 resume()
199 return function()
200 cancelled = true
201 for cancel in pairs(cancels) do
202 cancel()
203 end
204 end
205end
207-- the file listing and content search tools: they exist so the agent never has to
208-- open a shell for the two things it does most
209local EXCLUDED = { ['.git'] = true, ['node_modules'] = true, ['zig-cache'] = true, ['zig-out'] = true, ['.cache'] = true }
211local function glob_to_pattern(glob)
212 local pattern = glob:gsub('([%^%$%(%)%%%.%[%]%+%-%*%?])', '%%%1'):gsub('%%%*', '[^/]*'):gsub('%%%?', '.')
213 return '^' .. pattern .. '$'
214end
216local function find_files(args, done)
217 local root = absolute(args.path or vim.fn.getcwd())
218 local wanted = args.glob and glob_to_pattern(args.glob) or nil
219 local results, limit = {}, math.min(args.limit or 100, 300)
220 local function walk(dir)
221 if #results >= limit then return end
222 for name, type in vim.fs.dir(dir) do
223 if #results >= limit then break end
224 local full = dir .. '/' .. name
225 if type == 'directory' then
226 if not EXCLUDED[name] then walk(full) end
227 elseif not wanted or name:match(wanted) then
228 results[#results + 1] = full
229 end
230 end
231 end
232 walk(root)
233 local stat = vim.uv.fs_stat
234 table.sort(results, function(a, b)
235 local sa, sb = stat(a), stat(b)
236 return (sa and sa.mtime.sec or 0) > (sb and sb.mtime.sec or 0)
237 end)
238 local lines = vim.tbl_map(function(file) return relative(file) end, results)
239 done { text = #lines == 0 and 'No files matched.' or limited(lines, limit, 'files') }
240end
242local function search_files(args, done)
243 if vim.fn.executable('rg') == 0 then
244 return done { text = 'ripgrep is not installed.', error = true }
245 end
246 local argv = { 'rg', '--line-number', '--column', '--no-heading', '--color', 'never', '--max-count', tostring(args.max or 100) }
247 if args.literal then argv[#argv + 1] = '--fixed-strings' end
248 if args.glob then
249 argv[#argv + 1] = '--glob'
250 argv[#argv + 1] = args.glob
251 end
252 argv[#argv + 1] = args.pattern
253 argv[#argv + 1] = absolute(args.path or vim.fn.getcwd())
254 vim.system(argv, { text = true }, function(result)
255 -- the callback runs in a fast event context: the reply touches buffers
256 vim.schedule(function()
257 local out = result.stdout or ''
258 if result.code == 1 and out == '' then return done { text = 'No matches.' } end
259 if result.code ~= 0 then
260 return done { text = (result.stderr or ''):gsub('%s+$', ''), error = true }
261 end
262 done { text = limited(vim.split(out:gsub('\n$', ''), '\n', { plain = true }), LIST_LIMIT, 'matches') }
263 end)
264 end)
265end
267local function save(args, done)
268 local saved = {}
269 for _, path in ipairs(args.paths) do
270 local buffer, name = load(path)
271 vim.fn.mkdir(vim.fs.dirname(name), 'p')
272 vim.api.nvim_buf_call(buffer, function() vim.cmd('silent write!') end)
273 saved[#saved + 1] = relative(name)
274 end
275 done { text = 'Saved ' .. table.concat(saved, ', ') .. '.' }
276end
278local function diagnostics(args, done)
279 local buffer = args.path and load(args.path) or nil
280 local lines = {}
281 for _, item in ipairs(vim.diagnostic.get(buffer)) do
282 lines[#lines + 1] = ('%s:%d:%d %s %s%s'):format(
283 relative(vim.api.nvim_buf_get_name(item.bufnr)),
284 item.lnum + 1,
285 item.col + 1,
286 vim.diagnostic.severity[item.severity],
287 item.message,
288 item.source and ' [' .. item.source .. ']' or ''
289 )
290 end
291 table.sort(lines)
292 done { text = #lines == 0 and 'No diagnostics.' or limited(lines, LIST_LIMIT, 'diagnostics') }
293end
295local tools = {
296 unsaved_text = unsaved_text,
297 set_text = set_text,
298 find = find_files,
299 search = search_files,
300 nvim_lua = nvim_lua,
301 save = save,
302 diagnostics = diagnostics,
303 lsp = require 'bugabinga.pivi.lsp' { load = load, relative = relative, limited = limited },
304}
306return function(name, args, reply, progress)
307 local finished = false
308 local function done(result)
309 if finished then return end
310 finished = true
311 for _, buffer in ipairs(unsaved()) do
312 vim.bo[buffer].buflisted = true
313 end
314 reply(true, result)
315 end
316 local ok, cancel = pcall(function()
317 if not tools[name] then error('Unknown tool: ' .. tostring(name), 0) end
318 return tools[name](args, done, progress)
319 end)
320 if not ok then
321 finished = true
322 reply(false, cancel)
323 end
324 return ok and cancel or nil
325end

neovim/lua/bugabinga/pivi/transport.lua

Added
new file mode 100644

+93 / −0 text lines

1local call = require 'bugabinga.pivi.tools'
2
3return function(argv, on_event)
4 local pending, sequence, tail, stderr, stopped = {}, 0, '', '', false
5 local cancels = {}
6 local job, broken
7
8 local function send(record)
9 if stopped or broken then return false end
10 local ok, bytes = pcall(vim.fn.chansend, job, vim.json.encode(record) .. '\n')
11 return ok and bytes > 0
12 end
14 local function reply(id, ok, result)
15 local record = { type = 'reply', id = id, ok = ok }
16 if ok then
17 record.result = result
18 else
19 record.error = tostring(result)
20 end
21 send(record)
22 end
24 local function receive(line)
25 local record = vim.json.decode(line, { luanil = { object = true, array = true } })
26 assert(type(record) == 'table' and type(record.type) == 'string', 'Expected a worker record with a type')
27 if record.type == 'response' then
28 local callback = pending[record.id]
29 pending[record.id] = nil
30 if callback then callback(record.ok, record.ok and record.result or record.error) end
31 elseif record.type == 'tool' then
32 local id = record.id
33 cancels[id] = call(record.name, record.args, function(ok, result)
34 cancels[id] = nil
35 reply(id, ok, result)
36 end, function(text) send({ type = 'progress', id = id, text = text }) end)
37 else
38 if record.type == 'cancel' and cancels[record.id] then cancels[record.id]() end
39 on_event(record)
40 end
41 end
43 job = vim.fn.jobstart(argv, {
44 on_stdout = function(_, data)
45 data[1] = tail .. data[1]
46 tail = table.remove(data)
47 for _, line in ipairs(data) do
48 if broken then break end
49 if line ~= '' then
50 local ok, failure = pcall(receive, line)
51 if not ok then
52 broken = 'Cannot process worker message: ' .. tostring(failure)
53 vim.fn.jobstop(job)
54 end
55 end
56 end
57 end,
58 on_stderr = function(_, data) stderr = (stderr .. table.concat(data, '\n')):sub(-8192) end,
59 on_exit = function(_, code)
60 stopped = true
61 if not broken and tail ~= '' then broken = 'Worker disconnected with an incomplete JSONL record.' end
62 if broken then stderr = broken .. '\n' .. stderr end
63 for _, cancel in pairs(cancels) do
64 cancel()
65 end
66 local failed = pending
67 pending = {}
68 for _, callback in pairs(failed) do
69 callback(false, 'Pivi worker exited (' .. code .. '). ' .. stderr)
70 end
71 on_event({ type = 'exit', code = code, error = stderr, protocol_error = broken ~= nil })
72 end,
73 })
74 if job <= 0 then error('Cannot start pivi worker: ' .. argv[1]) end
76 return {
77 reply = reply,
78 request = function(method, params, callback)
79 sequence = sequence + 1
80 pending[sequence] = callback
81 if not send({ id = sequence, method = method, params = params }) then
82 pending[sequence] = nil
83 callback(false, 'Pivi worker is not connected.')
84 end
85 end,
86 close = function()
87 if stopped then return end
88 pcall(vim.fn.chanclose, job, 'stdin')
89 if not vim.wait(2000, function() return stopped end, 10) then vim.fn.jobstop(job) end
90 end,
91 running = function() return not stopped and not broken end,
92 }
93end

neovim/lua/bugabinga/pivi/view.lua

Added
new file mode 100644

+992 / −0 text lines

1local namespace = vim.api.nvim_create_namespace('pivi')
2local HIGHLIGHT = {
3 message = 'PiviHeading',
4 user = 'PiviUserHeading',
5 assistant = 'PiviAssistantHeading',
6 detail = 'PiviTool',
7 error = 'PiviError',
8}
9local ACTIONS = {
10 { key = '?', name = 'help', text = 'Contextual binding help' },
11 { key = 'd', name = 'toggle', text = 'Toggle conversation / draft' },
12 { key = 'a', name = 'actions', text = 'Actions / attachments' },
13 { key = 'o', name = 'inspect', text = 'Inspect entry / attachment' },
14 { key = 'x', name = 'abort', text = 'Stop agent work' },
15 { key = 'r', name = 'review', text = 'Review unsaved changes' },
16 { key = 'f', name = 'fork', text = 'Fork at entry', zone = 'entry' },
17 { key = 's', name = 'submit', text = 'Submit idle draft', zone = 'draft', when = 'idle' },
18 { key = 't', name = 'steer', text = 'Steer active run', zone = 'draft', when = 'busy' },
19 { key = 'u', name = 'followUp', text = 'Queue follow-up', zone = 'draft', when = 'busy' },
20}
21local BODY = {
22 nvim_lua = { 'code', 'lua' },
23 codemode = { 'code', 'javascript' },
24 write = { 'content', '' },
25}
26local USER_TITLE = { ['pi.compaction'] = 'compacted', ['pivi.interrupted'] = 'stopped by you' }
27local FAILURE = {
28 model_error = 'model response failed',
29 no_model = 'model unavailable',
30 faulted = 'agent runtime failed',
31 orphaned = 'task unavailable',
32 interrupted = 'response interrupted',
33 restart_limit = 'restart limit reached',
34 nothing_to_answer = 'nothing to continue',
35 turn_limit = 'tool round limit reached',
36 reset = 'conversation reset',
37 aborted = 'stopped',
38}
39local states = {}
40local range_at, render
41local function prefix()
42 return vim.g.pivi_prefix or '<leader>p'
43end
45local function shown(key)
46 return vim.fn.keytrans(vim.keycode(prefix() .. key))
47end
49for name, link in pairs({
50 PiviUser = 'NormalFloat',
51 PiviUserHeading = 'Question',
52 PiviAssistant = 'Visual',
53 PiviAssistantHeading = 'Title',
54 PiviHeading = 'Title',
55 PiviTool = 'NonText',
56 PiviCode = 'ColorColumn',
57 PiviError = 'ErrorMsg',
58}) do
59 vim.api.nvim_set_hl(0, name, { link = link, default = true })
60end
62local function split(text)
63 return vim.split(tostring(text or ''), '\n', { plain = true })
64end
66local function draft(state)
67 return table.concat(vim.api.nvim_buf_get_lines(state.draft_buffer, 0, -1, false), '\n')
68end
70local function set_draft(state, text)
71 vim.api.nvim_buf_set_lines(state.draft_buffer, 0, -1, false, split(text))
72 if state.save_draft then state.save_draft() end
73end
75local function text_of(content)
76 if type(content) == 'string' then return content end
77 local parts = {}
78 for _, part in ipairs(content or {}) do
79 parts[#parts + 1] = part.text or '[image]'
80 end
81 return table.concat(parts, '\n')
82end
84local function span(ms)
85 if ms < 1000 then return ms .. 'ms' end
86 local seconds = math.floor(ms / 1000)
87 return seconds < 60 and seconds .. 's' or ('%dm%02ds'):format(seconds / 60, seconds % 60)
88end
90local function section(lines, title, text, language)
91 if title ~= '' then lines[#lines + 1] = title end
92 if not language then return vim.list_extend(lines, split(text)) end
93 local width = 3
94 for run in tostring(text):gmatch('`+') do
95 width = math.max(width, #run + 1)
96 end
97 local fence = string.rep('`', width)
98 lines[#lines + 1] = fence .. language
99 vim.list_extend(lines, split(text))
100 lines[#lines + 1] = fence
101end
103-- the first line of a folded body, so a closed fold still shows what it hides
104local function block(out, title, text, entry, kind, language)
105 local lines = out.lines
106 local range = { first = out.offset + #lines + 1, width = #title, entry = entry, kind = kind, turn = out.turn }
107 section(lines, title, text, language)
108 lines[#lines + 1] = ''
109 range.last = out.offset + #lines
110 out.ranges[#out.ranges + 1] = range
111 return range
112end
114-- json arrives as one long line: pretty print it, so the transcript can be read
115local function pretty_json(text)
116 local trimmed = vim.trim(text)
117 if trimmed:sub(1, 1) ~= '{' and trimmed:sub(1, 1) ~= '[' then return nil end
118 local ok, value = pcall(vim.json.decode, trimmed)
119 if not ok or type(value) ~= 'table' then return nil end
120 local function render(node, depth)
121 if type(node) ~= 'table' then
122 -- the strings are shown as they are: a decoded newline stays a newline
123 if type(node) == 'string' then return node end
124 return tostring(node)
125 end
126 local keys = vim.tbl_keys(node)
127 table.sort(keys)
128 if #keys == 0 then return '{}' end
129 local list = #keys == #node and keys[1] == 1
130 local parts = {}
131 for _, key in ipairs(keys) do
132 parts[#parts+1] = list and render(node[key], depth + 1) or ('%s: %s'):format(vim.json.encode(key), render(node[key], depth + 1))
133 end
134 local indent = (' '):rep(depth + 1)
135 return (list and '[\n' or '{\n') .. indent .. table.concat(parts, ',\n' .. indent) .. '\n' .. (' '):rep(depth)
136 .. (list and ']' or '}')
137 end
138 local rendered = render(value, 0)
139 return rendered
140end
142local function result_text(message)
143 local diff = message.toolName == 'edit' and type(message.details) == 'table' and message.details.diff
144 local text = text_of(message.content):gsub('<harness>.-</harness>', '')
145 if diff then return text .. '\n' .. diff, 'diff' end
146 local json = pretty_json(text)
147 if json then return json, 'json' end
148 return text, 'text'
149end
151local function language_of(path)
152 if type(path) ~= 'string' or path == '' then return nil end
153 local filetype = vim.filetype.match { filename = path }
154 if not filetype or filetype == '' then return nil end
155 return vim.treesitter.language.get_lang(filetype) or filetype
156end
158-- agent internals never enter the transcript: they are collected per entry and
159-- stay reachable through inspect
160local function tool_call(out, part, entry, result)
161 local args = part.arguments
162 local subject = args.path or args.command or args.pattern or args.code
163 local title = 'tool: ' .. part.name
164 if type(subject) == 'string' then
165 local relative = vim.fn.fnamemodify(vim.trim(subject:match('^[^\n]*')), ':.')
166 local head = vim.fn.strcharpart(relative, 0, 80)
167 title = title .. ' ' .. head .. (vim.fn.strchars(head) < vim.fn.strchars(relative) and '…' or '')
168 end
169 local turn = out.turn
170 turn.tools = (turn.tools or 0) + 1
171 local lines = { title, pretty_json(vim.json.encode(args)) or vim.json.encode(args) }
172 if result then
173 local text = select(1, result_text(result))
174 lines[#lines + 1] = (result.isError and 'error: ' or 'result: ') .. text
175 if result.isError then
176 turn.failed = (turn.failed or 0) + 1
177 turn.failed_name = turn.failed_name or part.name
178 end
179 if result.timestamp then turn.finish = result.timestamp end
180 end
181 lines[#lines + 1] = ''
182 local hidden = out.hidden[entry]
183 if not hidden then
184 hidden = {}
185 out.hidden[entry] = hidden
186 end
187 vim.list_extend(hidden, lines)
188end
189local function user_block(out, title, text, entry, turn)
190 -- the editor context is sent to the model, but it is not part of the
191 -- conversation the person reads
192 local context = text:match('^%[editor: [^\n]*%]\n')
193 if context then text = text:sub(#context + 1) end
194 return block(out, title, text, entry, 'user')
195end
197local function committed(items)
198 local out = { lines = {}, ranges = {}, hidden = {}, offset = 0, turn = {} }
199 local results, paired = {}, {}
200 for _, item in ipairs(items) do
201 for _, message in ipairs(item.entry and item.entry.model or {}) do
202 if message.role == 'toolResult' and message.toolCallId then results[message.toolCallId] = message end
203 end
204 end
205 -- one quiet line where the agent worked: what it did, how long, what it cost
206 local function status_line(out, entry)
207 local turn = out.turn
208 if turn.statused or not (turn.tools or turn.thoughts or turn.failed) then return end
209 turn.statused = true
210 local parts = { '⟳' }
211 if turn.tools then parts[#parts + 1] = turn.tools .. ' tools' end
212 if turn.thoughts then parts[#parts + 1] = turn.thoughts .. ' thoughts' end
213 if turn.start and turn.finish then parts[#parts + 1] = span(turn.finish - turn.start) end
214 if (turn.cost or 0) > 0 then parts[#parts + 1] = ('$%.3f'):format(turn.cost) end
215 if turn.failed then
216 parts[#parts + 1] = turn.failed .. ' failed'
217 if turn.failed_name then parts[#parts + 1] = '(' .. turn.failed_name .. ')' end
218 end
219 block(out, table.concat(parts, ' '), '', entry, 'status')
220 end
221 for _, item in ipairs(items) do
222 local entry = item.entry
223 if not entry then
224 local hint = item.kind == 'earlier' and '[Earlier history: :Pivi earlier]' or '[Entries not loaded]'
225 vim.list_extend(out.lines, { hint, '' })
226 end
227 for _, message in ipairs(item.entry and item.entry.model or {}) do
228 if message.role == 'user' then
229 local title = USER_TITLE[entry.kind]
230 if entry.kind == 'pivi.interrupted' then
231 block(out, title, '', entry.id, 'message')
232 elseif title then
233 block(out, title, text_of(message.content), entry.id, 'detail')
234 else
235 out.turn = { start = message.timestamp }
237 user_block(out, '# you', text_of(message.content), entry.id, out.turn)
239 end
240 elseif message.role == 'toolResult' and not paired[message.toolCallId] then
241 local text = select(1, result_text(message))
242 local lines = { (message.isError and 'error: ' or 'result: ') .. message.toolName, text, '' }
243 local hidden = out.hidden[entry.id]
244 if not hidden then
245 hidden = {}
246 out.hidden[entry.id] = hidden
247 end
248 vim.list_extend(hidden, lines)
249 elseif message.role == 'assistant' then
250 out.last_error = message.stopReason == 'error' and message.errorMessage or nil
251 local turn = out.turn
252 local final = message.stopReason ~= 'error'
253 and message.stopReason ~= 'aborted'
254 and not vim.iter(message.content):any(function(part) return part.type == 'toolCall' end)
255 turn.cost = (turn.cost or 0) + (vim.tbl_get(message, 'usage', 'cost', 'total') or 0)
256 if message.timestamp then turn.finish = message.timestamp + (message.durationMs or 0) end
257 for _, part in ipairs(message.content) do
258 if part.type == 'text' and part.text ~= '' then
259 local turn_titled = turn.titled
260 local title = not turn_titled and '# assistant'
261 or message.stopReason == 'aborted' and 'partial response (interrupted)'
262 or message.stopReason == 'error' and 'partial response (failed)'
263 or ''
264 turn.titled = true
265 if final then status_line(out, entry.id) end
266 block(out, title, part.text, entry.id, 'assistant')
267 elseif part.type == 'thinking' then
268 turn.thoughts = (turn.thoughts or 0) + 1
269 elseif part.type == 'toolCall' then
270 if part.id then paired[part.id] = true end
271 tool_call(out, part, entry.id, results[part.id])
272 end
273 end
274 if message.stopReason == 'error' then
275 turn.failed = (turn.failed or 0) + 1
276 block(
277 out,
278 'model attempt failed',
279 message.errorMessage or 'Provider returned no error detail.',
280 entry.id,
281 'error',
282 'text'
283 )
284 end
285 end
286 end
287 end
288 return out
289end
291local function uncommitted(docs, offset, paused, last_error, started)
292 local out = { lines = {}, ranges = {}, offset = offset, turn = {} }
293 local live = docs['pi.live']
294 local partial = live.generation and live.generation.message
295 local content = partial and partial.content or {}
296 local final = not vim.iter(content):any(function(part) return part.type == 'toolCall' end)
297 -- one live line in the tail: the transcript must not be dead air while work runs
298 local running = vim.iter(live.tools or {}):find(function(tool) return tool.status ~= 'done' end)
299 if running and not paused then
300 local so_far = #(live.tools or {})
301 local clock = started and span(vim.uv.now() - started) or ''
302 block(out, ('⟳ %d tools · %s · %s'):format(so_far, running.name, clock), '', nil, 'status')
303 end
304 local titled = false
305 for _, part in ipairs(content) do
306 if part.type == 'text' and part.text ~= '' then
307 -- one turn reads as one assistant message: the first part carries the title
308 local title = paused and 'partial response (suspended)' or not titled and '# assistant' or ''
309 titled = true
310 block(out, title, part.text, nil, 'assistant')
311 elseif part.type == 'thinking' then
312 -- the model's scratchpad stays out of the transcript
313 out.turn.thoughts = (out.turn.thoughts or 0) + 1
314 end
315 end
316 if paused then
317 block(
318 out,
319 'work suspended',
320 'No work is running. :Pivi resume restarts retained tasks; :Pivi stop cancels them.\n'
321 .. 'Review existing edits before resuming.',
322 nil,
323 'message'
324 )
325 end
326 local retry = not paused and live.generation and live.generation.retry
327 if retry then
328 block(out, 'waiting to retry', retry.error, nil, 'error', 'text')
329 block(out, '', 'Automatic retry scheduled by provider runtime. :Pivi stop cancels waiting.', nil, 'message')
330 end
331 local failure = live.runFailure
332 if failure then
333 local title = FAILURE[failure.reason] or 'run stopped: ' .. failure.reason
334 local detail = failure.detail ~= last_error and failure.detail or nil
335 block(out, title, detail or '', nil, failure.reason == 'aborted' and 'message' or 'error', detail and 'text' or nil)
336 if failure.reason ~= 'aborted' then
337 block(
338 out,
339 '',
340 'No automatic replay. Check the error, then :Pivi login, :Pivi model, or :Pivi continue.\n'
341 .. 'Existing edits remain in buffers; :Pivi review before continuing.',
342 nil,
343 'message'
344 )
345 end
346 end
347 if live.compactionFailure then
348 block(out, 'compaction failed', live.compactionFailure.error, nil, 'error', 'text')
349 block(out, '', 'History retained. Resolve the error, then :Pivi compact to try again.', nil, 'message')
350 end
351 for _, item in ipairs(docs['pi.inbox'] and docs['pi.inbox'].items or {}) do
352 if item.content then user_block(out, 'queued: ' .. item.mode, text_of(item.content), nil, out.turn) end
353 end
354 return out
355end
357local function splice(buffer, from, to, lines)
358 local old = vim.api.nvim_buf_get_lines(buffer, from, to, false)
359 local first, old_last, new_last = 1, #old, #lines
360 while first <= old_last and first <= new_last and old[first] == lines[first] do
361 first = first + 1
362 end
363 while old_last >= first and new_last >= first and old[old_last] == lines[new_last] do
364 old_last, new_last = old_last - 1, new_last - 1
365 end
366 if first > old_last and first > new_last then return end
367 vim.bo[buffer].modifiable = true
368 vim.api.nvim_buf_set_lines(buffer, from + first - 1, from + old_last, false, vim.list_slice(lines, first, new_last))
369 vim.bo[buffer].modifiable = false
370 return from + first, old_last - first + 1, new_last - first + 1
371end
373local function adorn(buffer, range)
374 local start = range.first - (range.width == 0 and 1 or 0)
375 local lines = vim.api.nvim_buf_get_lines(buffer, start, range.last, false)
376 local fence, index = nil, 1
377 while index <= #lines do
378 local line = lines[index]
379 local row = start + index - 1
380 local run = line:match('^%s*(```+)') or line:match('^%s*(~~~+)')
381 if fence or run then
382 vim.api.nvim_buf_set_extmark(buffer, namespace, row, 0, { line_hl_group = 'PiviCode', priority = 100 })
383 if not fence then
384 fence = run
385 elseif run and run:sub(1, 1) == fence:sub(1, 1) and #run >= #fence and line:match('^%s*[`~]+%s*$') then
386 fence = nil
387 end
388 end
389 index = index + 1
390 end
391end
393local function decorate(state, groups, changed)
394 local buffer = state.buffer
395 local clear_from = changed
396 for _, ranges in ipairs(groups) do
397 for _, range in ipairs(ranges) do
398 if range.last >= changed then
399 if clear_from then
400 vim.api.nvim_buf_clear_namespace(buffer, namespace, math.min(clear_from, range.first) - 1, -1)
401 clear_from = nil
402 end
403 local row = range.first - 1
404 local line = vim.api.nvim_buf_get_lines(buffer, row, row + 1, false)[1] or ''
405 vim.api.nvim_buf_set_extmark(
406 buffer,
407 namespace,
408 row,
409 0,
410 { end_col = math.min(range.width, #line), hl_group = HIGHLIGHT[range.kind] }
411 )
412 if range.kind == 'user' then
413 local region = { end_row = range.last - 1, hl_group = 'PiviUser', hl_eol = true, priority = 90 }
414 vim.api.nvim_buf_set_extmark(buffer, namespace, row, 0, region)
415 local note = vim.api.nvim_buf_get_lines(buffer, row + 1, row + 2, false)[1] or ''
416 if note:match('^%[editor: ') then
417 vim.api.nvim_buf_set_extmark(buffer, namespace, row + 1, 0, { end_col = #note, hl_group = 'PiviTool' })
418 end
419 elseif range.kind == 'assistant' then
420 local region = { end_row = range.last - 1, hl_group = 'PiviAssistant', hl_eol = true, priority = 90 }
421 vim.api.nvim_buf_set_extmark(buffer, namespace, row, 0, region)
422 adorn(buffer, range)
423 elseif range.kind == 'message' then
424 adorn(buffer, range)
425 end
426 end
427 end
428 end
429 if clear_from then vim.api.nvim_buf_clear_namespace(buffer, namespace, clear_from - 1, -1) end
430end
432local function winbar(state)
433 local windows = {
434 [state.buffer] = vim.fn.win_findbuf(state.buffer),
435 [state.draft_buffer] = vim.fn.win_findbuf(state.draft_buffer),
436 }
437 if #windows[state.buffer] == 0 and #windows[state.draft_buffer] == 0 then return end
438 local labels = vim.tbl_map(function(attachment) return '+ ' .. attachment.label end, state.attachments)
439 local unsaved = 0
440 for _, buffer in ipairs(vim.api.nvim_list_bufs()) do
441 if vim.bo[buffer].modified and vim.bo[buffer].buftype == '' then unsaved = unsaved + 1 end
442 end
443 -- one clock for the whole turn: the status, then the time, then the activity
444 local elapsed = state.started and span(vim.uv.now() - state.started) or nil
445 local activity = state.activity or (state.busy and 'working' or nil)
446 local busy_status = state.submitting and 'sending'
447 or state.status .. (elapsed and ' ' .. elapsed or '') .. (activity and ' · ' .. activity or '')
448 local status = state.submitting and 'sending' or state.status
449 local model = state.model == 'no model' and 'loading models…' or state.model
450 local retry = not state.paused and state.view and vim.tbl_get(state.view.docs, 'pi.live', 'generation', 'retry')
451 if retry then
452 local seconds = math.max(0, math.ceil((retry.at - vim.uv.gettimeofday() * 1000) / 1000))
453 busy_status = 'retry in ' .. seconds .. 's'
454 status = busy_status
455 end
456 local conversation = { 'pivi', busy_status, model }
457 if (state.cost_total or 0) >= 0.01 then conversation[#conversation + 1] = ('$%.2f'):format(state.cost_total) end
458 conversation[#conversation + 1] = unsaved > 0 and unsaved .. ' unsaved' or nil
459 local hint = state.status == 'disconnected' and ':Pivi reconnect'
460 or state.busy and 'CR interrupt+send · C-J queue'
461 or shown('?') .. ' help'
462 local queued = state.view and #(vim.tbl_get(state.view.docs, 'pi.inbox', 'items') or {}) > 0
463 local draft_ready = vim.api.nvim_buf_is_valid(state.draft_buffer)
464 and not vim.iter(vim.api.nvim_buf_get_lines(state.draft_buffer, 0, -1, false)):all(function(l) return l:match('^%s*$') end)
465 for buffer, parts in pairs({
466 [state.buffer] = conversation,
467 [state.draft_buffer] = {
468 'pivi draft',
469 busy_status,
470 model,
471 state.busy and (queued and 'queued · C-J after this turn' or 'CR interrupts+send · C-J after this turn')
472 or draft_ready and 'draft ready · CR sends'
473 or nil,
474 unpack(labels),
475 },
476 }) do
477 for _, window in ipairs(windows[buffer]) do
478 local visible = vim.list_slice(parts)
479 if buffer == state.buffer then
480 local position = state.windows[window]
481 visible[2] = visible[2] .. ' · ' .. (position and position.following and 'following' or 'reading')
482 end
483 local available = vim.api.nvim_win_get_width(window) - vim.fn.strdisplaywidth(hint) - 3
484 while #visible > 2 and vim.fn.strdisplaywidth(table.concat(visible, ' · ')) > available do
485 table.remove(visible, 3)
486 end
487 local text = (table.concat(visible, ' · ') .. ' %= ' .. hint):gsub('%%', '%%%%'):gsub('%%%%=', '%%=')
488 if vim.wo[window][0].winbar ~= text then vim.wo[window][0].winbar = text end
489 end
490 end
491end
493-- the view of a window, read without switching to it: switching windows marks
494-- every window for a full redraw, which flickers while the transcript streams.
495local function position(window)
496 local cursor = vim.api.nvim_win_get_cursor(window)
497 local info = vim.fn.getwininfo(window)[1]
498 if not info then return { lnum = cursor[1], col = cursor[2], topline = cursor[1], leftcol = 0, curswant = cursor[2] } end
499 return {
500 lnum = cursor[1],
501 col = cursor[2],
502 coladd = 0,
503 curswant = cursor[2],
504 topline = info.topline,
505 leftcol = info.leftcol or 0,
506 skipcol = 0,
507 }
508end
510local function observe(state, window)
511 local current = position(window)
512 local record = state.windows[window] or { following = state.view == nil }
513 if
514 record.view
515 and (
516 record.view.lnum ~= current.lnum
517 or record.view.col ~= current.col
518 or record.input and not vim.deep_equal(record.view, current)
519 )
520 then
521 record.following = false
522 end
523 record.view, record.input = current, false
524 state.windows[window] = record
525 return record
526end
528local function follow(state, window)
529 window = window or vim.api.nvim_get_current_win()
530 if not vim.api.nvim_win_is_valid(window) or vim.api.nvim_win_get_buf(window) ~= state.buffer then return end
531 local record = observe(state, window)
532 local adjusting = state.adjusting
533 state.adjusting = true
534 local last = vim.api.nvim_buf_line_count(state.buffer)
535 -- touching another window while the user types moves the insert cursor away
536 if window ~= vim.api.nvim_get_current_win() and vim.api.nvim_get_mode().mode:match('^i') then
537 state.adjusting = adjusting
538 return
539 end
540 record.following = true
541 vim.api.nvim_win_set_cursor(window, { last, 0 })
542 state.adjusting = adjusting
543 record.view = position(window)
544 if not state.adjusting then winbar(state) end
545end
547local function focus_conversation(state)
548 local window = vim.fn.win_findbuf(state.buffer)[1]
549 if window and window ~= vim.api.nvim_get_current_win() then
550 vim.api.nvim_set_current_win(window)
551 else
552 vim.api.nvim_set_current_buf(state.buffer)
553 end
554 follow(state, window)
555end
557local function draft_split(state)
558 local existing = vim.fn.win_findbuf(state.draft_buffer)[1]
559 if existing then
560 vim.api.nvim_set_current_win(existing)
561 return existing
562 end
563 local current = vim.api.nvim_get_current_win()
564 local window = vim.api.nvim_win_get_buf(current) == state.buffer and current or vim.fn.win_findbuf(state.buffer)[1]
565 if not window then
566 -- the conversation takes the current window, the draft opens below it
567 vim.api.nvim_set_current_buf(state.buffer)
568 window = vim.api.nvim_get_current_win()
569 end
570 local ratio = tonumber(vim.g.pivi_draft_split_ratio)
571 local vertical = ratio ~= nil and vim.api.nvim_win_get_width(window) > vim.api.nvim_win_get_height(window) * ratio
572 vim.api.nvim_win_call(window, function() vim.cmd(vertical and 'rightbelow vsplit' or 'rightbelow split') end)
573 local opened = vim.api.nvim_get_current_win()
574 vim.api.nvim_win_set_buf(opened, state.draft_buffer)
575 if vertical then
576 vim.api.nvim_win_set_width(opened, math.max(20, math.floor(vim.api.nvim_win_get_width(window) * 0.4)))
577 else
578 -- the draft is where the person composes: it never starves below three lines
579 vim.api.nvim_win_set_height(opened, math.max(3, math.min(12, math.floor(vim.api.nvim_win_get_height(window) * 0.35))))
580 end
581 vim.api.nvim_set_current_win(opened)
582 return opened
583end
585local function working(state, busy)
586 if busy == state.active then return end
587 state.active = busy
588 state.started = busy and vim.uv.now() or nil
589 pcall(vim.api.nvim_ui_send, busy and '\027]9;4;3\027\\' or '\027]9;4;0\027\\')
590 if state.timer then state.timer:close() end
591 state.timer = nil
592 if not busy then return end
593 state.timer = vim.uv.new_timer()
594 state.timer:start(1000, 1000, vim.schedule_wrap(function()
595 winbar(state)
596 -- while work runs, the live line in the transcript ticks too
597 if state.busy and state.view then render(state, state.view) end
598 end))
599end
601render = function(state, view)
602 if not vim.api.nvim_buf_is_valid(state.buffer) then return end
603 local fresh = view.items ~= nil
604 local base = fresh and committed(view.items) or state.committed
605 local current = vim.api.nvim_get_current_win()
606 local windows = {}
607 for _, window in ipairs(vim.fn.win_findbuf(state.buffer)) do
608 local record = observe(state, window)
609 windows[window] = { following = record.following, view = vim.deepcopy(record.view) }
610 end
611 local origin = state.committed.ranges[1]
612 if not fresh then view.items = state.view.items end
613 state.committed, state.view = base, view
614 local live = view.docs['pi.live']
615 local prepend
616 if origin and origin.entry and base.ranges[1] and base.ranges[1].entry ~= origin.entry then
617 for _, range in ipairs(base.ranges) do
618 if range.entry == origin.entry then
619 prepend = range.first - origin.first
620 break
621 end
622 end
623 end
624 state.paused = view.scheduling == 'paused' and (live.run ~= nil or #(live.compactions or {}) > 0)
625 local tail = uncommitted(view.docs, #base.lines, state.paused, base.last_error)
626 state.live = tail.ranges
627 local old_last = vim.api.nvim_buf_line_count(state.buffer)
628 local changed, removed, added
629 local committed_change, tail_change = { nil, 0, 0 }, { nil, 0, 0 }
630 if fresh then
631 -- the committed history only grows: splice it against the old committed
632 -- region, so a new entry does not rewrite the whole transcript
633 local first, gone, grew = splice(state.buffer, 0, #state.committed.lines, base.lines)
634 committed_change = { first, gone or 0, grew or 0 }
635 local tail_first, tail_gone, tail_grew = splice(state.buffer, #base.lines, -1, tail.lines)
636 tail_change = { tail_first, tail_gone or 0, tail_grew or 0 }
637 changed = first or tail_first
638 removed = (gone or 0) + (tail_gone or 0)
639 added = (grew or 0) + (tail_grew or 0)
640 else
641 local tail_first, tail_gone, tail_grew = splice(state.buffer, #base.lines, -1, tail.lines)
642 tail_change = { tail_first, tail_gone or 0, tail_grew or 0 }
643 changed, removed, added = tail_first, tail_gone, tail_grew
644 end
645 if changed then
646 decorate(state, fresh and { base.ranges, tail.ranges } or { tail.ranges }, changed)
647 local last = vim.api.nvim_buf_line_count(state.buffer)
648 local function shifted(row)
649 local function apply(change)
650 local first, gone, grew = change[1], change[2], change[3]
651 if not first then return row end
652 if row >= first + gone then
653 if not (gone == 0 and row == first and row == old_last) then return row + grew - gone end
654 return row
655 elseif row >= first then
656 return math.min(row, first + grew - 1)
657 end
658 return row
659 end
660 if prepend and row >= origin.first then return math.max(1, math.min(row + prepend, last)) end
661 row = apply(committed_change)
662 row = apply(tail_change)
663 return math.max(1, math.min(row, last))
664 end
665 state.adjusting = true
666 for window, saved in pairs(windows) do
667 if saved.following then
668 follow(state, window)
669 else
670 local old_top = saved.view.topline
671 saved.view.lnum = shifted(saved.view.lnum)
672 saved.view.topline = shifted(saved.view.topline)
673 if old_top > last then saved.view.topline = math.max(1, last - vim.api.nvim_win_get_height(window) + 1) end
674 if window == vim.api.nvim_get_current_win() then vim.fn.winrestview(saved.view) end
675 state.windows[window].view = position(window)
676 end
677 end
678 state.adjusting = false
679 end
681 state.busy = live.run ~= nil
682 local running = vim.iter(live.tools or {}):find(function(tool) return tool.status ~= 'done' end)
683 state.activity = running and running.name or (live.generation and 'thinking' or nil)
684 working(state, (state.busy or #(live.compactions or {}) > 0) and not state.paused)
685 local status = state.stopping and 'stopping'
686 or state.paused and 'suspended'
687 or #(live.compactions or {}) > 0 and 'compacting'
688 or live.generation and live.generation.retry and 'retrying'
689 or state.busy and 'working'
690 or live.runFailure and (live.runFailure.reason == 'aborted' and 'stopped' or 'failed')
691 or live.compactionFailure and 'compaction failed'
692 or 'idle'
693 local model = view.docs['pi.agent'].model
694 model = model and model.provider .. '/' .. model.modelId or 'no model'
695 local cost = 0
696 for _, usage in pairs(vim.tbl_get(view.docs, 'pi.usage', 'models') or {}) do
697 cost = cost + (vim.tbl_get(usage, 'cost', 'total') or 0)
698 end
699 local raw_cost = cost
700 cost = cost > 0 and ('$%.3f'):format(cost) or nil
701 state.status, state.model, state.cost, state.cost_total = status, model, cost, raw_cost
702 winbar(state)
703end
705range_at = function(state, row)
706 local ranges = state.committed.ranges
707 local low, high = 1, #ranges
708 while low <= high do
709 local middle = math.floor((low + high) / 2)
710 local range = ranges[middle]
711 if not range or not range.first or not range.last then break end
712 if row < range.first then
713 high = middle - 1
714 elseif row > range.last then
715 low = middle + 1
716 else
717 return range
718 end
719 end
720 -- the search gives up on a broken range: fall back to a plain walk
721 for _, range in ipairs(ranges) do
722 if range.first and range.last and row >= range.first and row <= range.last then return range end
723 end
724 for _, range in ipairs(state.live) do
725 if range.first and range.last and row >= range.first and row <= range.last then return range end
726 end
727end
729-- the fold expression can run while another window is current: fall back to
730-- the only conversation that is open
731local function context(state)
732 return vim.api.nvim_get_current_buf() == state.draft_buffer and 'draft' or 'entry'
733end
735local function entry(state)
736 if vim.api.nvim_get_current_buf() ~= state.buffer then return end
737 local range = range_at(state, vim.api.nvim_win_get_cursor(0)[1])
738 return range and range.entry
739end
741local function entry_lines(state, id)
742 -- the dialogue comes from the buffer, the agent internals from the hidden log
743 local lines = {}
744 for _, range in ipairs(state.committed.ranges) do
745 if range.entry == id then
746 vim.list_extend(lines, vim.api.nvim_buf_get_lines(state.buffer, range.first - 1, range.last, false))
747 end
748 end
749 vim.list_extend(lines, state.committed.hidden[id] or {})
750 return lines
751end
753local function scratch(kind, lines, filetype)
754 local buffer = vim.api.nvim_create_buf(false, true)
755 vim.api.nvim_buf_set_name(buffer, 'pivi://' .. kind .. '/' .. buffer)
756 vim.api.nvim_buf_set_lines(buffer, 0, -1, false, lines)
757 vim.bo[buffer].filetype = filetype or 'markdown'
758 vim.bo[buffer].bufhidden = 'wipe'
759 vim.bo[buffer].modifiable = false
760 return buffer
761end
763local function page(kind, lines, filetype)
764 local origin = vim.api.nvim_get_current_buf()
765 local buffer = scratch(kind, lines, filetype)
766 vim.api.nvim_set_current_buf(buffer)
767 vim.keymap.set('n', 'q', function() vim.api.nvim_set_current_buf(origin) end, { buffer = buffer })
768 return buffer
769end
771local function float(kind, lines, title)
772 local width = math.max(20, math.min(72, vim.o.columns - 4))
773 local height = math.max(1, math.min(#lines, vim.o.lines - 6))
774 local window = vim.api.nvim_open_win(scratch(kind, lines), true, {
775 relative = 'editor',
776 width = width,
777 height = height,
778 row = math.max(0, math.floor((vim.o.lines - height) / 2) - 1),
779 col = math.max(0, math.floor((vim.o.columns - width) / 2)),
780 style = 'minimal',
781 border = 'single',
782 title = title,
783 })
784 vim.wo[window].wrap = true
785 vim.wo[window].linebreak = true
786 return window
787end
789local function help(state, full)
790 local zone = context(state)
791 local lines = { '# Pivi bindings', '' }
792 for _, action in ipairs(ACTIONS) do
793 local applies = (not action.zone or action.zone == zone)
794 and (not action.when or (action.when == 'busy') == state.busy)
795 if full or applies then
796 lines[#lines + 1] = ('%-10s %s'):format(shown(action.key), action.text)
797 end
798 end
799 vim.list_extend(lines, { '', 'gO: outline ]] and [[: next / previous heading' })
800 vim.list_extend(lines, {
801 '',
802 'draft: <CR> send (steers while busy) · <C-CR>/<C-J> queue follow-up · Esc in the conversation stops work',
803 })
804 if zone == 'entry' then
805 lines[#lines + 1] = 'G: follow latest scroll / search / inspect: read without following'
806 end
807 if not full then lines[#lines + 1] = '?: all bindings' end
808 if full then
809 vim.list_extend(lines, { '', '## Commands', '' })
810 for _, name in ipairs(vim.fn.getcompletion('Pivi ', 'cmdline')) do
811 lines[#lines + 1] = ':Pivi ' .. name
812 end
813 return page('help', lines)
814 end
816 local window = float('keys', lines, 'pivi keys · ' .. zone)
817 local function close()
818 if vim.api.nvim_win_is_valid(window) then vim.api.nvim_win_close(window, true) end
819 end
820 vim.keymap.set('n', '<Esc>', close, { buffer = 0 })
821 vim.keymap.set('n', 'q', close, { buffer = 0 })
822 vim.keymap.set('n', '?', function()
823 close()
824 help(state, true)
825 end, { buffer = 0 })
826end
828local function create(id, dispatch)
829 local names = { buffer = 'pivi://' .. id .. '/conversation', draft_buffer = 'pivi://' .. id .. '/draft' }
830 local existing = states[vim.fn.bufnr(names.buffer)]
831 if existing and vim.api.nvim_buf_is_valid(existing.draft_buffer) then return existing end
833 local state = { attachments = {}, committed = { lines = {}, ranges = {} }, live = {}, windows = {}, busy = false }
835 state.status, state.model = 'starting', 'no model'
836 for field, name in pairs(names) do
837 local buffer = vim.fn.bufnr(name)
838 if buffer == -1 then
839 buffer = vim.api.nvim_create_buf(true, true)
840 vim.api.nvim_buf_set_name(buffer, name)
841 end
842 vim.bo[buffer].buftype = 'nofile'
843 vim.bo[buffer].bufhidden = 'hide'
844 vim.bo[buffer].swapfile = false
845 vim.bo[buffer].filetype = 'markdown'
846 pcall(vim.treesitter.start, buffer, 'markdown')
847 state[field] = buffer
848 vim.api.nvim_create_autocmd('BufWinEnter', {
849 buffer = buffer,
850 callback = function()
851 winbar(state)
852 vim.wo[0][0].wrap = true
853 vim.wo[0][0].linebreak = true
854 vim.wo[0][0].breakindent = true
855 vim.wo[0][0].breakindentopt = 'list:-1'
856 -- the transcript and the draft carry no signs: the column would only eat space
857 vim.wo[0][0].signcolumn = 'no'
858 if field == 'buffer' then
859 vim.wo[0][0].conceallevel = 2
860 vim.wo[0][0].concealcursor = ''
861 vim.wo[0][0].smoothscroll = true
862 end
863 local window = vim.api.nvim_get_current_win()
864 if state.windows[window] and state.windows[window].following then
865 follow(state, window)
866 else
867 observe(state, window)
868 end
869 end,
870 })
871 end
872 state.save_draft =
873 require('bugabinga.pivi.draft')(state.draft_buffer, vim.fn.stdpath('state') .. '/pivi/sessions/' .. id)
874 vim.bo[state.buffer].formatlistpat = [[^\s*\d\+[.)]\s\+\|^\s*[-*+]\s\+]]
875 vim.bo[state.buffer].undolevels = -1
876 vim.bo[state.buffer].modifiable = false
877 states[state.buffer] = state
878 local function navigation()
879 if state.adjusting then return end
880 local changes = vim.v.event.all or {}
881 local resized = (changes.width or 0) ~= 0 or (changes.height or 0) ~= 0
882 state.adjusting = true
883 for _, window in ipairs(vim.fn.win_findbuf(state.buffer)) do
884 if resized and state.windows[window] and state.windows[window].following then
885 follow(state, window)
886 else
887 observe(state, window)
888 end
889 end
890 state.adjusting = false
891 winbar(state)
892 end
893 local scroll = vim.api.nvim_create_autocmd('WinScrolled', { callback = navigation })
894 local closed = vim.api.nvim_create_autocmd('WinClosed', {
895 callback = function(event) state.windows[tonumber(event.match)] = nil end,
896 })
897 vim.api.nvim_create_autocmd('CursorMoved', { buffer = state.buffer, callback = navigation })
898 vim.api.nvim_create_autocmd('BufWipeout', {
899 buffer = state.buffer,
900 callback = function()
901 working(state, false)
902 vim.api.nvim_del_autocmd(scroll)
903 vim.api.nvim_del_autocmd(closed)
904 states[state.buffer] = nil
905 end,
906 })
908 for _, action in ipairs(ACTIONS) do
909 local targets = action.zone == 'draft' and { state.draft_buffer }
910 or action.zone == 'entry' and { state.buffer }
911 or { state.buffer, state.draft_buffer }
912 for _, buffer in ipairs(targets) do
913 vim.keymap.set('n', prefix() .. action.key, function() dispatch(state, action.name) end, {
914 buffer = buffer,
915 desc = 'pivi: ' .. action.text,
916 })
917 end
918 end
919 vim.keymap.set('n', '<CR>', function()
920 dispatch(state, state.busy and 'steer' or 'submit')
921 end, { buffer = state.draft_buffer, desc = 'pivi: send draft (submit, or steer while busy)' })
922 for _, key in ipairs({ '<C-CR>', '<C-J>' }) do
923 vim.keymap.set('n', key, function() dispatch(state, 'followUp') end, {
924 buffer = state.draft_buffer,
925 desc = 'pivi: queue follow-up',
926 })
927 end
928 vim.keymap.set('n', '<Esc>', function()
929 if state.busy then dispatch(state, 'abort') end
930 end, { buffer = state.buffer, desc = 'pivi: stop work while busy' })
931 return state
932end
934vim.on_key(function(key, typed)
935 local state = states[vim.api.nvim_get_current_buf()]
936 if not state or state.adjusting or typed == '' or vim.api.nvim_get_mode().mode ~= 'n' then return end
937 local window = vim.api.nvim_get_current_win()
938 local record = observe(state, window)
939 record.input, record.intent = true, (record.intent or 0) + 1
940 local intent = record.intent
941 if key == 'G' then
942 vim.schedule(function()
943 if
944 record.intent == intent
945 and vim.api.nvim_win_is_valid(window)
946 and vim.api.nvim_win_get_buf(window) == state.buffer
947 and vim.api.nvim_win_get_cursor(window)[1] == vim.api.nvim_buf_line_count(state.buffer)
948 then
949 follow(state, window)
950 end
951 end)
952 elseif key == 'z' or key == '/' or key == '?' or key == 'v' or key == 'V' or key == vim.keycode('<C-v>') then
953 observe(state, window).following = false
954 vim.schedule(function()
955 if vim.api.nvim_buf_is_valid(state.buffer) then winbar(state) end
956 end)
957 end
958end, navigation_namespace)
960return {
961 create = create,
962 prefix = prefix,
963 follow = follow,
964 focus_conversation = focus_conversation,
965 draft_split = draft_split,
966 render = render,
967 winbar = winbar,
968 disconnected = function(state, message)
969 working(state, false)
970 state.ready, state.busy, state.status = false, false, 'disconnected'
971 if message and vim.api.nvim_buf_is_valid(state.buffer) then
972 local offset = vim.api.nvim_buf_line_count(state.buffer)
973 local out = { lines = {}, ranges = {}, offset = offset, turn = {} }
974 block(out, 'worker disconnected', message, nil, 'error', 'text')
975 block(out, '', ':Pivi reconnects. Draft and unsaved buffers remain in this editor.', nil, 'message')
976 local changed = splice(state.buffer, offset, -1, out.lines)
977 vim.list_extend(state.live, out.ranges)
978 if changed then decorate(state, { out.ranges }, changed) end
979 end
980 winbar(state)
981 end,
982 draft = draft,
983 set_draft = set_draft,
984 context = context,
985 entry = entry,
986 entry_lines = entry_lines,
987 page = page,
988 float = float,
989 help = help,
990 fold = fold,
991 foldtext = foldtext,
992}

neovim/lua/bugabinga/sessions.lua

Modified

+12 / −0 text lines

3333local save_session_for_cwd = function ()
3434 local cwd = vim.uv.cwd()
3536 local session_save_path = to_session_path( cwd )
3637 vim.cmd.mksession { session_save_path, bang = true }
3738end
9798 command = load_any_session,
101auto 'load_session_on_start' {
102 description = 'Load the session for cwd on startup, when nvim starts without arguments',
103 events = 'VimEnter',
104 once = true,
105 command = function()
106 if vim.fn.argc() > 0 then return end
107 local session = encode(vim.uv.cwd())
108 if file_exists(vim.fs.normalize(sessions .. '/' .. session)) then load_session(session) end
109 end,
110}
100112auto 'save_session_on_exit' {
101113 description = 'Save current session for cwd, when leaving vim',
102114 events = 'VimLeavePre',

neovim/lua/bugabinga/statusline.lua

Modified

+9 / −4 text lines

88 git_branch = {}, -- per-directory cache
99 lsp_count = 0,
11local cached_cwd = vim.uv.cwd()
11local cached_cwd = assert(vim.uv.cwd())
1313-- Component functions
1414local function mode_component()
4848end
5050local function file_component()
51 local path = vim.fn.fnamemodify(vim.api.nvim_buf_get_name(0), ':~:.')
51 local name = vim.api.nvim_buf_get_name(0)
52 -- An empty name modifies into the working directory, which reads as if the
53 -- buffer were a file in it. A nameless buffer says so instead.
54 if name == '' then return icon.file .. ' [No Name]' end
56 local path = vim.fn.fnamemodify(name, ':~:.')
5257 if #path > 40 then
5358 path = '...' .. path:sub(-37)
5459 end
6469 timeout = 2000,
6570 }, function(result)
6671 if result.code == 0 then
67 local branch = result.stdout:gsub('\n', ''):sub(1, 15)
72 local branch = (result.stdout or ''):gsub('\n', ''):sub(1, 15)
6873 cache.git_branch[cwd] = icon.branch .. ' ' .. branch
6974 else
7075 cache.git_branch[cwd] = ''
136141 {
137142 events = 'DirChanged',
138143 command = function()
139 cached_cwd = vim.uv.cwd()
144 cached_cwd = assert(vim.uv.cwd())
140145 cache.git_branch = {}
141146 vim.cmd.redrawstatus()
142147 end,

neovim/lua/bugabinga/terminal.lua

Modified

+1 / −1 text lines

3131 col = center_col,
3232 row = center_row,
3333 style = 'minimal',
34 border = options.border or vim.g.border_style,
34 border = options.border,
3535 }
3636 local window = vim.api.nvim_open_win( buffer, true, window_settings )
3737 if buffer_created then

neovim/lua/bugabinga/treesitter.lua

Modified

+91 / −43 text lines

2121local treesitter = puk 'nvim-treesitter'
2222treesitter.setup {}
23treesitter.install { 'bash', 'nu' }
23treesitter.install { 'bash', 'nu', 'ini', 'toml', 'kdl' }
25-- TODO: in 0.12 check if this behaviour is builtin on vim.treesitter.start()
26-- if so, remove my stuff
25-- checked on 0.12: core only auto-starts treesitter via the bundled ftplugins
26-- ( $VIMRUNTIME/ftplugin/{lua,markdown,query,help}.lua ). we run with
27-- 'filetype plugin off', so those never load. this autocmd is required and
28-- also covers auto-installing missing parsers, which core never does.
2729auto 'look_for_treesitter_parser' {
2830 description = 'Try loading a treesitter parser, if available.',
2931 events = 'FileType',
3739 end
3840 local ok, _ = pcall( vim.treesitter.start, data.buf )
3941 if not ok then
42 -- resolve filetype to its treesitter language (sh -> bash, quadlet -> ini,
43 -- cucumber -> gherkin) before consulting the registry
44 local lang = vim.treesitter.language.get_lang( match ) or match
4045 local available = require 'nvim-treesitter.parsers'
41 local potential_parser = available[match]
46 local potential_parser = available[lang]
4247 if potential_parser then
43 vim.notify( 'Found potential treesitter parser for current filetype. Trying to install it. ' .. match )
44 local task = require 'nvim-treesitter.install'.install( match, { force = false } )
48 vim.notify( 'Found potential treesitter parser for current filetype. Trying to install it. ' .. lang )
49 local task = require 'nvim-treesitter.install'.install( lang, { force = false } )
4550 task:await( function ( err, success )
4651 if not success then
47 vim.notify( 'Failed to install treesitter parser: ' .. match, vim.log.levels.ERROR )
52 vim.notify( 'Failed to install treesitter parser: ' .. lang, vim.log.levels.ERROR )
4853 return
4954 end
50 vim.treesitter.start( data.buf )
55 vim.schedule( function ()
56 if pcall( vim.treesitter.start, data.buf ) then
57 vim.opt_local.foldmethod = 'expr'
58 vim.opt_local.foldexpr = 'v:lua.vim.treesitter.foldexpr()'
59 else
60 -- revision marker lied (e.g. .so wiped out of band): force rebuild once
61 local repair = require 'nvim-treesitter.install'.install( { lang }, { force = true } )
62 repair:await( function ( _, repaired )
63 if repaired then
64 vim.schedule( function()
65 pcall( vim.treesitter.start, data.buf )
66 vim.opt_local.foldmethod = 'expr'
67 vim.opt_local.foldexpr = 'v:lua.vim.treesitter.foldexpr()'
68 end )
69 end
70 end )
71 end
72 end )
5173 end )
5274 end
5375 return
5678 vim.opt_local.foldexpr = 'v:lua.vim.treesitter.foldexpr()'
5779 end,
59-- add asciidoc parser
60auto 'install_asciidoc_parser' {
61 description = 'Install asciidoc parser into nvim-treesitter',
62 events = 'User',
63 pattern = 'TSUpdate',
64 command = function ()
65 require 'nvim-treesitter.parsers'.asciidoc = {
66 install_info = {
67 url = 'https://github.com/cathaysia/tree-sitter-asciidoc',
68 revision = '5b6ccea9953b939959f447f7bfea699ae6968a99',
69 branch = 'master', -- only needed if different from default branch
70 location = 'tree-sitter-asciidoc',
71 generate = false,
72 generate_from_json = false,
73 queries = 'queries/asciidoc', -- also install queries from given directory
74 },
75 }
76 end,
77}
78-- add d2 parser
81-- add d2 parser; the .so and queries are installed out of band by puk (puk.parsers.nuon)
7982vim.treesitter.language.register( 'd2', 'd2' )
80auto 'install_d2_parser' {
81 description = 'Install d2 parser into nvim-treesitter',
82 events = 'User',
83 pattern = 'TSUpdate',
84 command = function ()
85 require 'nvim-treesitter.parsers'.d2 = {
86 install_info = {
87 url = 'https://github.com/ravsii/tree-sitter-d2',
88 revision = 'ffb66ce4c801a1e37ed145ebd5eca1ea8865e00f',
89 branch = 'main', -- only needed if different from default branch
90 generate = true,
91 generate_from_json = true,
92 queries = 'queries', -- also install queries from given directory
93 },
94 }
83-- systemd units and podman quadlets are INI-dialect files
84vim.treesitter.language.register( 'ini', 'systemd' )
85-- podman quadlet units get their own semantic filetype, same INI grammar
86vim.treesitter.language.register( 'ini', 'quadlet' )
87-- sh files are POSIX-ish, the bash grammar covers them
88vim.treesitter.language.register( 'bash', 'sh' )
89-- opentofu files are HCL
90vim.treesitter.language.register( 'hcl', { 'opentofu', 'opentofu-vars' } )
91-- nvim calls the gherkin filetype 'cucumber'
92vim.treesitter.language.register( 'gherkin', 'cucumber' )
94-- surface treesitter parse errors as ERROR diagnostics in every language;
95-- refreshed on change/insert-leave/save, so typing stays flicker-free
96local ts_errors = vim.api.nvim_create_namespace 'treesitter-errors'
97local function collect_errors( node, out )
98 if node:type() == 'ERROR' or node:missing() then
99 local lnum, col = node:range()
100 out[#out + 1] = { lnum = lnum, col = col, end_lnum = lnum, end_col = col, message = 'syntax error', severity = vim.diagnostic.severity.ERROR, source = 'treesitter' }
101 return
102 end
103 for child in node:iter_children() do
104 collect_errors( child, out )
105 end
106end
107local function show_ts_errors( args )
108 local ok, parser = pcall( vim.treesitter.get_parser, args.buf )
109 if not ok or not parser then return end
110 local trees = parser:parse()
111 if not trees then return end
112 local tree = trees[1]
113 if not tree then return end
114 local out = {}
115 local root = tree:root()
116 if not root then return end
117 collect_errors( root, out )
118 vim.diagnostic.set( ts_errors, args.buf, out )
119end
120auto 'treesitter_error_diagnostics' {
121 description = 'Report treesitter parse errors as ERROR diagnostics.',
122 events = { 'FileType', 'TextChanged', 'InsertLeave', 'BufWritePost' },
123 pattern = '*',
124 command = function( args )
125 vim.schedule( function() show_ts_errors( args ) end )
95126 end,
129-- this module loads deferred, so the startup file's FileType event has already
130-- passed: catch up on every loaded buffer once
131vim.schedule( function()
132 for _, buf in ipairs( vim.api.nvim_list_bufs() ) do
133 if vim.api.nvim_buf_is_loaded( buf ) then
134 show_ts_errors( { buf = buf } )
135 end
136 end
137end )
139-- runs out of band via puk post-install (headless nvim, editor closed):
140-- updates nvim-treesitter-managed parsers to the revisions pinned upstream.
141local function post_install()
142 require 'nvim-treesitter.install'.update():wait()
143end
98145_G.BugabingaTreesitter = {
99146 is_ignored = is_ignored,
147 post_install = post_install,
102150return BugabingaTreesitter

neovim/lua/bugabinga/winbar.lua

Modified

+1 / −1 text lines

2424puk.defer 'incline' ( function ( incline )
2525 incline.setup {
2626 ignore = {
27 filetypes = ignored.filetypes,
27 filetypes = vim.list_extend(vim.deepcopy(ignored.filetypes), { 'image' }),
2828 },
2929 debounce_threshold = { falling = 500, rising = 250 },
3030 window = {

neovim/lua/std/auto.lua

Modified

+1 / −1 text lines

9292 vim.api.nvim_create_autocmd(autocommand.events, {
9393 desc = autocommand.description,
9494 group = autocommand.buffer and nil or group,
95 buffer = autocommand.buffer,
95 buf = autocommand.buffer,
9696 pattern = autocommand.pattern,
9797 once = autocommand.once,
9898 command = command,

neovim/lua/std/cheatsheet.lua

Deleted
deleted file mode 100644

+0 / −51 text lines

1local categories = {
2 lsp = 'LSP',
3 fuzzy = 'FZF',
4 files = 'FILE',
5 terminal = 'TERM',
6 editing = 'EDIT',
7 search = 'FIND',
8 session = 'SESS',
9 diff = 'DIFF',
10 operator = 'OP',
11 fun = 'FUN',
12}
14local category_patterns = {
15 '^lsp: ', 'lsp',
16 '^fuzzy: ', 'fuzzy',
17 '^files: ', 'files',
18 '^terminal: ', 'terminal',
19 '^editing: ', 'editing',
20 '^search: ', 'search',
21 '^session: ', 'session',
22 '^diff: ', 'diff',
23 '^operator: ', 'operator',
24 '^fun: ', 'fun',
25}
27local get_category_icon = function(category)
28 return categories[category] or category:upper()
29end
31local parse_description = function(desc)
32 if not desc or desc == '' then
33 return 'general', '*no description*'
34 end
36 for i = 1, #category_patterns, 2 do
37 local pattern, category = category_patterns[i], category_patterns[i + 1]
38 if desc:match(pattern) then
39 return category, desc:gsub(pattern, '')
40 end
41 end
43 return 'general', desc
44end
46return {
47 categories = categories,
48 category_patterns = category_patterns,
49 get_category_icon = get_category_icon,
50 parse_description = parse_description,
51}

neovim/lua/std/commentstring.lua

Added
new file mode 100644

+83 / −0 text lines

1local commentstring = {
2 -- harvested from nvim 0.12 vim.filetype.get_option while ftplugin was still on.
3 -- these are the authoritative builtin values. edit freely.
4 bash = "# %s",
5 c = "// %s",
6 clojure = "; %s",
7 cmake = "# %s",
8 conf = "# %s",
9 cpp = "// %s",
10 css = "/* %s */",
11 dart = "// %s",
12 desktop = "# %s",
13 dockerfile = "# %s",
14 elixir = "# %s",
15 erlang = "% %s",
16 fish = "# %s",
17 gdscript = "# %s",
18 gitcommit = "# %s",
19 gitconfig = "; %s",
20 gleam = "// %s",
21 go = "// %s",
22 graphql = "# %s",
23 hcl = "# %s",
24 html = "<!-- %s -->",
25 java = "// %s",
26 javascript = "// %s",
27 javascriptreact = "// %s",
28 jsonc = "// %s",
29 julia = "# %s",
30 just = "# %s",
31 kotlin = "// %s",
32 lisp = "; %s",
33 lua = "-- %s",
34 make = "# %s",
35 markdown = "<!-- %s -->",
36 nim = "# %s",
37 nu = "# %s",
38 ocaml = "(* %s *)",
39 odin = "// %s",
40 perl = "# %s",
41 php = "/* %s */",
42 proto = "// %s",
43 python = "# %s",
44 qml = "// %s",
45 r = "# %s",
46 roc = "# %s",
47 ruby = "# %s",
48 rust = "// %s",
49 scala = "// %s",
50 scheme = "; %s",
51 scss = "// %s",
52 sh = "# %s",
53 sql = "-- %s",
54 swift = "// %s",
55 systemd = "; %s",
56 terraform = "# %s",
57 tex = "% %s",
58 tmux = "# %s",
59 toml = "# %s",
60 typescript = "// %s",
61 typescriptreact = "// %s",
62 v = "// %s",
63 vim = '"%s',
64 xml = "<!-- %s -->",
65 yaml = "# %s",
66 zig = "// %s",
68 -- nvim had no builtin commentstring for these. added by hand.
69 haskell = "-- %s",
70 ini = "; %s",
71 bibtex = "% %s",
73 -- your custom filetypes ( from options/filetypes.lua ). VERIFY these.
74 d2 = "# %s",
75 vfp = "* %s", -- Visual FoxPro line comment
76 gotmpl = "{{/* %s */}}",
77 opentofu = "# %s",
78 quadlet = "# %s",
79 shtml = "<!-- %s -->",
80 superhtml = "<!-- %s -->",
81}
83return commentstring

neovim/lua/std/const.lua

Modified

+3 / −1 text lines

1local executable = require 'std.executable'
2
13local uname = vim.uv.os_uname()
24local win32 = uname.sysname:match 'Win' and true or false
35local wsl = uname.release:match 'WSL2' and true or false
3739local function query_os_background()
3840 if win32 or wsl then
3941 return 'light'
40 elseif vim.fn.executable 'busctl' ~= 0 then
42 elseif executable 'busctl' then
4143 local cmd = {
4244 'busctl', '--user', '--expect-reply=true', 'call',
4345 'org.freedesktop.portal.Desktop',

neovim/lua/std/dbg.lua.bak

Deleted
deleted file mode 100644

+0 / −189 text lines

1local user_command = require 'std.user_command'
2local icon = require 'std.icon'
3
4local DBG_FILE = vim.fn.stdpath 'state' .. '/bugabinga_config_debug.jsonl'
5
6---Debug kinds and their mapped highlight groups and icons.
7---@type table<string,[string, string]>
8local DBG_KINDS = {
9 --TODO
10 DEBUG = {},
11 TRACE = {},
12 ERROR = {},
13}
15---@alias dbg_kind
16---| 'DEBUG' normal debug event -> use this, when logging debug information
17---| 'TRACE' function trace event -> use this, when tracing function call flow
18---| 'ERROR' error event -> use this, when logging unexpected events
20---Get context information from `debug.traceback()` and other `debug` functions.
21---Wwhen getting the stacktrace, we need to account for the function call graph inside this `dbg` module.
22---Either its: `callsite -> metatable -> print_debug -> print_debug_kind -> get_context`.
23---Or: `callsite -> print_debug_kind -> get_context`.
24---In both cases we are only interested in callsite to determine file name, the function name and line number.
25---
26---@return string filename The filename, the calling function resides in.
27---@return string function_name The name of the function, where `dbg` was called in.
28---@return integer line_number Line number the calling functions is invoking the `dbg` function at.
29local function get_context()
30 --TODO
31 local filename = nil
32 local function_name = nil
33 local line_number = nil
34 return filename, function_name, line_number
35end
37--- Encodes debug event to JSON
38--- @param event table<string, table, string, table, string, string, integer> debug event to log
39--- @return string json JSON-encoded debug event
40local function encode( event )
41 return vim.json.encode( event, {
42 escape_slash = true,
43 } )
44end
46--- Decodes debug event from JSON
47--- @param line string JSON-encoded debug event
48--- @return table<string, table, string, table, string, string, integer> event debug event to log
49local function decode( line )
50 return vim.json.decode( line, {
51 luanil = {
52 object = true,
53 array = true,
54 },
55 } )
56end
58--- Writes debug events to the debug file, one per line.
59---
60--- @see encode
61--- @param event table<string, table, string, table, string, string, integer> debug event to log
62local function write_to_debug_file( event )
63 local file, errmsg = io.open( DBG_FILE, 'a+' )
64 if not file then
65 error( 'Unable to open debug log file `' .. DBG_FILE .. '`: ' .. errmsg )
66 end
67 local json_line = encode( event )
68 file:write( json_line )
69 file:flush()
70 file:close()
71end
73---Replaces expressions inside the given `format`, by indexing into `user_data`.
74---
75---Resolve `format`, by replacing `{<expr>}` inside format string.
76---`<expr>` is used to index into `user_data`.
77---e.g.: `user_data = {a = 1, b = 2, c = 3}`
78---To get `b`: the format expression would be `{b}`.
79---`{b}` would be replaced by `2` in format string.
80---
81---e.g.: `user_data = {{a=1},{b=2},{c=3}}`
82---To index into nested structures, use numbers: `{2.b}`.
83---`{2.b}` would be replaced by `2` in format string.
84---Indexing is 1-based, as per usual in lua.
85---Values are converted by `vim.inspect` to strings.
86---
87---@see vim.inspect
88---
89---@param format string Message with optional "{}"-style expressions inside
90---@param data table Arbitrary data, that can be indexed into, to pick values for the `format` string
91---@return string formatted_message Message with format expressions resolved
92local function format_message( format, data )
93 local formatted_message
94 --TODO
95 return formatted_message
96end
98if vim.g.bugabinga_debug_mode == nil then
99 vim.g.bugabinga_debug_mode = false
100end
102local function is_debug_mode()
103 return vim.g.bugabinga_debug_mode
104end
106---Log debug message of particular kind.
107---@param kind dbg_kind kind of event
108---@param message string message format string
109---@param ... any arbitrary user data, that can be referenced in message format
110local function print_debug_kind( kind, message, ... )
111 if not is_debug_mode() then
112 return
113 end
114 local now = os.date '!*t'
115 local user_data = { ... }
116 local filename, function_name, line_number = get_context()
117 write_to_debug_file {
118 kind = kind,
119 date = now,
120 format = message,
121 data = user_data,
122 filename = filename,
123 fn = function_name,
124 line = line_number,
125 }
126end
128---Log a debug event.
129---@param message string message format string
130---@param ... any arbitrary user data, that can be referenced in message format
131local function print_debug( message, ... )
132 if not is_debug_mode() then
133 return
134 end
135 print_debug_kind( 'DEBUG', message, ... )
136end
138local function toggle_debug_mode()
139 vim.g.bugabinga_debug_mode = not vim.g.bugabinga_debug_mode
140 vim.notify( 'Toggled debug mode to ' .. tostring( is_debug_mode() ) )
141end
143--- Opens the debug file in a special buffer, that is not modifiable.
144--- It renders the debug events in a table with special functions:
145--- - filter by type
146--- - jump to location
147--- - colors and icons for different kinds
148--- Filters are a label, e.g. "Filter by kind: " plus a special region after it on one line in the buffer above the table.
149--- Typing in that region activates the filtering in the table.
150---
151--- Icons are shown as prefix to kind values in their cells: <icon> <KIND>.
152--- The table rows are highlighted according to kinds in `DBG_KINDS`.
153--- Note: table row can be multiline because of formatted messages. Highlighting needs to account for that.
154---
155--- Pressing enter while the cursor is on a table row, jumps to this events location.
156---
157--- Debug events are read and decoded from `DBG_FILE` and converted to a table of:
158--- Kind, Date, Message, Location
159---
160--- Kind -> debug event kind + icon
161--- Date -> human readable datetime in hosts timezone
162--- Message -> formatted message from format string and user data
163--- Locataion -> combined file name, function name and line number
164local function open_special_debug_buffer()
165 --TODO
166end
168--- Opens the file `DBG_FILE` in a normal neovim buffer
169local function open_raw_debug_file()
170 --TODO
171end
173user_command.Debug 'Toggle global vim config debug mode.' ( toggle_debug_mode )
174user_command.DebugOpen 'Open special buffer with debug events' ( open_special_debug_buffer )
175user_command.DebugOpenRaw 'Opens the JSON debug file in normal buffer' ( open_raw_debug_file )
177return setmetatable(
178 {
179 kind = print_debug_kind,
180 toggle = toggle_debug_mode,
181 get = is_debug_mode,
182 }, {
183 --TODO: refactor usages of this function in other code to new name
184 __call = print_debug,
185 __newindex = function ( ... )
186 error(
187 'Assignments are not supported for std.dbg.\n' .. vim.inspect( ... ), 2 )
188 end,
189 } )

neovim/lua/std/dbg/encode.lua

Deleted
deleted file mode 100644

+0 / −25 text lines

1---Encodes a debug event to JSON.
2---@param event table debug event
3---@return string json
4local function encode( event )
5 return vim.json.encode( event, {
6 escape_slash = true,
7 } )
8end
9
10---Decodes a JSON line into a debug event.
11---@param line string JSON string
12---@return table event
13local function decode( line )
14 return vim.json.decode( line, {
15 luanil = {
16 object = true,
17 array = true,
18 },
19 } )
20end
22return {
23 encode = encode,
24 decode = decode,
25}

neovim/lua/std/dbg/file.lua

Deleted
deleted file mode 100644

+0 / −125 text lines

1local encode = require 'std.dbg.encode'
2local decode = require 'std.dbg.encode'
3
4local DBG_FILE = vim.fn.stdpath 'state' .. '/bugabinga_config_debug.jsonl'
5
6---Returns the path to the debug log file.
7---@return string
8local function get_path()
9 return vim.g.bugabinga_debug_file_override or DBG_FILE
10end
12---Returns the filename, function name, and line number of the caller.
13---Skips all frames inside std/dbg/* modules.
14---@return string filename
15---@return string function_name
16---@return integer line_number
17local function get_context()
18 local level = 2
19 while true do
20 local info = debug.getinfo(level, 'Sln')
21 if not info then break end
22 local src = info.short_src or info.source
23 if src and not src:match 'std/dbg' and not src:match '@std/dbg' then
24 return src, info.name or '', info.currentline or 0
25 end
26 level = level + 1
27 end
28 return 'unknown', '', 0
29end
31---Appends a debug event as a JSON line to the debug file.
32---@param event table debug event
33---@param path string? override path
34local function write(event, path)
35 local file_path = path or DBG_FILE
36 local dir = vim.fs.dirname(file_path)
37 if dir and dir ~= '' then
38 vim.fn.mkdir(dir, 'p')
39 end
40 local file, errmsg = io.open(file_path, 'a')
41 if not file then
42 error('Unable to open debug log file `' .. file_path .. '`: ' .. tostring(errmsg))
43 end
44 local json_line = encode.encode(event)
45 file:write(json_line .. '\n')
46 file:flush()
47 file:close()
48end
50---Closes the open file descriptor. No-op with io.open.
51local function close_fd()
52end
54---Clears the debug log file by truncating it.
55local function clear_log()
56 local dir = vim.fs.dirname(DBG_FILE)
57 if dir and dir ~= '' then
58 vim.fn.mkdir(dir, 'p')
59 end
60 local file, errmsg = io.open(DBG_FILE, 'w')
61 if file then
62 file:close()
63 end
64end
66---Reads all debug events from a JSONL file.
67---@param path string? override path (defaults to DBG_FILE)
68---@return table[] list of decoded events
69local function read_all(path)
70 local file_path = path or DBG_FILE
71 local file = io.open(file_path, 'r')
72 if not file then
73 return {}
74 end
75 local events = {}
76 for line in file:lines() do
77 if line and line ~= '' then
78 local ok, event = pcall(decode.decode, line)
79 if ok and event then
80 table.insert(events, event)
81 end
82 end
83 end
84 file:close()
85 return events
86end
88---Reads only new events from the JSONL file, skipping the first `last_count` lines.
89---Use for incremental updates when tailing a growing file.
90---@param last_count number skip this many lines before reading new ones
91---@param path string? override path (defaults to DBG_FILE)
92---@return table[] new_events list of newly decoded events
93---@return number new_total total count of events in file after reading
94local function read_new(last_count, path)
95 local file_path = path or DBG_FILE
96 local file = io.open(file_path, 'r')
97 if not file then
98 return {}, 0
99 end
100 local new_events = {}
101 local current_count = 0
102 for line in file:lines() do
103 if line and line ~= '' then
104 current_count = current_count + 1
105 if current_count > last_count then
106 local ok, event = pcall(decode.decode, line)
107 if ok and event then
108 table.insert(new_events, event)
109 end
110 end
111 end
112 end
113 file:close()
114 return new_events, current_count
115end
117return {
118 get_path = get_path,
119 get_context = get_context,
120 write = write,
121 read_all = read_all,
122 read_new = read_new,
123 close_fd = close_fd,
124 clear_log = clear_log,
125}

neovim/lua/std/dbg/format.lua

Deleted
deleted file mode 100644

+0 / −275 text lines

1---Debug event format module.
2---Resolves {0} and {N} and {N.key...} placeholders against wrapped varargs.
3---
4---## Model
5---
6---All varargs are wrapped into `wrapped = {...}`. Every placeholder indexes into this.
7---
8---### Syntax: {0}, {N}, or {N.key.sub...}
9--- {0} -> vim.inspect(all data)
10--- {N} -> wrapped[N]
11--- {N.key} -> wrapped[N].key
12--- {N.1.key} -> wrapped[N][1].key (numeric into string)
13--- {N.["key"]} -> wrapped[N]["key"] (bracket = always string key)
14--- {N.["a.b"]} -> wrapped[N]["a.b"] (key containing dots)
15--- Mixed bare and bracket: {N.a.["x.y"].z} works as expected
16---
17---### Grammar (key segments after {N.})
18--- key_segment := bare_key | '[' quoted_string ']'
19--- bare_key := [^.[]+ (alphanumeric, underscores, etc.)
20--- quoted_string := '"' [^"]* '"' | "'" [^']* "'"
21--- Separator '.' between segments. No whitespace between segments.
22---
23---### Examples
24--- dbg('{0}', {a=1, b='bee'}) -> '{ a = 1, b = "bee" }'
25--- dbg('{1}', 'hello') -> 'hello'
26--- dbg('{2}', 'a', 'b') -> 'b'
27--- dbg('{1.name}', {name='hi'}) -> 'hi'
28--- dbg('{1.1}', {{'nested'}}) -> 'nested'
29--- dbg('{1.1.name}', {{name='nested'}}) -> 'nested'
30--- dbg('{2.1.jan.name}', {'x', {jan={name='jan'}}}) -> 'jan'
31--- dbg('{2.1.jan.age}', {'x', {age=39, {jan={name='jan',age=11}}}}) -> '11'
32--- dbg('{1.["a.b"]}', { {['a.b'] = 'dots'} }) -> 'dots'
33--- dbg('{1.["1"]}', { {['1'] = 'str', [1] = 'int'} }) -> 'str' (string key wins)
34--- dbg('{1.["function"]}', { {['function'] = 'kw'} }) -> 'kw'
35--- dbg('{1.["hello world"]}', { {['hello world'] = 'hw'} }) -> 'hw'
36--- dbg('{1.[""]}', { {[''] = 'empty'} }) -> 'empty'
37---
38---### Rules
39--- - {0} returns vim.inspect of all data; cannot be followed by keys
40--- - First key must be numeric (0 or the index into wrapped)
41--- - Subsequent bare keys are strings unless they parse as integers
42--- - Bracket keys (["key"]) are ALWAYS string keys — never parsed as numbers
43--- - This means {1.["2"]} accesses string key "2", while {1.2} accesses integer key 2
44--- - Indices out of range produce an error
45--- - Any nil result (missing index or missing chained key) produces an error
46--- - Table values are rendered via vim.inspect
47---
48---### Error Suggestions
49--- - Index off by 1-3: suggests correct index (e.g., {3} with 2 items suggests {2})
50--- - Wrong key name: suggests closest key using Levenshtein distance (threshold 2)
51---
52---@param format string format string with placeholders
53---@param data table varargs list packed as {...}
54---@return string formatted message
55---@see vim.inspect
57---Parses a key expression into segments.
58---Grammar:
59--- expression := key_segment ('.' key_segment)*
60--- key_segment := bare_key | '[' quoted_string ']'
61--- bare_key := [^.[]+
62--- quoted_string := '"' [^"]* '"' | "'" [^']* "'"
63---Returns array of { key = string|number, is_string = boolean }.
64---Bracket keys are always strings; bare keys are strings unless numeric.
65---@param inner string
66---@return table
67local function parse_keys(inner)
68 local keys = {}
69 local pos = 1
71 while pos <= #inner do
72 if inner:sub(pos, pos) == '.' then
73 pos = pos + 1
74 end
76 if pos > #inner then break end
78 local c = inner:sub(pos, pos)
79 if c == '[' then
80 pos = pos + 1
81 if pos > #inner then
82 error('parse error: unclosed bracket in {' .. inner .. '}')
83 end
85 local quote = inner:sub(pos, pos)
86 if quote ~= '"' and quote ~= "'" then
87 error('parse error: expected quote in {' .. inner .. '}')
88 end
89 pos = pos + 1
91 local key_start = pos
92 local quote_end = inner:find(quote, pos, true)
93 if not quote_end then
94 error('parse error: unclosed bracket in {' .. inner .. '}')
95 end
97 local key = inner:sub(key_start, quote_end - 1)
98 pos = quote_end + 1
100 if pos > #inner or inner:sub(pos, pos) ~= ']' then
101 error('parse error: expected ] in {' .. inner .. '}')
102 end
103 pos = pos + 1
105 keys[#keys + 1] = { key = key, is_string = true }
106 else
107 local key_start = pos
108 while pos <= #inner and inner:sub(pos, pos) ~= '.' and inner:sub(pos, pos) ~= '[' do
109 pos = pos + 1
110 end
111 local key = inner:sub(key_start, pos - 1)
112 if key == '' then
113 error('parse error: empty key in {' .. inner .. '}')
114 end
115 keys[#keys + 1] = { key = tonumber(key) or key, is_string = false }
116 end
117 end
119 return keys
120end
122---Computes Levenshtein edit distance between two strings.
123---Uses Wagner-Fischer dynamic programming algorithm.
124---@param a string first string
125---@param b string second string
126---@return number edit distance (0 = identical)
127local function levenshtein(a, b)
128 local m, n = #a, #b
129 if m == 0 then return n end
130 if n == 0 then return m end
132 local prev = {}
133 local curr = {}
134 for j = 0, n do
135 prev[j] = j
136 end
138 for i = 1, m do
139 curr[0] = i
140 for j = 1, n do
141 local cost = a:sub(i, i) == b:sub(j, j) and 0 or 1
142 curr[j] = math.min(prev[j] + 1, curr[j - 1] + 1, prev[j - 1] + cost)
143 end
144 prev, curr = curr, prev
145 end
147 return prev[n]
148end
150---Suggests a similar key from a table based on Levenshtein distance.
151---Only suggests keys within threshold distance (<= 2).
152---@param tbl table the table to search
153---@param wrong_key string the key that was not found
154---@return string? suggested key or nil if none close enough
155local function suggest_key(tbl, wrong_key)
156 if type(wrong_key) ~= 'string' then return nil end
157 local best_key, best_dist = nil, math.huge
158 for k in pairs(tbl) do
159 if type(k) == 'string' then
160 local d = levenshtein(k, wrong_key)
161 if d < best_dist then
162 best_key, best_dist = k, d
163 end
164 end
165 end
166 if best_dist <= 2 then return best_key end
167 return nil
168end
170local function format_message(format, data)
171 vim.validate('format', format, 'string')
172 vim.validate('data', data, 'table')
174 local data_len = #data
176 local result = {}
177 local pos = 1
179 while pos <= #format do
180 local startbrace, endbrace = format:find('%b{}', pos)
181 if not startbrace then
182 table.insert(result, format:sub(pos))
183 break
184 end
186 if startbrace > pos then
187 table.insert(result, format:sub(pos, startbrace - 1))
188 end
190 local match = format:sub(startbrace, endbrace)
191 local inner = match:match('^{%s*(.-)%s*}$')
193 local replacement
195 if not inner or inner == '' then
196 error('Empty {} is not allowed. Use {N} or {N.key...} syntax.')
197 else
198 local keys = parse_keys(inner)
200 local first_key_entry = keys[1]
201 local first_key = first_key_entry.key
203 if first_key_entry.is_string or type(first_key) ~= 'number' then
204 error(
205 'First key in {' .. inner .. '} must be a numeric index (like {1} or {1.key}). '
206 .. 'Named keys like {' .. inner .. '} are not supported. Use {1.' .. inner .. '} instead.'
207 )
208 end
210 local idx = first_key
212 if idx == 0 then
213 if #keys > 1 then
214 error('{0} cannot be followed by keys like {0.key}. Use {0} alone or {N.key} instead.')
215 end
216 if vim.tbl_count(data) == 0 then
217 error('{0} cannot be used on empty data.')
218 end
219 replacement = vim.inspect(data)
220 elseif idx > data_len or idx < 1 then
221 local suggestion = nil
222 if idx > data_len and idx <= data_len + 3 then
223 suggestion = ' (did you mean {' .. (idx - 1) .. '}?)'
224 end
225 error(
226 'Index ' .. idx .. ' is out of range (have ' .. data_len .. ' items)' .. (suggestion or '')
227 )
228 else
229 local current = data[idx]
230 local failed_key = nil
231 local parent_table = nil
233 for i = 2, #keys do
234 if current == nil then break end
235 local k = keys[i]
236 local access_key = k.is_string and k.key or tonumber(k.key) or k.key
237 if type(current) == 'table' then
238 local key_exists = false
239 for ek in pairs(current) do
240 if ek == access_key then key_exists = true break end
241 end
242 if not key_exists then
243 failed_key = access_key
244 parent_table = current
245 end
246 end
247 current = current[access_key]
248 end
250 if current == nil then
251 local msg = 'Key not found while resolving {' .. inner .. '}'
252 if failed_key and parent_table then
253 local suggestion = suggest_key(parent_table, failed_key)
254 if suggestion then
255 msg = msg .. " (did you mean '" .. suggestion .. "'?)"
256 end
257 end
258 error(msg)
259 end
261 replacement = type(current) == 'table' and vim.inspect(current) or tostring(current)
262 end
263 end
265 table.insert(result, replacement)
266 pos = endbrace + 1
267 end
269 return table.concat(result)
270end
272return setmetatable(
273 { levenshtein = levenshtein },
274 { __call = function(_, ...) return format_message(...) end }
275)

neovim/lua/std/dbg/init.lua

Modified

+71 / −73 text lines

1---Debug logging facade.
2---Provides dbg(), dbg.kind(), dbg.toggle(), dbg.get() and user commands.
3---All debug output goes to the JSONL file at stdpath('state')/bugabinga_config_debug.jsonl.
4local file = require 'std.dbg.file'
5local format = require 'std.dbg.format'
1--- Debug logging facade. Minimal by design: everything goes to one JSONL file.
2--- File: stdpath('state')/bugabinga_config_debug.jsonl
3---
4--- API:
5--- dbg( message, ... ) -- DEBUG level, printf-style ( string.format )
6--- dbg.kind( kind, message, ... )
7--- dbg.print( message, ... ) -- DEBUG level, explicit method form
8--- dbg.get() -- is debug mode on
9--- dbg.toggle()
10---
11--- Commands: :DbgModeToggle :DbgOpenFile :DbgClear
612local user_command = require 'std.user_command'
7local viewer = require 'std.dbg.viewer'
14local DBG_FILE = vim.fn.stdpath 'state' .. '/bugabinga_config_debug.jsonl'
916if vim.g.bugabinga_debug_mode == nil then
1017 vim.g.bugabinga_debug_mode = false
1118end
13---Returns whether debug mode is currently enabled.
14---@return boolean
15local function is_debug_mode()
20local function path()
21 return vim.g.bugabinga_debug_file_override or DBG_FILE
22end
24local function enabled()
1625 return vim.g.bugabinga_debug_mode
1726end
19---Toggles debug mode on/off and prints a notification.
20local function toggle_debug_mode()
21 vim.g.bugabinga_debug_mode = not vim.g.bugabinga_debug_mode
22 vim.notify( 'Toggled debug mode to ' .. tostring( is_debug_mode() ) )
28-- filename, function name and line of the caller, skipping this module's frames.
29local function context()
30 local level = 2
31 while true do
32 local info = debug.getinfo( level, 'Sln' )
33 if not info then return 'unknown', '', 0 end
34 local source = info.short_src or info.source
35 if source and not source:match 'std/dbg' then
36 return source, info.name or '', info.currentline or 0
37 end
38 level = level + 1
39 end
2340end
25---Logs a debug event of the specified kind.
26---Writes to the debug JSONL file if debug mode is enabled.
27---@param kind_name string DEBUG, TRACE, or ERROR
28---@param message string format string with {} or {N} placeholders
29---@param ... any values to substitute into the format string
30local function print_debug_kind( kind_name, message, ... )
31 if not is_debug_mode() then
32 return
33 end
34 local now = os.time()
35 local user_data = { ... }
36 local message = format( message, user_data )
37 local filename, function_name, line_number = file.get_context()
42local function log( kind, message, ... )
43 if not enabled() then return end
44 local data = { ... }
45 local ok, formatted = pcall( string.format, message, ... )
46 local source, fn, line = context()
3847 local event = {
39 kind = kind_name,
40 date = now,
41 message = message,
42 data = user_data,
43 filename = filename,
44 fn = function_name,
45 line = line_number,
48 kind = kind,
49 date = os.time(),
50 message = ok and formatted or message,
51 data = data,
52 filename = source,
53 fn = fn,
54 line = line,
4655 }
47 file.write( event, file.get_path() )
48end
50---Logs a DEBUG event.
51---@param _ any ignored (table receiver when called via metatable)
52---@param message string format string with {} or {N} placeholders
53---@param ... any values to substitute
54local function print_debug( _, message, ... )
55 if not is_debug_mode() then
56 return
56 local file_path = path()
57 vim.fn.mkdir( vim.fs.dirname( file_path ), 'p' )
58 local handle, err = io.open( file_path, 'a' )
59 if not handle then
60 error( 'dbg: cannot open ' .. file_path .. ': ' .. tostring( err ) )
5761 end
58 print_debug_kind( 'DEBUG', message, ... )
62 handle:write( vim.json.encode( event ) .. '\n' )
63 handle:close()
5964end
61---Opens or closes the debug viewer depending on current state.
62local function toggle_debug_viewer()
63 if viewer.is_open() then
64 viewer.close()
65 else
66 viewer.open()
67 end
66local function toggle()
67 vim.g.bugabinga_debug_mode = not enabled()
68 vim.notify( 'debug mode: ' .. tostring( enabled() ) )
6869end
70---Opens the raw JSONL debug file in a normal buffer.
71local function open_raw_debug_file()
72 vim.cmd.edit( file.get_path() )
73end
71user_command.DbgModeToggle 'Toggle global vim config debug mode.' ( toggle )
72user_command.DbgOpenFile 'Open the JSONL debug file in a buffer' ( function ()
73 vim.cmd.edit( path() )
74end )
75user_command.DbgClear 'Clear the JSONL debug file' ( function ()
76 local handle = io.open( path(), 'w' )
77 if handle then handle:close() end
78end )
75user_command.DbgModeToggle 'Toggle global vim config debug mode.' ( toggle_debug_mode )
76user_command.DbgViewToggle 'Open or close the debug event viewer' ( toggle_debug_viewer )
77user_command.DbgOpenFile 'Opens the JSON debug file in normal buffer' ( open_raw_debug_file )
78user_command.DbgClear 'Clears the JSON debug file' ( file.clear_log )
80return setmetatable(
81 {
82 kind = print_debug_kind,
83 toggle = toggle_debug_mode,
84 get = is_debug_mode,
85 },
86 {
87 __call = print_debug,
88 __newindex = function ( ... )
89 error( 'Assignments are not supported for std.dbg.\n' .. vim.inspect( ... ), 2 )
90 end,
91 }
92)
80return setmetatable( {
81 kind = log,
82 print = function ( message, ... ) log( 'DEBUG', message, ... ) end,
83 toggle = toggle,
84 get = enabled,
85}, {
86 __call = function ( _, message, ... ) log( 'DEBUG', message, ... ) end,
87 __newindex = function ( ... )
88 error( 'Assignments are not supported for std.dbg.\n' .. vim.inspect( ... ), 2 )
89 end,
90} )

neovim/lua/std/dbg/init.lua.bak

Deleted
deleted file mode 100644

+0 / −69 text lines

1local file = require 'std.dbg.file'
2local kinds = require 'std.dbg.kinds'
3local format = require 'std.dbg.format'
4local user_command = require 'std.user_command'
5
6if vim.g.bugabinga_debug_mode == nil then
7 vim.g.bugabinga_debug_mode = false
8end
9
10local function is_debug_mode()
11 return vim.g.bugabinga_debug_mode
12end
14local function toggle_debug_mode()
15 vim.g.bugabinga_debug_mode = not vim.g.bugabinga_debug_mode
16 vim.notify( 'Toggled debug mode to ' .. tostring( is_debug_mode() ) )
17end
19local function print_debug_kind( kind_name, message, ... )
20 if not is_debug_mode() then
21 return
22 end
23 local now = os.time()
24 local user_data = { ... }
25 local filename, function_name, line_number = file.get_context()
26 local event = {
27 kind = kind_name,
28 date = now,
29 format = message,
30 data = user_data,
31 filename = filename,
32 fn = function_name,
33 line = line_number,
34 }
35 file.write( event )
36end
38local function print_debug( message, ... )
39 if not is_debug_mode() then
40 return
41 end
42 print_debug_kind( 'DEBUG', message, ... )
43end
45local function open_special_debug_buffer()
46 vim.notify( 'Debug viewer not yet implemented (Stage 2)', vim.log.levels.WARN )
47end
49local function open_raw_debug_file()
50 vim.cmd.edit( file.get_path() )
51end
53user_command.Debug 'Toggle global vim config debug mode.' ( toggle_debug_mode )
54user_command.DebugOpen 'Open special buffer with debug events' ( open_special_debug_buffer )
55user_command.DebugOpenRaw 'Opens the JSON debug file in normal buffer' ( open_raw_debug_file )
57return setmetatable(
58 {
59 kind = print_debug_kind,
60 toggle = toggle_debug_mode,
61 get = is_debug_mode,
62 },
63 {
64 __call = print_debug,
65 __newindex = function ( ... )
66 error( 'Assignments are not supported for std.dbg.\n' .. vim.inspect( ... ), 2 )
67 end,
68 }
69)

neovim/lua/std/dbg/kinds.lua

Deleted
deleted file mode 100644

+0 / −48 text lines

1local icon = require 'std.icon'
2
3---@class DbgKind
4---@field icon string nerd font icon
5---@field hl_group string neovim highlight group
6
7---@type table<string, DbgKind>
8local DBG_KINDS = {
9 DEBUG = { icon = icon.search, hl_group = 'DiagnosticInfo' },
10 TRACE = { icon = icon.event, hl_group = 'DiagnosticHint' },
11 ERROR = { icon = icon.error, hl_group = 'DiagnosticError' },
12}
14---Returns the kind details for a given kind name.
15---@param kind_name string must be one of DEBUG, TRACE, ERROR
16---@return DbgKind
17local function get(kind_name)
18 vim.validate('kind_name', kind_name, 'string')
19 local kind = DBG_KINDS[kind_name]
20 if not kind then
21 local available = vim.tbl_keys(DBG_KINDS)
22 error('Unknown debug kind: ' .. kind_name .. '. Available: ' .. vim.inspect(available))
23 end
24 return kind
25end
27---Returns a list of all available kind names.
28---@return string[]
29local function list()
30 return vim.tbl_keys(DBG_KINDS)
31end
33---Formats a kind name into a display string with icon and name.
34---@param kind_name string
35---@return string
36local function format(kind_name)
37 local kind = get(kind_name)
38 return kind.icon .. ' ' .. kind_name
39end
41return {
42 DEBUG = DBG_KINDS.DEBUG,
43 TRACE = DBG_KINDS.TRACE,
44 ERROR = DBG_KINDS.ERROR,
45 get = get,
46 list = list,
47 format = format,
48}No final newline

neovim/lua/std/dbg/viewer.lua

Deleted
deleted file mode 100644

+0 / −680 text lines

1---Debug event viewer — special buffer UI for browsing debug events.
2---
3---## Public API
4---
5---| Function | Description |
6---| ----------------------- | ------------------------------------------------ |
7---| `open()` | Open viewer (reuse existing window if open) |
8---| `close()` | Close viewer and delete its buffer + watcher |
9---| `refresh()` | Re-read all events from disk and re-render |
10---| `is_open()` | Returns `true` if viewer window is valid |
11---| `jump_to_source(win_id)`| Jump to the source file:line of event at cursor |
12---| `clear_filters()` | Remove all active filters |
13---| `filter_by_kind()` | Prompt for kind filter (fk) |
14---| `filter_by_message()` | Prompt for message filter (fm) |
15---| `filter_by_location()` | Prompt for filename filter (fl) |
16---| `filter_by_all()` | Prompt for combined filter (ff) |
17---| `get_winbar()` | Returns winbar text (used by format string) |
18---
19---## Keymaps (in viewer buffer)
20---
21---| Key | Action |
22---| ----- | -------------------------- |
23---| `q` | Close viewer |
24---| `<Esc>` | Close viewer |
25---| `r` | Refresh events from disk |
26---| `<CR>` | Jump to source location |
27---| `ff` | Filter combined (all) |
28---| `fc` | Clear filters + notify |
29---| `fk` | Filter by kind |
30---| `fm` | Filter by message |
31---| `fl` | Filter by location |
32---
33---## Layout
34---
35---- Opens as a **bottom split** (`botright split`), respecting `splitbelow`
36---- Height is **golden ratio** (~61.8% of screen height)
37---- Each event renders as a **4-line block**: header, message, location, blank
38---- Events sorted **newest-first** (by date descending)
39---- Auto-refreshes via `vim.uv.fs_event` when debug file changes
40---
41---## Filtering
42---
43---- Filters use `vim.fn.matchfuzzy` for fuzzy matching
44---- Multiple filters combine with **AND** logic
45---- `ff` prompts for combined filter across kind + message + filename
46---- `fc` clears all filters and shows `vim.notify`
47---- Active filters displayed in **winbar**
48---- Event count shown as `filtered/total` when filters active
49---
50---## Events Structure
51---
52---Events loaded from `std.dbg.file` (JSONL). Each event:
53---```lua
54---{
55--- kind = "DEBUG" | "TRACE" | "ERROR",
56--- date = os.time() integer,
57--- message = formatted string,
58--- data = { ... }, -- raw user data
59--- filename = "@source.lua" or "[string ...]",
60--- fn = "function_name",
61--- line = 123,
62---}
63---```
64---
65---## Highlights
66---
67---| Highlight Group | Links To | Applied To |
68---| ------------------------ | ---------------- | ------------------- |
69---| `DbgViewerKindIcon` | `Title` | Kind icon in header |
70---| `DbgViewerKind` | `Comment` | Kind name in header |
71---| `DbgViewerTime` | `Normal` | Timestamp in header |
72---| `DbgViewerMessage` | `Comment` | Message lines |
73---| `DbgViewerLocation` | `Comment` | Location lines |
74---| (kind-specific) | `DiagnosticInfo/Hint/Error` | Icon backgrounds |
75---
76---## Internal Architecture
77---
78---- `H.state` — module-local state:
79--- ```lua
80--- {
81--- buf_id = number,
82--- win_id = number,
83--- events = event[],
84--- filtered_indices = number[] | nil,
85--- filters = { all = "", kind = "", message = "", filename = "" },
86--- line_events = table, -- line_idx (1-based) -> event_idx (1-based)
87--- filtered_count = number, -- how many events currently displayed
88--- event_count = number, -- total events read from file
89--- watcher = uv_fs_event | nil,
90--- highlights = highlight[], -- all active highlights for re-apply on prepend
91--- }
92--- ```
93---- `H.ns_id` — namespace for buffer highlights
94---- `H.BUF_NAME_PREFIX` — buffer name pattern: `dbgviewer://<buf_id>/debug-events`
95---- `H.FT` — filetype set on viewer buffer: `DbgViewer`
96local file = require 'std.dbg.file'
97local kinds = require 'std.dbg.kinds'
98local timeago = require 'std.timeago'
99local map = require 'std.map'
101local start_watcher
102local on_file_change
104local H = {
105 state = nil,
106}
108H.ns_id = vim.api.nvim_create_namespace 'std.dbg.viewer'
110H.BUF_NAME_PREFIX = 'dbgviewer://'
112H.FT = 'DbgViewer'
114local NS_HL = {
115 kind_icon = 'DbgViewerKindIcon',
116 kind_name = 'DbgViewerKind',
117 time = 'DbgViewerTime',
118 message = 'DbgViewerMessage',
119 location = 'DbgViewerLocation',
120}
122local KIND_TO_HL = {
123 DEBUG = 'DiagnosticInfo',
124 TRACE = 'DiagnosticHint',
125 ERROR = 'DiagnosticError',
126}
128local WINBAR_FORMAT = '%%#%s#%%{v:lua.require("std.dbg.viewer").get_winbar()}%%#Normal#'
130local FILTER_WINBAR_SPECS = {
131 { key = 'all', prefix = ' all:"', suffix = '"' },
132 { key = 'kind', prefix = ' kind:', suffix = '' },
133 { key = 'message', prefix = ' msg:"', suffix = '"' },
134 { key = 'filename',prefix = ' file:', suffix = '' },
135}
137local FILTER_SPECS = {
138 {
139 key = 'all',
140 extract = function(ev) return ev.kind .. ' ' .. ev.message .. ' ' .. sanitize_src(ev.filename) end,
141 },
142 {
143 key = 'kind',
144 extract = function(ev) return ev.kind end,
145 },
146 {
147 key = 'message',
148 extract = function(ev) return ev.message end,
149 },
150 {
151 key = 'filename',
152 extract = function(ev) return sanitize_src(ev.filename) end,
153 },
154}
156local function get_kind_hl_group(kind_name)
157 return KIND_TO_HL[kind_name] or 'DiagnosticInfo'
158end
160local function sanitize_src(src)
161 if not src or src == '' then return 'unknown' end
162 return (src:gsub('^@', ''):gsub('^%[string .+%]$', 'unknown'))
163end
165local function make_winbar()
166 return string.format(WINBAR_FORMAT, NS_HL.kind_icon)
167end
169local function get_winbar()
170 if not H.state or not H.state.win_id then return '' end
171 local s = H.state
172 local parts = {}
173 local has_filter = false
175 for _, spec in ipairs(FILTER_WINBAR_SPECS) do
176 local val = s.filters[spec.key]
177 if val and val ~= '' then
178 parts[#parts + 1] = spec.prefix .. val .. spec.suffix
179 has_filter = true
180 end
181 end
183 local filter_str = has_filter and table.concat(parts, '') or ''
184 local count = s.filtered_count or 0
185 local total = s.events and #s.events or 0
186 local count_str = count == total and tostring(total) or count .. '/' .. total
188 return ' ' .. kinds.get('DEBUG').icon .. ' Debug [' .. count_str .. ' events]' .. filter_str
189end
191local function format_event_for_display(event)
192 local kind_info = kinds.get(event.kind)
193 local icon = kind_info.icon
194 local rel_time = timeago.format(event.date)
195 local src = sanitize_src(event.filename)
196 local loc = src .. ':' .. (event.line or '?')
197 local msg = event.message or '(no message)'
199 return {
200 icon = icon,
201 kind_name = event.kind,
202 time = rel_time,
203 message = msg,
204 location = loc,
205 }
206end
208local function build_lines_and_hl(events)
209 local lines = {}
210 local line_events = {}
211 local highlights = {}
213 if #events == 0 then
214 lines[1] = ' (no debug events)'
215 line_events[1] = nil
216 return lines, line_events, highlights
217 end
219 for ei, event in ipairs(events) do
220 local d = format_event_for_display(event)
222 local header = string.format(' %s %s · %s', d.icon, d.kind_name, d.time)
223 local msg_line = ' ' .. d.message
224 local loc_line = ' ' .. d.location
226 local header_line_idx = #lines + 1
227 lines[#lines + 1] = header
228 line_events[header_line_idx] = ei
229 highlights[#highlights + 1] = {
230 line = header_line_idx,
231 kind = event.kind,
232 icon_start = 1,
233 icon_end = #d.icon + 1,
234 kind_name_start = #d.icon + 2,
235 kind_name_end = #d.icon + 2 + #d.kind_name,
236 time_start = #header - #d.time,
237 time_end = #header,
238 }
240 local msg_line_idx = #lines + 1
241 lines[#lines + 1] = msg_line
242 line_events[msg_line_idx] = ei
244 local loc_line_idx = #lines + 1
245 lines[#lines + 1] = loc_line
246 line_events[loc_line_idx] = ei
247 highlights[#highlights + 1] = {
248 line = loc_line_idx,
249 location = true,
250 }
252 local blank_idx = #lines + 1
253 lines[#lines + 1] = ''
254 line_events[blank_idx] = nil
255 end
257 return lines, line_events, highlights
258end
260local function apply_highlights(buf_id, highlights, events)
261 vim.api.nvim_buf_clear_highlight(buf_id, H.ns_id, 0, -1)
263 for _, hl in ipairs(highlights) do
264 local lnum = hl.line - 1
266 if hl.location then
267 vim.api.nvim_buf_add_highlight(buf_id, H.ns_id, NS_HL.location, lnum, 0, -1)
268 elseif hl.kind then
269 vim.api.nvim_buf_add_highlight(buf_id, H.ns_id, get_kind_hl_group(hl.kind), lnum, hl.icon_start - 1, hl.icon_end - 1)
270 vim.api.nvim_buf_add_highlight(buf_id, H.ns_id, NS_HL.kind_name, lnum, hl.kind_name_start - 1, hl.kind_name_end - 1)
271 vim.api.nvim_buf_add_highlight(buf_id, H.ns_id, NS_HL.time, lnum, hl.time_start - 1, hl.time_end - 1)
272 else
273 vim.api.nvim_buf_add_highlight(buf_id, H.ns_id, NS_HL.message, lnum, 0, -1)
274 end
275 end
276end
278local function create_buf()
279 local buf_id = vim.api.nvim_create_buf(false, true)
280 vim.api.nvim_buf_set_name(buf_id, H.BUF_NAME_PREFIX .. buf_id .. '/debug-events')
281 vim.bo[buf_id].buftype = 'nofile'
282 vim.bo[buf_id].bufhidden = 'wipe'
283 vim.bo[buf_id].buflisted = false
284 vim.bo[buf_id].modifiable = false
285 vim.bo[buf_id].swapfile = false
286 vim.bo[buf_id].filetype = H.FT
287 vim.bo[buf_id].modeline = false
288 return buf_id
289end
291local function open_win(buf_id)
292 local height = math.max(5, math.floor(0.618 * vim.o.lines))
293 vim.cmd('botright split')
294 local win_id = vim.api.nvim_get_current_win()
295 vim.api.nvim_win_set_buf(win_id, buf_id)
296 vim.wo[win_id].wrap = true
297 vim.wo[win_id].scrolloff = 0
298 vim.wo[win_id].cursorline = true
299 vim.wo[win_id].winbar = make_winbar()
300 vim.api.nvim_win_set_height(win_id, height)
301 return win_id
302end
304local function event_passes_filters(event, filters)
305 for _, spec in ipairs(FILTER_SPECS) do
306 local fval = filters[spec.key]
307 if fval and fval ~= '' then
308 local ftext = spec.extract(event)
309 if #vim.fn.matchfuzzy({ ftext }, fval) == 0 then
310 return false
311 end
312 end
313 end
314 return true
315end
317local function compute_filtered_indices(events, filters)
318 if not filters then return nil end
320 local has_any_filter = false
321 for _, spec in ipairs(FILTER_SPECS) do
322 local fval = filters[spec.key]
323 if fval and fval ~= '' then
324 has_any_filter = true
325 break
326 end
327 end
329 if not has_any_filter then return nil end
331 local result = {}
332 for i, ev in ipairs(events) do
333 if event_passes_filters(ev, filters) then
334 result[#result + 1] = i
335 end
336 end
337 return result
338end
340local function render()
341 if not H.state or not H.state.buf_id then return end
343 local events = H.state.events or {}
344 local filtered_indices = H.state.filtered_indices
345 local display_events = filtered_indices and (function()
346 local r = {}
347 for _, idx in ipairs(filtered_indices) do r[#r+1] = events[idx] end
348 return r
349 end)() or events
351 local lines, line_events, highlights = build_lines_and_hl(display_events)
352 H.state.line_events = line_events
353 H.state.highlights = highlights
354 H.state.filtered_count = #display_events
356 local was_modifiable = vim.bo[H.state.buf_id].modifiable
357 vim.bo[H.state.buf_id].modifiable = true
358 vim.api.nvim_buf_set_lines(H.state.buf_id, 0, -1, false, lines)
359 vim.bo[H.state.buf_id].modifiable = was_modifiable
361 apply_highlights(H.state.buf_id, highlights, events)
363 if H.state.win_id and vim.api.nvim_win_is_valid(H.state.win_id) then
364 vim.wo[H.state.win_id].winbar = make_winbar()
365 end
366end
368local function prepend_new_events(new_events)
369 if not H.state or not H.state.buf_id then return end
370 if #new_events == 0 then return end
372 local new_display_events = {}
373 for _, ev in ipairs(new_events) do
374 if event_passes_filters(ev, H.state.filters) then
375 new_display_events[#new_display_events + 1] = ev
376 end
377 end
379 if #new_display_events == 0 then return end
381 local new_lines = {}
382 local new_highlights = {}
383 local new_line_events = {}
385 local base_idx = 1
386 for ei, event in ipairs(new_display_events) do
387 local d = format_event_for_display(event)
389 local header = string.format(' %s %s · %s', d.icon, d.kind_name, d.time)
390 local msg_line = ' ' .. d.message
391 local loc_line = ' ' .. d.location
393 local header_line_idx = #new_lines + 1
394 new_lines[#new_lines + 1] = header
395 new_line_events[header_line_idx] = base_idx + ei - 1
396 new_highlights[#new_highlights + 1] = {
397 line = header_line_idx,
398 kind = event.kind,
399 icon_start = 1,
400 icon_end = #d.icon + 1,
401 kind_name_start = #d.icon + 2,
402 kind_name_end = #d.icon + 2 + #d.kind_name,
403 time_start = #header - #d.time,
404 time_end = #header,
405 }
407 local msg_line_idx = #new_lines + 1
408 new_lines[#new_lines + 1] = msg_line
409 new_line_events[msg_line_idx] = base_idx + ei - 1
411 local loc_line_idx = #new_lines + 1
412 new_lines[#new_lines + 1] = loc_line
413 new_line_events[loc_line_idx] = base_idx + ei - 1
414 new_highlights[#new_highlights + 1] = {
415 line = loc_line_idx,
416 location = true,
417 }
419 local blank_idx = #new_lines + 1
420 new_lines[#new_lines + 1] = ''
421 new_line_events[blank_idx] = nil
422 end
424 local was_modifiable = vim.bo[H.state.buf_id].modifiable
425 vim.bo[H.state.buf_id].modifiable = true
426 vim.api.nvim_buf_set_lines(H.state.buf_id, 0, 0, false, new_lines)
427 vim.bo[H.state.buf_id].modifiable = was_modifiable
429 local shift = #new_lines
430 local shifted_line_events = {}
431 for line_idx, event_idx in pairs(H.state.line_events) do
432 shifted_line_events[line_idx + shift] = event_idx + #new_display_events
433 end
434 for line_idx, event_idx in pairs(new_line_events) do
435 shifted_line_events[line_idx] = event_idx
436 end
437 H.state.line_events = shifted_line_events
439 local all_highlights = {}
440 for _, hl in ipairs(H.state.highlights or {}) do
441 all_highlights[#all_highlights + 1] = {
442 line = hl.line + shift,
443 kind = hl.kind,
444 location = hl.location,
445 icon_start = hl.icon_start,
446 icon_end = hl.icon_end,
447 kind_name_start = hl.kind_name_start,
448 kind_name_end = hl.kind_name_end,
449 time_start = hl.time_start,
450 time_end = hl.time_end,
451 }
452 end
453 for _, hl in ipairs(new_highlights) do
454 all_highlights[#all_highlights + 1] = hl
455 end
456 H.state.highlights = all_highlights
458 vim.api.nvim_buf_clear_highlight(H.state.buf_id, H.ns_id, 0, -1)
459 for _, hl in ipairs(all_highlights) do
460 local lnum = hl.line - 1
461 if hl.location then
462 vim.api.nvim_buf_add_highlight(H.state.buf_id, H.ns_id, NS_HL.location, lnum, 0, -1)
463 elseif hl.kind then
464 vim.api.nvim_buf_add_highlight(H.state.buf_id, H.ns_id, get_kind_hl_group(hl.kind), lnum, hl.icon_start - 1, hl.icon_end - 1)
465 vim.api.nvim_buf_add_highlight(H.state.buf_id, H.ns_id, NS_HL.kind_name, lnum, hl.kind_name_start - 1, hl.kind_name_end - 1)
466 vim.api.nvim_buf_add_highlight(H.state.buf_id, H.ns_id, NS_HL.time, lnum, hl.time_start - 1, hl.time_end - 1)
467 else
468 vim.api.nvim_buf_add_highlight(H.state.buf_id, H.ns_id, NS_HL.message, lnum, 0, -1)
469 end
470 end
472 H.state.filtered_count = H.state.filtered_count + #new_display_events
474 if H.state.win_id and vim.api.nvim_win_is_valid(H.state.win_id) then
475 vim.wo[H.state.win_id].winbar = make_winbar()
476 end
477end
479local function on_file_change()
480 if not H.state then return end
482 local watcher = H.state.watcher
483 if watcher then
484 watcher:stop()
485 H.state.watcher = nil
486 end
488 local new_events, new_total = file.read_new(H.state.event_count)
489 if #new_events == 0 and new_total == H.state.event_count then
490 H.state.watcher = start_watcher()
491 return
492 end
494 local reversed = {}
495 for i = #new_events, 1, -1 do
496 reversed[#reversed + 1] = new_events[i]
497 end
498 new_events = reversed
500 for i = #new_events, 1, -1 do
501 table.insert(H.state.events, 1, new_events[i])
502 end
503 H.state.event_count = new_total
505 prepend_new_events(new_events)
507 H.state.watcher = start_watcher()
508end
510start_watcher = function()
511 local path = file.get_path()
512 local callback = function(err)
513 if err then return end
514 on_file_change()
515 end
516 local watcher = vim.uv.new_fs_event()
517 watcher:start(path, {}, callback)
518 return watcher
519end
521local function setup_keymaps(buf_id, win_id)
522 map.normal { keys = 'q', command = close, buffer = buf_id, desc = 'Close debug viewer' }
523 map.normal { keys = '<Esc>', command = close, buffer = buf_id, desc = 'Close debug viewer' }
524 map.normal { keys = 'r', command = refresh, buffer = buf_id, desc = 'Refresh events from disk' }
525 map.normal { keys = '<CR>', command = function() jump_to_source(win_id) end, buffer = buf_id, desc = 'Jump to source location' }
526 map.normal { keys = 'ff', command = function() filter_by_all() end, buffer = buf_id, desc = 'Filter combined (all)' }
527 map.normal { keys = 'fc', command = function() clear_filters() vim.notify('Filters cleared') end, buffer = buf_id, desc = 'Clear filters + notify' }
528 map.normal { keys = 'fk', command = function() filter_by_kind() end, buffer = buf_id, desc = 'Filter by kind' }
529 map.normal { keys = 'fm', command = function() filter_by_message() end, buffer = buf_id, desc = 'Filter by message' }
530 map.normal { keys = 'fl', command = function() filter_by_location() end, buffer = buf_id, desc = 'Filter by location' }
531end
533function open()
534 if H.state and H.state.win_id and vim.api.nvim_win_is_valid(H.state.win_id) then
535 vim.api.nvim_set_current_win(H.state.win_id)
536 return
537 end
539 local events = file.read_all()
540 for i = 1, math.floor(#events / 2) do
541 events[i], events[#events - i + 1] = events[#events - i + 1], events[i]
542 end
543 local buf_id = create_buf()
544 local win_id = open_win(buf_id)
545 setup_keymaps(buf_id, win_id)
547 local watcher = start_watcher()
549 H.state = {
550 buf_id = buf_id,
551 win_id = win_id,
552 events = events,
553 filtered_indices = nil,
554 filters = { all = '', kind = '', message = '', filename = '' },
555 line_events = {},
556 filtered_count = #events,
557 event_count = #events,
558 watcher = watcher,
559 }
561 render()
562end
564function close()
565 if not H.state then return end
567 if H.state.watcher then
568 H.state.watcher:stop()
569 H.state.watcher = nil
570 end
572 if H.state.win_id and vim.api.nvim_win_is_valid(H.state.win_id) then
573 pcall(vim.api.nvim_win_close, H.state.win_id, true)
574 end
575 if H.state.buf_id and vim.api.nvim_buf_is_valid(H.state.buf_id) then
576 pcall(vim.api.nvim_buf_delete, H.state.buf_id, { force = true })
577 end
579 H.state = nil
580end
582function refresh()
583 if not H.state then return end
585 local events = file.read_all()
586 H.state.events = events
587 H.state.event_count = #events
588 H.state.filtered_indices = compute_filtered_indices(events, H.state.filters)
589 render()
590end
592function is_open()
593 return H.state ~= nil
594 and H.state.win_id ~= nil
595 and vim.api.nvim_win_is_valid(H.state.win_id)
596end
598function jump_to_source(win_id)
599 if not H.state or not H.state.buf_id then return end
601 local cursor = vim.api.nvim_win_get_cursor(win_id or H.state.win_id)
602 local line_idx = cursor[1]
604 local event_idx = H.state.line_events[line_idx]
605 if not event_idx then
606 event_idx = H.state.line_events[line_idx - 1]
607 end
608 if not event_idx then
609 event_idx = H.state.line_events[line_idx + 1]
610 end
611 if not event_idx then return end
613 local event = H.state.events[event_idx]
614 if not event then return end
616 local path = sanitize_src(event.filename)
617 if path == 'unknown' or path == '' then return end
619 close()
620 vim.cmd.edit(path)
621 if event.line and event.line > 0 then
622 pcall(vim.api.nvim_win_set_cursor, 0, { event.line, 0 })
623 end
624end
626function clear_filters()
627 if not H.state then return end
628 H.state.filters = { all = '', kind = '', message = '', filename = '' }
629 H.state.filtered_indices = nil
630 H.state.filtered_count = #H.state.events
631 render()
632end
634function filter_by_all()
635 vim.ui.input({ prompt = 'Filter (all): ' }, function(value)
636 if value == nil then return end
637 if not H.state then return end
638 H.state.filters.all = value or ''
639 H.state.filtered_indices = compute_filtered_indices(H.state.events, H.state.filters)
640 render()
641 end)
642end
644local function do_filter(field, prompt_msg)
645 vim.ui.input({ prompt = prompt_msg .. ': ' }, function(value)
646 if value == nil then return end
647 if not H.state then return end
648 H.state.filters[field] = value or ''
649 H.state.filtered_indices = compute_filtered_indices(H.state.events, H.state.filters)
650 render()
651 end)
652end
654function filter_by_kind()
655 do_filter('kind', 'Filter kind')
656end
658function filter_by_message()
659 do_filter('message', 'Filter message')
660end
662function filter_by_location()
663 do_filter('filename', 'Filter location')
664end
666return {
667 open = open,
668 close = close,
669 refresh = refresh,
670 is_open = is_open,
671 jump_to_source = jump_to_source,
672 clear_filters = clear_filters,
673 filter_by_all = filter_by_all,
674 filter_by_kind = filter_by_kind,
675 filter_by_message = filter_by_message,
676 filter_by_location = filter_by_location,
677 get_winbar = get_winbar,
678 _on_file_change = on_file_change,
679 _get_state = function() return H.state end,
680}

neovim/lua/std/executable.lua

Added
new file mode 100644

+4 / −0 text lines

1return function(name)
2 vim.validate('name', name, 'string')
3 return vim.fn.executable(name) == 1
4end

neovim/lua/std/ftoptions.lua

Added
new file mode 100644

+99 / −0 text lines

1-- per-filetype options harvested from the builtin vimscript ftplugins
2-- ( nvim 0.12, before the ftplugin kill ) then filtered to pure-data options.
3-- deliberately dropped: omnifunc ( LSP owns it ), includeexpr ( vimscript/autoload ),
4-- cinkeys/cinwords ( cindent is off, treesitter indents ).
5-- commentstring lives in std.commentstring. edit freely.
6local ftoptions = {
7 ["c"] = {
8 comments = [[sO:* -,mO:* ,exO:*/,s1:/*,mb:*,ex:*/,:///,://]],
9 define = [[^\s*#\s*define]],
10 formatoptions = [[jcroql]],
11 include = [[^\s*#\s*include]],
12 path = [[.,/usr/include,,**]],
13 },
14 ["cpp"] = {
15 comments = [[sO:* -,mO:* ,exO:*/,s1:/*,mb:*,ex:*/,:///,://]],
16 define = [[^\s*#\s*define]],
17 formatoptions = [[jcroql]],
18 include = [[^\s*#\s*include]],
19 path = [[.,/usr/include,,**]],
20 },
21 ["css"] = {
22 comments = [[s1:/*,mb:*,ex:*/]],
23 formatoptions = [[jcroql]],
24 include = [[^\s*@import\s\+\%(url(\)\=]],
25 },
26 ["html"] = {
27 comments = [[s:<!--,m: ,e:-->]],
28 matchpairs = [[(:),{:},[:],<:>]],
29 },
30 ["java"] = {
31 comments = [[:///,sO:* -,mO:* ,exO:*/,s1:/*,mb:*,ex:*/,://,b:#,:%,:XCOMM,n:>,fb:-,fb:•]],
32 define = [[\C\m^\s*\%(\%(\%(@\%(interface\)\@!\%(\K\k*\.\)*\K\k*\)\s\+\)*\%(p\%(rivate\|rotected\|ublic\)\s\+\)\=\)\@>\%(\%(\%(abstract\|final\|non-sealed\|s\%(ealed\|tatic\|trictfp\)\)\s\+\)*\%(class\|enum\|@\=interface\|record\)\s\+\ze\K\k*\>\|\%(\%(abstract\|default\|final\|native\|s\%(tatic\|trictfp\|ynchronized\)\)\s\+\)*\%(<.\{-1,}>\s\+\)\=\%(\K\k*\.\)*\K\k*\s*\%(<.\{-1,}>\%(\s\|\[\)\@=\)\=\s*\%(\[\]\s*\)*\s\+\ze\%(\<\%(assert\|case\|instanceof\|new\|return\|throw\|when\)\s\+\)\@18<!\K\k*\s*(\)]],
33 formatoptions = [[jcroql]],
34 include = [[\C\m^\s*import\s\+\ze\%(\K\k*\.\)\+\K\k*;]],
35 suffixesadd = [[.java]],
36 },
37 ["javascript"] = {
38 comments = [[sO:* -,mO:* ,exO:*/,s1:/*,mb:*,ex:*/,://]],
39 define = [[\(^\s*(*async\s\+function\|(*function\)\|^\s*\(\*\|static\|async\|get\|set\|\i\+\.\)\|^\s*\(\ze\i\+\)\(([^)]*).*{$\|\s*[:=,]\)\|^\s*\(export\s\+\|export\s\+default\s\+\)*\(var\|let\|const\|function\|class\)\|\<as\>]],
40 formatoptions = [[jcroql]],
41 suffixesadd = [[.js,.jsx,.es,.es6,.cjs,.mjs,.jsm,.vue,.json]],
42 },
43 ["javascriptreact"] = {
44 comments = [[sO:* -,mO:* ,exO:*/,s1:/*,mb:*,ex:*/,://]],
45 define = [[\(^\s*(*async\s\+function\|(*function\)\|^\s*\(\*\|static\|async\|get\|set\|\i\+\.\)\|^\s*\(\ze\i\+\)\(([^)]*).*{$\|\s*[:=,]\)\|^\s*\(export\s\+\|export\s\+default\s\+\)*\(var\|let\|const\|function\|class\)\|\<as\>]],
46 formatoptions = [[jcroql]],
47 suffixesadd = [[.js,.jsx,.es,.es6,.cjs,.mjs,.jsm,.vue,.json]],
48 },
49 ["json"] = {
50 formatoptions = [[cqj]],
51 },
52 ["jsonc"] = {
53 comments = [[sO:* -,mO:* ,exO:*/,s1:/*,mb:*,ex:*/,://]],
54 formatoptions = [[cqj]],
55 },
56 ["ocaml"] = {
57 comments = [[sr:(**,mb: ,ex:*),sr:(* ,mb: ,ex:*)]],
58 formatoptions = [[cqort]],
59 iskeyword = [[@,48-57,_,192-255,-,',`]],
60 },
61 ["roc"] = {
62 comments = [[:##,:#]],
63 },
64 ["rust"] = {
65 comments = [[s0:/*!,ex:*/,s1:/*,mb:*,ex:*/,:///,://!,://]],
66 formatoptions = [[croqnlj]],
67 include = [[\v^\s*(pub\s+)?use\s+\zs(\f|:)+]],
68 matchpairs = [[(:),{:},[:],<:>]],
69 suffixesadd = [[.rs]],
70 },
71 ["scss"] = {
72 comments = [[s1:/*,mb:*,ex:*/,://]],
73 define = [[^\C\v\s*%(\@function|\@mixin|\=)|^\s*%(\$[[:alnum:]-]+:|[%.][:alnum:]-]+\s*%(\{|$))@=]],
74 include = [[^\s*@import\s\+\%(url(\)\=["']\=]],
75 suffixesadd = [[.sass,.scss,.css]],
76 },
77 ["typescript"] = {
78 comments = [[sO:* -,mO:* ,exO:*/,s1:/*,mb:*,ex:*/,://]],
79 formatoptions = [[jcroql]],
80 iskeyword = [[@,48-57,_,192-255,-,$,#]],
81 suffixesadd = [[.ts,.d.ts,.tsx,.js,.jsx,.cjs,.mjs]],
82 },
83 ["typescriptreact"] = {
84 comments = [[sO:* -,mO:* ,exO:*/,s1:/*,mb:*,ex:*/,://]],
85 formatoptions = [[jcroql]],
86 iskeyword = [[@,48-57,_,192-255,-,$,#]],
87 suffixesadd = [[.ts,.d.ts,.tsx,.js,.jsx,.cjs,.mjs]],
88 },
89 ["zig"] = {
90 comments = [[:///,://!,://]],
91 define = [[\v(<fn>|<const>|<var>|^\s*\#\s*define)]],
92 formatoptions = [[jcroql]],
93 include = [[\v(\@import>|\@cInclude>|^\s*\#\s*include)]],
94 iskeyword = [[@,48-57,_,192-255,-,@-@]],
95 suffixesadd = [[.zig,.zir,.zon]],
96 },
97}
99return ftoptions

neovim/lua/std/icon.lua

Modified

+6 / −4 text lines

44 ['table'] = '',
55 arrow_left = '',
66 arrow_right = '',
7 backspace_key = '',
7 backspace_key = '󰌍',
88 block = '█',
99 branch = '',
1010 carriage_return = '␍',
8181 quot_right = '"',
8282 reference = '󰈇 ',
8383 replace = '',
84 return_key = '',
84 return_key = '󰌑',
8585 running = ' ',
8686 select = '󰒉',
8787 slant_left = '▟',
9090 space = '·',
9191 space_key = '󱁐',
9292 spelling = '󰓆',
93 start = '',
9493 struct = ' ',
9594 subversion = '󰳗',
9695 tab = '󰌒',
97 tab_key = '',
96 tab_key = '󰌒',
9897 telescope = '🔭',
9998 terminal = '',
10099 text = ' ',
109108 value = '󰎠 ',
110109 variable = '󰀫 ',
111110 vertical_bar = '│',
111 robot = '󰚩',
112 gauge = '󰊚',
113 dollar = '󰇁',
112114 vim = '',
113115 virtual = '󰢔',
114116 visual = '󰒉',

neovim/lua/std/light_up.lua

Modified

+3 / −7 text lines

5353 return namespace
5454end
56--- @return table groups A map of all highlight group names, mapping to themselves g:match('^([%w@%._]+)%s').
56--- @return table groups A map of all highlight group names, mapping to themselves.
5757local function get_vim_highlight_groups()
5858 local groups = {}
60 local highlight_command_output = vim.fn.execute 'highlight'
61 for line in highlight_command_output:gmatch '[^\n]+' do
62 local match = line:match '^([%w@%._]+)%s'
63 if match then groups[match] = match end
59 for name in pairs( vim.api.nvim_get_hl( 0, {} ) ) do
60 groups[name] = name
6461 end
6662 return groups
6763end

neovim/lua/std/localrc.lua

Deleted
deleted file mode 100644

+0 / −29 text lines

1local dbg = require 'std.dbg'
2
3--- loads given lua file path in current working directory into the current neovim lua runtime.
4--- @param file_name string path to lua file, that should be loaded
5--- @param validator function|string|table a validation function, that checks, if the loaded value fulfills your requirements.
6--- If `validator` is a string or table, then it should contain the allowed types of the value.
7--- @return any returns the evaluated value of the loaded lua file or `nil`, if it does not exists or did not pass
8--- validation.
9return function ( file_name, validator )
10 local filepath = vim.fn.fnamemodify( file_name, ':p' )
11 local file = vim.secure.read( filepath )
12 if not file then
13 return nil
14 end
15 local fn, err = loadstring( file )
16 if not fn or err then
17 dbg( 'unable to load %s. %s', file_name, err )
18 return nil
19 end
20 local value = fn()
21 local validator_type = type( validator )
22 if validator_type == 'string' or validator_type == 'table' then
23 local expected_types = validator_type == 'table' and validator or { validator, }
24 local value_type = type( value )
25 local is_valid = vim.iter( expected_types ):any( function ( t ) return t == value_type end )
26 return is_valid and value or nil
27 end
28 return validator( value ) and value or nil
29end

neovim/lua/std/map.lua

Modified

+2 / −2 text lines

4747 local options = vim.tbl_extend( 'keep', map.options, {
4848 silent = true,
4949 desc = map.description,
50 buffer = map.buffer,
50 buf = map.buffer,
5151 remap = map.remap,
5252 } )
6868 self.modes = {}
7070 return function ()
71 local delete_options = options.buffer and { buffer = options.buffer } or {}
71 local delete_options = options.buf and { buf = options.buf } or {}
7272 if type( keys ) == 'table' then
7373 for _, key in ipairs( keys ) do
7474 vim.keymap.del( modes, key, delete_options )

neovim/lua/std/project.lua

Modified

+5 / −7 text lines

9191-- ```
9292---@param path string? The starting path, from where to begin the search. If `nil`, the path of the current buffer is
9393---used.
94---@param markers table<string,number> List of markers, that define the root, that is searched for.
94---@param markers { name: string, weight: number }[] List of markers that define the searched root.
9595---@param stop string? The last directory on the path to root, when to stop searching. if `nil`, the users home
9696---directory is used.
9797---@return string? # Directory, that contains the `markers` and lies on the path from `path` to `stop`.
9898local function find_root(path, markers, stop)
99 validate {
100 path = { path, 'string', true, },
101 markers = { markers, 'table', },
102 stop = { stop, 'string', true, },
103 }
99 validate('markers', markers, 'table')
100 validate('path', path, 'string', true)
101 validate('stop', stop, 'string', true)
105103 path = path or vim.api.nvim_buf_get_name(0)
106104 path = normalize(expand(path))
176174--- Determines the project root directory of the current buffer file. A "project" is not clearly defined for all programming languages, so this function uses a heuristic approach.
177175---@param path string? path to start searching from. If `nil`, then path of current buffer is used.
178---@param markers table<string, number>? list of markers. a marker is a table with `name` and `weight` key. `name` can be a file or directory name, that indicates, that if a file/folder with that name exists in a directory, that directory is likely to be a project root. `weight` is a means to express confidence in that likelihood. Values should be between 1 and 3. Internally, there are some project-agnostic markers defined (e.g. README, LICENSE, .git, ...) that will be merged with `custom_markers`.
176---@param markers { name: string, weight: number }[]? list of weighted project markers.
179177---
180178---@return string? # The project root of the current buffer, or `nil`, if none could be determined.
181179---

neovim/lua/std/puk.lua

Modified

+4 / −4 text lines

1local load_pack = function(plugin_name, load_plugin)
1local load_pack = function(plugin_name)
22 vim.validate('plugin_name', plugin_name, 'string')
3 vim.cmd.packadd { plugin_name, bang = not load_plugin }
3 vim.cmd.packadd { plugin_name, bang = vim.v.vim_did_init == 0 }
44 return require(plugin_name)
55end
88 {
99 defer = function(plugin_name)
1010 return vim.schedule_wrap(function(f)
11 f(load_pack(plugin_name, true))
11 f(load_pack(plugin_name))
1212 end)
1313 end,
1414 },
1515 {
1616 __call = function(_, plugin_name)
17 return load_pack(plugin_name, false)
17 return load_pack(plugin_name)
1818 end,
1919 }

neovim/lua/std/string.lua

Deleted
deleted file mode 100644

+0 / −7 text lines

1local function is_blank(string)
2 return string == nil or string == '' or vim.trim(string) == ''
3end
4
5return {
6 is_blank = is_blank,
7}

neovim/lua/std/table/deep_copy.lua

Deleted
deleted file mode 100644

+0 / −11 text lines

1local function deep_copy(any)
2 if type(any) ~= 'table' then return any end
3
4 local result = {}
5 for key, value in pairs(any) do
6 result[key] = deep_copy(value)
7 end
8 return result
9end
11return deep_copy

neovim/lua/std/table/init.lua

Modified

+1 / −12 text lines

1--- Facade over various table functions in lua, neovim and some of my own.
1--- Facade over table functions used by this config.
22return {
3 deep_copy = require 'std.table.deep_copy',
43 join = require 'std.table.join',
6 contains = vim.tbl_contains,
7 count = vim.tbl_count,
8 deep_extend = vim.tbl_deep_extend,
9 extend = vim.tbl_extend,
105 filter = vim.tbl_filter,
11 get = vim.tbl_get,
12 is_array = vim.tbl_isarray,
13 is_empty = vim.tbl_isempty,
14 keys = vim.tbl_keys,
156 map = vim.tbl_map,
16 values = vim.tbl_values,
188 concat = table.concat,
199 insert = table.insert,
20 maxn = table.maxn,
2110 remove = table.remove,
2211 sort = table.sort,

neovim/lua/std/timeago.lua

Modified

+1 / −1 text lines

1313---@return number
1414local function round( num ) return math.floor( num + 0.5 ) end
16---@param time osdate
16---@param time integer
1717---@return string
1818local function format( time )
1919 local now = os.time()

neovim/pivi/.gitignore

Added
new file mode 100644

+1 / −0 text lines

1node_modules/

neovim/pivi/README.md

Added
new file mode 100644

+215 / −0 text lines

1# Pivi
2
3Standalone Neovim agent harness built on Pi Durable 1.5.2.
4Not a Pi coding-agent SDK/RPC adapter.
5Old `.system/` pivi documents describe the retired implementation.
6
7## Ownership
8
9- Durable owns conversations, model requests, tools, queues, compaction, persistence.
10- Neovim owns workspace buffers, including unsaved content.
11- File and process access goes through Durable's execution environment, implemented by `env.mjs` (`NeovimExecutionEnv`).
12- Durable's own `read`, `edit` and `write` run on it unchanged. There is no shell tool.
13- In that environment a file with unsaved editor changes reads as the editor has it, a file that exists only as a buffer exists, and a write inside the working directory becomes a buffer change: unsaved, undoable, one undo step per write.
14- Everything else falls through to disk: files without unsaved changes, binary content, paths outside the working directory, temporary files.
15- Neovim-native tools sit beside it: `save`, `lsp`, `diagnostics`, `nvim_lua`.
16- `lsp` asks the attached language server: definition, references, implementation, type definition, hover, rename, file symbols, workspace symbols. It takes a line plus the symbol text, sees unsaved changes, and leaves renamed buffers unsaved.
17- `nvim_lua` runs a Lua chunk inside Neovim with the whole API, as a coroutine.
18 `system(command, options)` starts a program from Neovim, streams its output, and returns code, stdout and stderr without freezing the editor.
19 `await(function(resolve) … end)` suspends until any callback resolves; `sleep(ms)` waits.
20 Programs see saved files only; the output begins with the unsaved buffers they could not see.
21 Calls that would freeze the editor are refused (`vim.wait`, `vim.system(...):wait()`, `vim.fn.system`), and a chunk computing for 10 s without yielding is stopped.
22 Globals a chunk assigns stay inside that chunk.
23- The system prompt forbids moving the user's window, buffer, cursor, or cwd.
24- No Pi coding-agent tools, config loader, or security sandbox.
25- Edits are best effort; no revision checks or transactional recovery across editor/worker crashes.
27## Runtime
29Node 22.19+ required.
30Dependencies and lockfile live here, independently of the installed Pi CLI.
32```nu
33just pivi-install
34just test-pivi
35```
37`harness.mjs` owns Durable integration.
38`env.mjs` owns the execution environment; `tools.mjs` the Neovim-native tools.
39`credentials.mjs` owns the credential file.
40`worker.mjs` carries pivi's own JSONL transport over stdin/stdout.
41`../lua/bugabinga/pivi/` owns Neovim interaction.
42Transport records are pivi-specific, not Pi coding-agent RPC commands.
43Streamed view records omit the committed `items` when unchanged.
44Neovim reuses already rendered committed text.
45Window options (winbar, folds, wrap) are set window-locally; folding is enabled there even when disabled globally.
47## Interaction
49`:Pivi` opens the read-only Markdown conversation in the current window.
50`:Pivi draft` opens an ordinary editable Markdown draft in that same window.
51`<leader>pd` toggles conversation ↔ draft without a permanent split.
52Draft undo is independent of streamed transcript updates.
53Draft text is saved atomically to `stdpath('state')/pivi/sessions/<id>/draft.txt` and restored with that session.
54Typing uses a 250 ms save debounce; leaving the draft or accepting a submission flushes immediately.
55A failed save leaves the draft modified and reports the error; the prior saved copy remains untouched.
56Repeated submission keys are ignored until the first request is acknowledged or rejected.
57Submitting from the draft shows the conversation at its end.
58`G` resumes following; new output stays bottom-aligned.
59Scrolling, searching, selecting, or opening folds pauses following in that window.
60The winbar shows `following` or `reading`; each window keeps its own state.
61Shrinking output never resumes following on its own.
62Queued steering and follow-up messages appear as `queued:` blocks until placed.
63Live thinking and tool preparation appear as folded blocks while a turn streams.
64Finished turns collapse their work into one fold with tool/error totals, elapsed time, and known cost.
65Visible work stays open while you inspect it; streaming preserves your reading position.
66Tool results sit inside their call's fold; `zo` opens the work, then individual calls.
67Markdown tables remain native text so cursor movement, search, selection, and yanking agree.
68Code blocks use a background; native Markdown conceal, outline, and heading motions remain available.
69The winbar shows elapsed work and known session cost.
70OSC 9;4 busy/reset sequences are emitted when Neovim supports `nvim_ui_send`; terminal support is optional.
71Every submitted prompt starts with an automatic `[editor: cwd · buffer · line · saved state]` note about the most recently used workspace buffer.
72Buffers the agent modifies become listed, so they show up in the buffer list.
73`:Pivi compact` on a short conversation reports that there is nothing to compact.
75## Stopping
77`<leader>px` or `:Pivi stop` stops the current work; the winbar shows `stopping` until it has.
78Stop is never queued behind other operations.
79Programs started with `system` are killed with their whole process group, and the waiting chunk is dropped.
80A chunk in a tight Lua loop is stopped by the 10 s limit; a blocking call into C that slips past the guards cannot be interrupted.
81The stopped request stays in the conversation, followed by `stopped by you`; the model is told not to continue it.
82Queued steering and follow-up messages return to the draft instead of being lost.
83Stopping while idle does nothing.
84Closing pivi or Neovim kills commands the agent started.
86## Failures and recovery
88Tool failures stay in the transcript; the model can recover without stopping the conversation.
89Provider backoff shows the provider's error and a retry countdown; `:Pivi stop` cancels waiting.
90Failed runs show `failed`, not `idle`, with the original error and recovery commands.
91Quota and authentication messages remain verbatim; pivi does not guess their meaning.
92Drafts and unsaved editor changes are not cleared by a failed run.
93`:Pivi login` repairs credentials; `:Pivi model` changes the model.
94`:Pivi continue` asks before continuing a stopped run from retained history without adding another prompt.
95Continuation may repeat actions; review existing edits first.
96`:Pivi resume` resumes interrupted Durable tasks after reconnecting, not a terminal provider failure.
97Disconnected winbars point to `:Pivi` for reconnecting.
98Retained work after reconnect shows `suspended`, not `working`; use `:Pivi resume` or `:Pivi stop`.
99Startup/storage failures and malformed worker records retain diagnostic text instead of resetting the session.
100Compaction failure keeps history intact; `:Pivi compact` explicitly retries after fixing the cause.
102## Review
104`<leader>pr` or `:Pivi review` shows every unsaved change against disk as one diff buffer and fills the quickfix list with the changes.
105The conversation winbar shows how many buffers are unsaved.
106Review keys: `<CR>` jump to the change, `s` save only that change, `r` revert only that change, `S` save the file, `R` revert the file after confirmation, `q` back.
107Saving one change writes the file with just that change applied and leaves the rest unsaved; reverting one change is undoable in its buffer.
108The review refreshes whenever it is entered, and covers your own unsaved edits as well as the agent's.
110`<leader>p?` shows the bindings that apply where the cursor is.
111`?` inside that popup opens the full, searchable binding help.
113Every pivi key is `vim.g.pivi_prefix` plus one character; the prefix defaults to `<leader>p`.
114Set `vim.g.pivi_prefix` before pivi loads to move them all, including the global `<prefix>p` that opens pivi.
115Pivi maps nothing outside that prefix in its conversation and draft buffers.
116Native `/`, `?`, folds, editing, registers remain available where applicable.
118Draft actions:
120- `<CR>` in normal mode sends the draft: submit while idle, steer while busy.
121- `<C-CR>` or `<C-J>` in the draft queues a follow-up. Insert mode is untouched.
122- `<Esc>` in the conversation stops work while busy.
124Prefixed actions (`vim.g.pivi_prefix`, default `<leader>p`):
126- `gb` in normal mode is the goblin operator: `gb}` sends a motion, `gbG` the rest of the buffer.
127- `gb` in visual mode sends the selection. `:Pivi goblin` sends the whole current buffer.
128- `vim.g.pivi_goblin_prompt` overrides the prompt goblin sends with the attachment.
129- `<leader>ps`: submit while idle.
130- `<leader>pt`: steer active run.
131- `<leader>pu`: queue follow-up.
132- `<leader>pa`: attach/open/remove buffer, file, or diagnostics context.
133- `<leader>po`: inspect attachment.
134- `<leader>px`: stop work.
135- `<leader>pr`: review unsaved changes.
137Attachments resolve through Neovim at submission time.
138Attachment labels appear in the draft window's winbar, not as virtual lines.
139Each attachment is appended to the submitted prompt as a `<buffer number name>...</buffer>` block.
140Diagnostics attachments are appended as a `<diagnostics ...>...</diagnostics>` block of `line:col SEVERITY message` lines.
141Files are loaded as buffers before attachment.
143Conversation actions:
145- `<leader>po`: inspect entry in a detail buffer.
146- `<leader>pf`: fork at committed entry under cursor.
147 On a prompt: new conversation holds the history before it, prompt returns as draft; refused while the draft is not empty.
148- `za`: native tool/thinking/result fold.
150Compaction summaries appear in the conversation as a folded `compacted` block.
152Commands are `attach`, `close`, `compact`, `continue`, `draft`, `earlier`, `fork`, `help`, `login`, `logout`, `model`, `new`, `resume`, `review`, `show`, `stop`.
153`new` and `fork` reject active work rather than silently interrupting it.
154`resume` explicitly resumes interrupted Durable tasks after the editor reconnects.
156## Models
158`:Pivi model` selects an available model.
159`:Pivi model provider/model-id` selects directly.
160Default runtime uses pi-ai built-in providers.
161A provider is usable through a stored sign-in or through its environment variables.
162`:Pivi model` lists only usable models; with none, it leads straight into sign-in.
163Normal Pi coding-agent providers, authentication files, settings, extensions, skills, and templates are not automatically loaded.
164No model requests happen merely by opening pivi; `:Pivi model` refreshes provider model catalogs.
166## Sign-in
168`:Pivi login [provider]` signs in; `:Pivi logout [provider]` removes a stored sign-in.
169The provider picker shows each provider's state: `●` signed in, `◐` ready through environment, `○` not set up.
170Providers offering both ask whether to use an account or an API key.
171API keys are typed into a masked prompt.
172Account sign-in shows a panel inside Neovim and opens the browser.
173Panel keys: `o` open browser, `y` copy link or device code, `p` paste a code by hand, `q` or `<Esc>` cancel.
174Closing the panel cancels the sign-in.
175After a first sign-in without a chosen model, the model picker opens for that provider.
177Credentials live in `stdpath('state')/pivi/auth.json`, mode 0600, shared by all pivi sessions.
178Writes are atomic and serialized across Neovim instances through a lock file, so token refresh cannot lose updates.
179Pi's own `~/.pi/agent/auth.json` is never read or written; sign in once per provider in pivi.
181`vim.g.pivi_node` optionally selects the Node executable.
182`vim.g.pivi_config` optionally names an absolute `.mjs` config path.
183Its default export is a function, sync or async, receiving `{ credentials }` and returning `{ models, extensions }`.
184Pass `credentials` to your own Models collection to keep sign-in working.
185`models` is a pi-ai Models collection; extension contributions currently use Durable's registry format.
186This bootstrap seam is not yet a stable pivi extension API.
188## Storage
190```text
191stdpath('state')/pivi/sessions/<PiviSession>/session.sqlite
192```
194One pivi session owns one Durable storage, containing multiple conversations and one active conversation reference.
195Cwd does not determine identity.
196`vim.g.PiviSession` is restored with Neovim session globals after pivi has been opened.
197No ShaDa dependency.
198Only one worker should open a given pivi session for writing.
200Closing/reopening the worker preserves draft buffers in the running Neovim instance.
201Draft text is recovered from its separate file, not SQLite.
202Unsaved workspace buffers and attachment selections are not recovered by pivi after Neovim exits.
203Abrupt termination can lose draft edits from the debounce interval.
204Old Pi coding-agent session files are neither migrated nor deleted.
206## Verification
208`just test-pivi` runs offline Durable tests, real editor/worker integration tests, and driven native-input tests.
209The input test types a draft while a deterministic provider streams, checks undo/redo against unchanged transcript, toggles buffers, then repeats.
210No external model calls are required.
212## Not implemented yet
214Native location metadata/actions, image attachments, custom interaction requests, richer terminal integration, MCP bridge, stable pivi extensions, delegation, model thinking picker, custom providers from Pi's `models.json`.
215No claim of legacy feature parity.

neovim/pivi/credentials.mjs

Added
new file mode 100644

+73 / −0 text lines

1import { mkdir, open, readFile, rename, rm, stat, writeFile } from 'node:fs/promises';
2import { dirname } from 'node:path';
3import { setTimeout as sleep } from 'node:timers/promises';
4
5const STALE_LOCK_MS = 60_000;
6
7export function fileCredentials(path) {
8 const lock = `${path}.lock`;
9 let queue = Promise.resolve();
11 async function load() {
12 try {
13 return JSON.parse(await readFile(path, 'utf8'));
14 } catch (error) {
15 if (error.code === 'ENOENT') return {};
16 throw error;
17 }
18 }
20 async function save(all) {
21 const temporary = `${path}.${process.pid}.tmp`;
22 await writeFile(temporary, JSON.stringify(all, null, 2), { mode: 0o600 });
23 await rename(temporary, path);
24 }
26 async function acquire() {
27 await mkdir(dirname(path), { recursive: true });
28 for (;;) {
29 try {
30 await (await open(lock, 'wx')).close();
31 return;
32 } catch (error) {
33 if (error.code !== 'EEXIST') throw error;
34 const age = Date.now() - (await stat(lock).catch(() => ({ mtimeMs: 0 }))).mtimeMs;
35 if (age > STALE_LOCK_MS) await rm(lock, { force: true });
36 else await sleep(50);
37 }
38 }
39 }
41 function exclusive(task) {
42 const result = queue.then(async () => {
43 await acquire();
44 try {
45 return await task(await load());
46 } finally {
47 await rm(lock, { force: true });
48 }
49 });
50 queue = result.catch(() => {});
51 return result;
52 }
54 return {
55 async read(provider) { return (await load())[provider]; },
56 async list() {
57 return Object.entries(await load()).map(([providerId, credential]) => ({ providerId, type: credential.type }));
58 },
59 modify(provider, change) {
60 return exclusive(async (all) => {
61 const next = await change(all[provider]);
62 if (next === undefined) return all[provider];
63 await save({ ...all, [provider]: next });
64 return next;
65 });
66 },
67 delete(provider) {
68 return exclusive(async ({ [provider]: removed, ...rest }) => {
69 if (removed !== undefined) await save(rest);
70 });
71 },
72 };
73}

neovim/pivi/env.mjs

Added
new file mode 100644

+79 / −0 text lines

1import { mkdtemp, rm, writeFile } from 'node:fs/promises';
2import { tmpdir } from 'node:os';
3import { basename, join, relative, resolve } from 'node:path';
4import { err, FileError, ok } from '@earendil-works/pi-durable/env';
5import { NodeExecutionEnv } from '@earendil-works/pi-durable/env/node';
6
7export class NeovimExecutionEnv extends NodeExecutionEnv {
8 #editor;
9
10 constructor({ cwd, editor }) {
11 super({ cwd });
12 this.id = 'pivi-neovim';
13 this.#editor = editor;
14 }
16 async #unsaved(path, context) {
17 return (await this.#editor('unsaved_text', { path: resolve(this.cwd, path) }, context))?.text;
18 }
20 async readTextFile(path, context) {
21 const text = await this.#unsaved(path, context);
22 return text === undefined ? super.readTextFile(path, context) : ok(text);
23 }
25 async readBinaryFile(path, context) {
26 const text = await this.#unsaved(path, context);
27 return text === undefined ? super.readBinaryFile(path, context) : ok(new TextEncoder().encode(text));
28 }
30 async exists(path, context) {
31 const onDisk = await super.exists(path, context);
32 if (onDisk.ok && onDisk.value) return onDisk;
33 return (await this.#unsaved(path, context)) === undefined ? onDisk : ok(true);
34 }
36 async fileInfo(path, context) {
37 const text = await this.#unsaved(path, context);
38 if (text === undefined) return super.fileInfo(path, context);
39 const absolute = resolve(this.cwd, path);
40 const size = Buffer.byteLength(text);
41 return ok({ name: basename(absolute), path: absolute, kind: 'file', size, mtimeMs: Date.now() });
42 }
44 async openBinaryReader(path, options, context) {
45 const text = await this.#unsaved(path, context);
46 if (text === undefined) return super.openBinaryReader(path, options, context);
47 const directory = await mkdtemp(join(tmpdir(), 'pivi-buffer-'));
48 const discard = () => rm(directory, { recursive: true, force: true });
49 const snapshot = join(directory, basename(path));
50 await writeFile(snapshot, text);
51 const opened = await super.openBinaryReader(snapshot, options, context);
52 if (!opened.ok) {
53 await discard();
54 return opened;
55 }
56 const reader = opened.value;
57 return ok({
58 info: (inner) => reader.info(inner),
59 read: (offset, length, inner) => reader.read(offset, length, inner),
60 scanLines: (range, inner) => reader.scanLines(range, inner),
61 async close(inner) {
62 await reader.close(inner);
63 await discard();
64 },
65 });
66 }
68 async writeFile(path, content, context) {
69 const absolute = resolve(this.cwd, path);
70 const workspace = !relative(this.cwd, absolute).startsWith('..');
71 if (typeof content !== 'string' || !workspace) return super.writeFile(path, content, context);
72 try {
73 await this.#editor('set_text', { path: absolute, content }, context);
74 return ok(undefined);
75 } catch (error) {
76 return err(new FileError('unknown', error.message, absolute));
77 }
78 }
79}

neovim/pivi/harness.mjs

Added
new file mode 100644

+195 / −0 text lines

1import { readFile, writeFile } from 'node:fs/promises';
2import { BACKGROUND_CONTEXT as context } from '@earendil-works/chord/context';
3import { InMemoryCredentialStore } from '@earendil-works/pi-ai';
4import { builtinModels } from '@earendil-works/pi-ai/providers/all';
5import { CodemodeSandbox } from '@earendil-works/pi-codemode';
6import {
7 Harness, LiveDoc, ConversationTranscript, createRegistry, defineDoc, defineExtension,
8} from '@earendil-works/pi-durable';
9import { createCodemodeExtension } from '@earendil-works/pi-durable/codemode';
10import { createEditTool, createReadTool, createWriteTool } from '@earendil-works/pi-durable/tools';
11import { openNodeSqliteStorage } from '@earendil-works/pi-durable/storage/sqlite/node';
12import { NeovimExecutionEnv } from './env.mjs';
13import { neovim } from './tools.mjs';
15const Session = defineDoc({
16 kind: 'pivi.session',
17 version: 1,
18 scope: 'session',
19 initial: () => ({ active: null }),
20 checkpointWhen: () => true,
21});
23const SUBMISSION = {
24 submit: { whenBusy: 'reject' },
25 steer: { whenBusy: 'steer', whenIdle: 'reject' },
26 followUp: { whenBusy: 'followUp', whenIdle: 'reject' },
27};
29export async function openPivi({
30 database, editor, interact, onView, onReport, onNotice, cwd = process.cwd(), modelFile,
31 credentials = new InMemoryCredentialStore(), models = builtinModels({ credentials }), extensions = [],
32}) {
33 const storage = await openNodeSqliteStorage(database);
34 const sandbox = new CodemodeSandbox();
35 let harness;
36 try {
37 const registry = createRegistry();
38 const files = defineExtension({
39 name: 'pivi.files',
40 tools: [createReadTool(), createEditTool(), createWriteTool()],
41 });
42 for (const extension of [files, neovim(editor), createCodemodeExtension({ sandbox }), ...extensions]) {
43 registry.install(extension);
44 }
45 const environment = new NeovimExecutionEnv({ cwd, editor });
46 harness = await Harness.open(storage, { models, registry, onReport, env: () => environment }, context);
47 let conversation;
48 let transcript;
49 let watch;
50 let login;
51 const show = async (view) => onView?.({
52 ...transcript.merge(view), scheduling: (await harness.inspect(context)).scheduling,
53 });
55 async function activate(next) {
56 await watch?.stop();
57 conversation = next;
58 transcript = new ConversationTranscript((query, limit, callContext) =>
59 next.entries(query, limit, undefined, callContext));
60 await harness.commit(async (tx) => { (await tx.doc(Session)).active = next.id; }, context);
61 watch = await next.watch(context);
62 await show(watch.value);
63 watch.start(async (call) => { if (call.kind === 'value') await show(call.value); });
64 }
66 async function requireIdle() {
67 const live = await harness.snapshot(LiveDoc, conversation.id, context);
68 if (live?.run || live?.compactions?.length) throw new Error('Stop active work before changing conversation.');
69 }
71 const active = (await harness.snapshot(Session, context))?.active;
72 await activate((active != null && await harness.conversation(active, context)) || await harness.root(context));
74 // A new session keeps the model the last one used, when the provider still offers it.
75 if (modelFile && !(await conversation.agent(context)).model) {
76 try {
77 const saved = JSON.parse(await readFile(modelFile, 'utf8'));
78 if (models.getModel(saved.provider, saved.modelId)) {
79 await conversation.configure({ model: saved }, context);
80 }
81 } catch {
82 // No usable saved model: pick one with :Pivi model.
83 }
84 }
86 return {
87 harness,
88 get conversation() { return conversation; },
89 async close() {
90 await watch.stop();
91 await harness.close(context);
92 await sandbox.close();
93 },
94 commands: {
95 async submit({ content, mode = 'submit' }) {
96 if (!Object.hasOwn(SUBMISSION, mode)) throw new Error(`Unknown submission mode: ${mode}`);
97 if (!(await conversation.agent(context)).model) throw new Error('Choose a model with :Pivi model first.');
98 const submission = await conversation.submit({ type: 'input', content, ...SUBMISSION[mode] }, context);
99 return { id: submission.id };
100 },
101 async models() {
102 await models.refresh();
103 return (await models.getAvailable()).map(({ provider, id }) => ({ provider, modelId: id }));
104 },
105 async configure({ model }) {
106 if (!models.getModel(model.provider, model.modelId)) throw new Error('Unknown model.');
107 await conversation.configure({ model }, context);
108 if (modelFile) await writeFile(modelFile, JSON.stringify(model), 'utf8').catch(() => {});
109 },
110 async compact({ instructions }) {
111 const task = await conversation.compact(instructions || undefined, context);
112 harness.waitForTask(task, context).then(({ state: { outcome } }) => {
113 const { entryId, submissionId } = outcome.result ?? {};
114 if (outcome.status === 'completed' && !entryId && !submissionId) {
115 onNotice?.('Nothing to compact yet: the conversation is still short.');
116 }
117 }, () => {});
118 },
119 async earlier() {
120 const current = watch.value;
121 const view = await transcript.loadEarlier(context);
122 if (view.items === current.items || view.items?.length === current.items?.length) {
123 onNotice?.('No earlier entries: the transcript already starts here.');
124 }
125 await onView?.({ ...view, scheduling: (await harness.inspect(context)).scheduling });
126 },
127 async resume() {
128 const { tasks } = await harness.inspect(context);
129 harness.resume();
130 if (!tasks.length) onNotice?.('Nothing suspended in this session to resume.');
131 await show(watch.value);
132 },
133 async continue() {
134 await requireIdle();
135 const live = await harness.snapshot(LiveDoc, conversation.id, context);
136 if (!live?.runFailure) throw new Error('No stopped run to continue. Write a new draft instead.');
137 await conversation.submit({ type: 'continue' }, context);
138 },
139 async new() {
140 await requireIdle();
141 const { model } = await conversation.agent(context);
142 const options = { ownership: { kind: 'ownerless' }, agent: { model } };
143 await activate(await harness.createConversation(options, context));
144 },
145 async fork({ entry }) {
146 await requireIdle();
147 await activate(await conversation.fork(entry, { ownership: { kind: 'ownerless' } }, context));
148 },
149 },
150 immediate: {
151 async abort() {
152 const running = (await harness.snapshot(LiveDoc, conversation.id, context))?.run !== undefined;
153 await conversation.abort(context);
154 if (!running) return;
155 const message = { role: 'user', content: [{ type: 'text', text: '[interrupted]' }], timestamp: Date.now() };
156 const entry = { kind: 'pivi.interrupted', data: null, model: [message] };
157 await conversation.submit({ type: 'write', entry }, context);
158 },
159 async providers() {
160 const stored = new Map((await credentials.list()).map(({ providerId, type }) => [providerId, type]));
161 return Promise.all(models.getProviders().map(async ({ id, name, auth }) => ({
162 id,
163 name,
164 stored: stored.get(id),
165 source: (await models.checkAuth(id).catch(() => undefined))?.source,
166 methods: [
167 auth.oauth && { type: 'oauth', label: auth.oauth.loginLabel ?? auth.oauth.name },
168 auth.apiKey?.login && { type: 'api_key', label: auth.apiKey.name },
169 ].filter(Boolean),
170 })));
171 },
172 async login({ provider, method }) {
173 if (login) throw new Error('Another sign-in is in progress.');
174 login = new AbortController();
175 try {
176 const { signal } = login;
177 const prompt = (request) => interact.prompt({
178 ...request, signal: request.signal ? AbortSignal.any([request.signal, signal]) : signal,
179 });
180 await models.login(provider, method, { signal, prompt, notify: interact.notify });
181 await models.refresh({ providers: [provider] });
182 } finally {
183 login = undefined;
184 }
185 },
186 async cancel() { login?.abort(); },
187 async logout({ provider }) { await models.logout(provider); },
188 },
189 };
190 } catch (error) {
191 await sandbox.close();
192 await (harness ?? storage).close(context);
193 throw error;
194 }
195}

neovim/pivi/package-lock.json

Added
new file mode 100644

+1236 / −0 text lines

1{
2 "name": "pivi",
3 "lockfileVersion": 3,
4 "requires": true,
5 "packages": {
6 "": {
7 "name": "pivi",
8 "dependencies": {
9 "@earendil-works/chord": "1.5.2",
10 "@earendil-works/pi-ai": "1.5.2",
11 "@earendil-works/pi-codemode": "1.5.2",
12 "@earendil-works/pi-durable": "1.5.2",
13 "@earendil-works/pi-schema": "1.5.2"
14 },
15 "engines": {
16 "node": ">=22.19.0"
17 }
18 },
19 "node_modules/@anthropic-ai/sdk": {
20 "version": "0.129.0",
21 "resolved": "https://registry.npmjs.org/@anthropic-ai/sdk/-/sdk-0.129.0.tgz",
22 "integrity": "sha512-MH7LB20kNpGLUpPTe2OG5XvL/KhX8HUO9XyBaFjgFk6TLS4Xjt0VPIuMKywe7POKKPslX+QxSlVok9e+8kG5Nw==",
23 "license": "MIT",
24 "dependencies": {
25 "json-schema-to-ts": "^3.1.1",
26 "standardwebhooks": "^1.0.0"
27 },
28 "bin": {
29 "anthropic-ai-sdk": "bin/cli"
30 },
31 "peerDependencies": {
32 "zod": "^3.25.0 || ^4.0.0"
33 },
34 "peerDependenciesMeta": {
35 "zod": {
36 "optional": true
37 }
38 }
39 },
40 "node_modules/@aws-sdk/client-bedrock-runtime": {
41 "version": "3.1127.0",
42 "resolved": "https://registry.npmjs.org/@aws-sdk/client-bedrock-runtime/-/client-bedrock-runtime-3.1127.0.tgz",
43 "integrity": "sha512-IDl/lrPb90aH+pZFHGNDmgH9nAUQj5PlZH1sJ3w7RikctyjHSnY3oNjZhrLoaBoQn/rNK0zsP6OHEqEhj2tdLA==",
44 "license": "Apache-2.0",
45 "dependencies": {
46 "@aws-sdk/core": "^3.977.9",
47 "@aws-sdk/credential-provider-node": "^3.972.82",
48 "@aws-sdk/eventstream-handler-node": "^3.972.34",
49 "@aws-sdk/middleware-eventstream": "^3.972.29",
50 "@aws-sdk/middleware-websocket": "^3.972.52",
51 "@aws-sdk/token-providers": "3.1127.0",
52 "@aws-sdk/types": "^3.974.5",
53 "@smithy/core": "^3.33.3",
54 "@smithy/fetch-http-handler": "^5.7.2",
55 "@smithy/node-http-handler": "^4.11.3",
56 "@smithy/types": "^4.17.2",
57 "tslib": "^2.6.2"
58 },
59 "engines": {
60 "node": ">=20.0.0"
61 }
62 },
63 "node_modules/@aws-sdk/core": {
64 "version": "3.981.0",
65 "resolved": "https://registry.npmjs.org/@aws-sdk/core/-/core-3.981.0.tgz",
66 "integrity": "sha512-Mnu7gaDrC5UCdyH8uLxLfB2eWbjE/HbjKX1U1J2VQxG3TTATUDObW2wU3I8iH3e9YH5NN2CY6w1mlAIe2XJ3jg==",
67 "license": "Apache-2.0",
68 "dependencies": {
69 "@aws-sdk/types": "^3.975.1",
70 "@aws-sdk/xml-builder": "^3.972.43",
71 "@aws/lambda-invoke-store": "^0.3.0",
72 "@smithy/core": "^3.40.0",
73 "@smithy/signature-v4": "^5.7.5",
74 "@smithy/types": "^4.20.0",
75 "bowser": "^2.11.0",
76 "tslib": "^2.6.2"
77 },
78 "engines": {
79 "node": ">=20.0.0"
80 }
81 },
82 "node_modules/@aws-sdk/credential-provider-env": {
83 "version": "3.972.84",
84 "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-env/-/credential-provider-env-3.972.84.tgz",
85 "integrity": "sha512-akZJetiMVeLRHsKzYh3LamDCo74ZUCeo0XoyRKMEMZT5qP7ReM6LhpioBCyuqKP5Vav5gEOeCmaQV0VVQr1Meg==",
86 "license": "Apache-2.0",
87 "dependencies": {
88 "@aws-sdk/core": "^3.981.0",
89 "@aws-sdk/types": "^3.975.1",
90 "@smithy/core": "^3.40.0",
91 "@smithy/types": "^4.20.0",
92 "tslib": "^2.6.2"
93 },
94 "engines": {
95 "node": ">=20.0.0"
96 }
97 },
98 "node_modules/@aws-sdk/credential-provider-http": {
99 "version": "3.972.86",
100 "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-http/-/credential-provider-http-3.972.86.tgz",
101 "integrity": "sha512-U4mHaDRPWAn63yhl7FXIzbppNmW1F+4dSLeuiUpej2v3Xb6rGwvayEJ8SdlrdMV+/mZtd+GStTEP2HqurEzXtw==",
102 "license": "Apache-2.0",
103 "dependencies": {
104 "@aws-sdk/core": "^3.981.0",
105 "@aws-sdk/types": "^3.975.1",
106 "@smithy/core": "^3.40.0",
107 "@smithy/fetch-http-handler": "^5.8.1",
108 "@smithy/node-http-handler": "^4.14.2",
109 "@smithy/types": "^4.20.0",
110 "tslib": "^2.6.2"
111 },
112 "engines": {
113 "node": ">=20.0.0"
114 }
115 },
116 "node_modules/@aws-sdk/credential-provider-http/node_modules/@smithy/node-http-handler": {
117 "version": "4.14.2",
118 "resolved": "https://registry.npmjs.org/@smithy/node-http-handler/-/node-http-handler-4.14.2.tgz",
119 "integrity": "sha512-i1uORV1v3qBqP43ayRKzIdm1q5x14tf8N4Dd06/QUX1Szm6VxHMrTsu20X5E63UFsaNZCRjI4SXG0jDmqYa+3w==",
120 "license": "Apache-2.0",
121 "dependencies": {
122 "@smithy/core": "^3.39.0",
123 "@smithy/types": "^4.20.0",
124 "tslib": "^2.6.2"
125 },
126 "engines": {
127 "node": ">=18.0.0"
128 }
129 },
130 "node_modules/@aws-sdk/credential-provider-ini": {
131 "version": "3.973.30",
132 "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-ini/-/credential-provider-ini-3.973.30.tgz",
133 "integrity": "sha512-r6r6499GWoGN943NA5YEhBEQ6TEOGTf7tTOBhHd/zw0UbNvSzd1/zPCNcDkPmRarA+e24X7KgxutqxjoWcskBg==",
134 "license": "Apache-2.0",
135 "dependencies": {
136 "@aws-sdk/core": "^3.981.0",
137 "@aws-sdk/credential-provider-env": "^3.972.84",
138 "@aws-sdk/credential-provider-http": "^3.972.86",
139 "@aws-sdk/credential-provider-login": "^3.972.92",
140 "@aws-sdk/credential-provider-process": "^3.972.84",
141 "@aws-sdk/credential-provider-sso": "^3.973.28",
142 "@aws-sdk/credential-provider-web-identity": "^3.972.90",
143 "@aws-sdk/nested-clients": "^3.998.3",
144 "@aws-sdk/types": "^3.975.1",
145 "@smithy/core": "^3.40.0",
146 "@smithy/credential-provider-imds": "^4.5.2",
147 "@smithy/types": "^4.20.0",
148 "tslib": "^2.6.2"
149 },
150 "engines": {
151 "node": ">=20.0.0"
152 }
153 },
154 "node_modules/@aws-sdk/credential-provider-login": {
155 "version": "3.972.92",
156 "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-login/-/credential-provider-login-3.972.92.tgz",
157 "integrity": "sha512-96bcp9Pe/Xd60OEwncZ+kAQTQSu+fJnpUGz1qE6ghF5jnETmrk8XMU86mIP3lolvnCgR61XbZ+Ht6hdBjiQOmQ==",
158 "license": "Apache-2.0",
159 "dependencies": {
160 "@aws-sdk/core": "^3.981.0",
161 "@aws-sdk/nested-clients": "^3.998.3",
162 "@aws-sdk/types": "^3.975.1",
163 "@smithy/core": "^3.40.0",
164 "@smithy/types": "^4.20.0",
165 "tslib": "^2.6.2"
166 },
167 "engines": {
168 "node": ">=20.0.0"
169 }
170 },
171 "node_modules/@aws-sdk/credential-provider-node": {
172 "version": "3.972.97",
173 "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-node/-/credential-provider-node-3.972.97.tgz",
174 "integrity": "sha512-E4a0IXXJVsIdo/K9roX4JAEfI0JJr7KTPymkbKgETRDqEcLygE4ZlLTe24+7Qkh8Dl5YpnPd+Tt0DOPJDFXIwA==",
175 "license": "Apache-2.0",
176 "dependencies": {
177 "@aws-sdk/credential-provider-env": "^3.972.84",
178 "@aws-sdk/credential-provider-http": "^3.972.86",
179 "@aws-sdk/credential-provider-ini": "^3.973.30",
180 "@aws-sdk/credential-provider-process": "^3.972.84",
181 "@aws-sdk/credential-provider-sso": "^3.973.28",
182 "@aws-sdk/credential-provider-web-identity": "^3.972.90",
183 "@aws-sdk/types": "^3.975.1",
184 "@smithy/core": "^3.40.0",
185 "@smithy/credential-provider-imds": "^4.5.2",
186 "@smithy/types": "^4.20.0",
187 "tslib": "^2.6.2"
188 },
189 "engines": {
190 "node": ">=20.0.0"
191 }
192 },
193 "node_modules/@aws-sdk/credential-provider-process": {
194 "version": "3.972.84",
195 "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-process/-/credential-provider-process-3.972.84.tgz",
196 "integrity": "sha512-199C6OpNejd0nq9GFAkEFIKids1FL0R6LJtL9c1OTiDOXki7S1OduuPxW4+hE0LwndcYJ7YHOuYTlqScfpCocA==",
197 "license": "Apache-2.0",
198 "dependencies": {
199 "@aws-sdk/core": "^3.981.0",
200 "@aws-sdk/types": "^3.975.1",
201 "@smithy/core": "^3.40.0",
202 "@smithy/types": "^4.20.0",
203 "tslib": "^2.6.2"
204 },
205 "engines": {
206 "node": ">=20.0.0"
207 }
208 },
209 "node_modules/@aws-sdk/credential-provider-sso": {
210 "version": "3.973.28",
211 "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-sso/-/credential-provider-sso-3.973.28.tgz",
212 "integrity": "sha512-bGg7wH8wVDJQIcJggO9lg1ZYbG7l+PbLwHuM3Bi/e1TlCZhU712JS1W3tdRpyptdJD1UGyhBNGO/YrhrQCHKbg==",
213 "license": "Apache-2.0",
214 "dependencies": {
215 "@aws-sdk/core": "^3.981.0",
216 "@aws-sdk/nested-clients": "^3.998.3",
217 "@aws-sdk/token-providers": "3.1166.0",
218 "@aws-sdk/types": "^3.975.1",
219 "@smithy/core": "^3.40.0",
220 "@smithy/types": "^4.20.0",
221 "tslib": "^2.6.2"
222 },
223 "engines": {
224 "node": ">=20.0.0"
225 }
226 },
227 "node_modules/@aws-sdk/credential-provider-sso/node_modules/@aws-sdk/token-providers": {
228 "version": "3.1166.0",
229 "resolved": "https://registry.npmjs.org/@aws-sdk/token-providers/-/token-providers-3.1166.0.tgz",
230 "integrity": "sha512-ngJ8mxXqtQ9mnp7QV6TWKJCxkpjVfPWxKQSc2FYhCyCfOVFIGdFv7P+/RqVffFrJAorwBPpktnv32gNlcEgF4g==",
231 "license": "Apache-2.0",
232 "dependencies": {
233 "@aws-sdk/core": "^3.981.0",
234 "@aws-sdk/nested-clients": "^3.998.3",
235 "@aws-sdk/types": "^3.975.1",
236 "@smithy/core": "^3.40.0",
237 "@smithy/types": "^4.20.0",
238 "tslib": "^2.6.2"
239 },
240 "engines": {
241 "node": ">=20.0.0"
242 }
243 },
244 "node_modules/@aws-sdk/credential-provider-web-identity": {
245 "version": "3.972.90",
246 "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-web-identity/-/credential-provider-web-identity-3.972.90.tgz",
247 "integrity": "sha512-duLeE3xlf0viHeH+1RM4z5duR3b32BCZTWVMu+MbxFPjQBxy7hmIGEqt5hekuFPRuXoyhMovjNl+PNNsb5oiGQ==",
248 "license": "Apache-2.0",
249 "dependencies": {
250 "@aws-sdk/core": "^3.981.0",
251 "@aws-sdk/nested-clients": "^3.998.3",
252 "@aws-sdk/types": "^3.975.1",
253 "@smithy/core": "^3.40.0",
254 "@smithy/types": "^4.20.0",
255 "tslib": "^2.6.2"
256 },
257 "engines": {
258 "node": ">=20.0.0"
259 }
260 },
261 "node_modules/@aws-sdk/eventstream-handler-node": {
262 "version": "3.972.42",
263 "resolved": "https://registry.npmjs.org/@aws-sdk/eventstream-handler-node/-/eventstream-handler-node-3.972.42.tgz",
264 "integrity": "sha512-YVB1wrpE1WF8NvMpaRyhwm9XBYl3HTbPNEIgybi0b0XpmBrJ7Y3Y/drbxh9qAVMbR+0hcwM63GPWzhOVRuerfg==",
265 "license": "Apache-2.0",
266 "dependencies": {
267 "@aws-sdk/types": "^3.975.1",
268 "@smithy/core": "^3.40.0",
269 "@smithy/types": "^4.20.0",
270 "tslib": "^2.6.2"
271 },
272 "engines": {
273 "node": ">=20.0.0"
274 }
275 },
276 "node_modules/@aws-sdk/middleware-eventstream": {
277 "version": "3.972.38",
278 "resolved": "https://registry.npmjs.org/@aws-sdk/middleware-eventstream/-/middleware-eventstream-3.972.38.tgz",
279 "integrity": "sha512-4K6FDz2BxH3rve8Hw/8uApWXKCuKKMeYKzY23PoiGqUBWaA23eAy+GzW9aoG3Cm7HqgYzqkljl3ECJRJCxGs7g==",
280 "license": "Apache-2.0",
281 "dependencies": {
282 "@aws-sdk/types": "^3.975.1",
283 "@smithy/core": "^3.40.0",
284 "@smithy/types": "^4.20.0",
285 "tslib": "^2.6.2"
286 },
287 "engines": {
288 "node": ">=20.0.0"
289 }
290 },
291 "node_modules/@aws-sdk/middleware-websocket": {
292 "version": "3.972.66",
293 "resolved": "https://registry.npmjs.org/@aws-sdk/middleware-websocket/-/middleware-websocket-3.972.66.tgz",
294 "integrity": "sha512-feGNDB15ZgqX4DTsUykkgj7d8hzfzx03v80EIyRA1FTbsbAJQKxYB50kRbrrpE5WeFaWhgk+p5YHlsoyXrI2/g==",
295 "license": "Apache-2.0",
296 "dependencies": {
297 "@aws-sdk/core": "^3.981.0",
298 "@aws-sdk/types": "^3.975.1",
299 "@smithy/core": "^3.40.0",
300 "@smithy/fetch-http-handler": "^5.8.1",
301 "@smithy/signature-v4": "^5.7.5",
302 "@smithy/types": "^4.20.0",
303 "tslib": "^2.6.2"
304 },
305 "engines": {
306 "node": ">= 14.0.0"
307 }
308 },
309 "node_modules/@aws-sdk/nested-clients": {
310 "version": "3.998.3",
311 "resolved": "https://registry.npmjs.org/@aws-sdk/nested-clients/-/nested-clients-3.998.3.tgz",
312 "integrity": "sha512-acHTTzMB13CU6dU4sxABYExMI3PQM2zStWH2MiUwJp/7QKTrLg2f7mbzSXoegW2kYOk2tdqQYagsZrWB8Xv7eA==",
313 "license": "Apache-2.0",
314 "dependencies": {
315 "@aws-sdk/core": "^3.981.0",
316 "@aws-sdk/signature-v4-multi-region": "^3.996.52",
317 "@aws-sdk/types": "^3.975.1",
318 "@smithy/core": "^3.40.0",
319 "@smithy/fetch-http-handler": "^5.8.1",
320 "@smithy/node-http-handler": "^4.14.2",
321 "@smithy/types": "^4.20.0",
322 "tslib": "^2.6.2"
323 },
324 "engines": {
325 "node": ">=20.0.0"
326 }
327 },
328 "node_modules/@aws-sdk/nested-clients/node_modules/@smithy/node-http-handler": {
329 "version": "4.14.2",
330 "resolved": "https://registry.npmjs.org/@smithy/node-http-handler/-/node-http-handler-4.14.2.tgz",
331 "integrity": "sha512-i1uORV1v3qBqP43ayRKzIdm1q5x14tf8N4Dd06/QUX1Szm6VxHMrTsu20X5E63UFsaNZCRjI4SXG0jDmqYa+3w==",
332 "license": "Apache-2.0",
333 "dependencies": {
334 "@smithy/core": "^3.39.0",
335 "@smithy/types": "^4.20.0",
336 "tslib": "^2.6.2"
337 },
338 "engines": {
339 "node": ">=18.0.0"
340 }
341 },
342 "node_modules/@aws-sdk/signature-v4-multi-region": {
343 "version": "3.996.52",
344 "resolved": "https://registry.npmjs.org/@aws-sdk/signature-v4-multi-region/-/signature-v4-multi-region-3.996.52.tgz",
345 "integrity": "sha512-6W6SjGc8OXUhMzNxU1X922ghD+PP1XvzmCk5Scui0jaYsLezycMYR1RaLp5xTIOUrhTXyb4DnAbPr3fBgmdnzg==",
346 "license": "Apache-2.0",
347 "dependencies": {
348 "@aws-sdk/types": "^3.975.1",
349 "@smithy/signature-v4": "^5.7.5",
350 "@smithy/types": "^4.20.0",
351 "tslib": "^2.6.2"
352 },
353 "engines": {
354 "node": ">=20.0.0"
355 }
356 },
357 "node_modules/@aws-sdk/token-providers": {
358 "version": "3.1127.0",
359 "resolved": "https://registry.npmjs.org/@aws-sdk/token-providers/-/token-providers-3.1127.0.tgz",
360 "integrity": "sha512-Dv2TMWBshJ+tF6ahs2Sy5bh4Iabsd4GAQqVvE9XZmYmnoaVbpS2QKIKE/HRacc7bTtbjEEvP+laGzHvHlf1CiQ==",
361 "license": "Apache-2.0",
362 "dependencies": {
363 "@aws-sdk/core": "^3.977.9",
364 "@aws-sdk/nested-clients": "^3.997.44",
365 "@aws-sdk/types": "^3.974.5",
366 "@smithy/core": "^3.33.3",
367 "@smithy/types": "^4.17.2",
368 "tslib": "^2.6.2"
369 },
370 "engines": {
371 "node": ">=20.0.0"
372 }
373 },
374 "node_modules/@aws-sdk/types": {
375 "version": "3.975.1",
376 "resolved": "https://registry.npmjs.org/@aws-sdk/types/-/types-3.975.1.tgz",
377 "integrity": "sha512-7rGxUkCB2QPoQOeJmonmAICTN2zrH+fpmi1p4Iwu72lnxNaMhOgqcbpyddifnM1DBb19TWQ1u6z/XjkaFNEDWw==",
378 "license": "Apache-2.0",
379 "dependencies": {
380 "@smithy/types": "^4.20.0",
381 "tslib": "^2.6.2"
382 },
383 "engines": {
384 "node": ">=20.0.0"
385 }
386 },
387 "node_modules/@aws-sdk/xml-builder": {
388 "version": "3.972.43",
389 "resolved": "https://registry.npmjs.org/@aws-sdk/xml-builder/-/xml-builder-3.972.43.tgz",
390 "integrity": "sha512-rG8QVx4DOrJWptsogu1Aq+CDsnPKaBrAlJpKLxrJrIDXAq1ElnW0yQjjBnlWSXll0cDakCG6UDvaqwz0A9d9Og==",
391 "license": "Apache-2.0",
392 "dependencies": {
393 "@smithy/types": "^4.20.0",
394 "tslib": "^2.6.2"
395 },
396 "engines": {
397 "node": ">=20.0.0"
398 }
399 },
400 "node_modules/@aws/lambda-invoke-store": {
401 "version": "0.3.0",
402 "resolved": "https://registry.npmjs.org/@aws/lambda-invoke-store/-/lambda-invoke-store-0.3.0.tgz",
403 "integrity": "sha512-sl4Bm6yiMNYrZKkqqDFWN0UfnWhlS8ivKxrYl+6t0gCLrqr8y3B2IqZZbFRkfaVVp7C/baApyh71P+LeE1A2sQ==",
404 "license": "Apache-2.0",
405 "engines": {
406 "node": ">=18.0.0"
407 }
408 },
409 "node_modules/@babel/runtime": {
410 "version": "7.29.14",
411 "resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.29.14.tgz",
412 "integrity": "sha512-Y5tqevQaUAZhhj82BpYMNC1ssvLQTVAfwKdm8iy8qwmhvC2/CpcAu8OC+QEtjM7pMk7knx83u1Qj8gzkicyelw==",
413 "license": "MIT",
414 "engines": {
415 "node": ">=6.9.0"
416 }
417 },
418 "node_modules/@earendil-works/chord": {
419 "version": "1.5.2",
420 "resolved": "https://registry.npmjs.org/@earendil-works/chord/-/chord-1.5.2.tgz",
421 "integrity": "sha512-3g088g7qVXL2cpRAKWjj9za6RLls9FBnuUo5c0hBZ0xCftBQjae0opS+34M22vdXTVE7BNqkRG/FPc9BsM7eEg==",
422 "license": "MIT",
423 "dependencies": {
424 "@earendil-works/pi-schema": "1.5.2",
425 "@earendil-works/pi-telemetry": "1.5.2"
426 },
427 "engines": {
428 "node": ">=22.19.0"
429 },
430 "peerDependencies": {
431 "esbuild": "0.28.2",
432 "react": "19.3.0",
433 "ws": "8.21.0"
434 },
435 "peerDependenciesMeta": {
436 "esbuild": {
437 "optional": true
438 },
439 "react": {
440 "optional": true
441 },
442 "ws": {
443 "optional": true
444 }
445 }
446 },
447 "node_modules/@earendil-works/pi-ai": {
448 "version": "1.5.2",
449 "resolved": "https://registry.npmjs.org/@earendil-works/pi-ai/-/pi-ai-1.5.2.tgz",
450 "integrity": "sha512-2tWPSnV3qzfiDIY3aWluBag3vC++Vs+VsXt/UquSU5onPMohPih72FUhIhaqmDdMYubOgB3Byl9uF4Vk40JLvQ==",
451 "license": "MIT",
452 "dependencies": {
453 "@anthropic-ai/sdk": "0.129.0",
454 "@aws-sdk/client-bedrock-runtime": "3.1127.0",
455 "@earendil-works/pi-schema": "1.5.2",
456 "@earendil-works/pi-telemetry": "1.5.2",
457 "@google/genai": "2.21.0",
458 "@smithy/node-http-handler": "4.12.1",
459 "http-proxy-agent": "9.1.0",
460 "https-proxy-agent": "9.1.0",
461 "openai": "7.19.0",
462 "partial-json": "0.1.7"
463 },
464 "bin": {
465 "pi-ai": "dist/cli.js"
466 },
467 "engines": {
468 "node": ">=22.19.0"
469 }
470 },
471 "node_modules/@earendil-works/pi-codemode": {
472 "version": "1.5.2",
473 "resolved": "https://registry.npmjs.org/@earendil-works/pi-codemode/-/pi-codemode-1.5.2.tgz",
474 "integrity": "sha512-HoZQ40a9RgdZ1VgmrX6x8887cNXedaRJT1l+Ie5YRIMK4gY7v0EpsiNqf6dmixrKylZlTgUSyR+vE8xhjfkr+w==",
475 "license": "MIT",
476 "dependencies": {
477 "quickjs-wasi": "3.6.2"
478 },
479 "engines": {
480 "node": ">=22.19.0"
481 }
482 },
483 "node_modules/@earendil-works/pi-durable": {
484 "version": "1.5.2",
485 "resolved": "https://registry.npmjs.org/@earendil-works/pi-durable/-/pi-durable-1.5.2.tgz",
486 "integrity": "sha512-zDB3anbI/yD0IG+VVY+g5tU+c5XOVqQAFwLkXRMiqZb4p/afWro0voZtLNoRAWcDA2r73kvmH6kKin9Ka8l55g==",
487 "license": "MIT",
488 "dependencies": {
489 "@earendil-works/chord": "1.5.2",
490 "@earendil-works/pi-ai": "1.5.2",
491 "@earendil-works/pi-codemode": "1.5.2",
492 "@earendil-works/pi-schema": "1.5.2",
493 "@earendil-works/pi-telemetry": "1.5.2",
494 "@silvia-odwyer/photon": "0.3.3",
495 "diff": "8.0.4"
496 },
497 "engines": {
498 "node": ">=22.19.0"
499 }
500 },
501 "node_modules/@earendil-works/pi-schema": {
502 "version": "1.5.2",
503 "resolved": "https://registry.npmjs.org/@earendil-works/pi-schema/-/pi-schema-1.5.2.tgz",
504 "integrity": "sha512-hJoyCXWUhsSrXY5wJo2Q4kHXUsR51pNhkJHAMkWRwVMLDRtMDPkKNaa+JlVRVqTw1hjdSxcVVaFLSDbKlaTXEQ==",
505 "license": "MIT",
506 "engines": {
507 "node": ">=22.19.0"
508 }
509 },
510 "node_modules/@earendil-works/pi-telemetry": {
511 "version": "1.5.2",
512 "resolved": "https://registry.npmjs.org/@earendil-works/pi-telemetry/-/pi-telemetry-1.5.2.tgz",
513 "integrity": "sha512-m+cumjIqNh1aMISi/9ttcG3ZOwIdriPbz/eMyWmRMJCGa/WcgY1RX4lrb7HvsHhSfI/JUeBESA4nOCr8C3y5ow==",
514 "license": "MIT",
515 "engines": {
516 "node": ">=22.19.0"
517 }
518 },
519 "node_modules/@google/genai": {
520 "version": "2.21.0",
521 "resolved": "https://registry.npmjs.org/@google/genai/-/genai-2.21.0.tgz",
522 "integrity": "sha512-+PDtco2/Z0ONdzCGekCoCT+O1VJS9xJQNN4XzQpXG/t3El/SWWMkCWlFRO1KmivOHPa4Q0VjUYu1HBKCZ/v33Q==",
523 "hasInstallScript": true,
524 "license": "Apache-2.0",
525 "dependencies": {
526 "google-auth-library": "^10.3.0",
527 "p-retry": "^4.6.2",
528 "protobufjs": "^7.5.4",
529 "ws": "^8.18.0"
530 },
531 "engines": {
532 "node": ">=20.0.0"
533 },
534 "peerDependencies": {
535 "@modelcontextprotocol/sdk": "^1.25.2"
536 },
537 "peerDependenciesMeta": {
538 "@modelcontextprotocol/sdk": {
539 "optional": true
540 }
541 }
542 },
543 "node_modules/@protobufjs/aspromise": {
544 "version": "1.1.2",
545 "resolved": "https://registry.npmjs.org/@protobufjs/aspromise/-/aspromise-1.1.2.tgz",
546 "integrity": "sha512-j+gKExEuLmKwvz3OgROXtrJ2UG2x8Ch2YZUxahh+s1F2HZ+wAceUNLkvy6zKCPVRkU++ZWQrdxsUeQXmcg4uoQ==",
547 "license": "BSD-3-Clause"
548 },
549 "node_modules/@protobufjs/base64": {
550 "version": "1.1.2",
551 "resolved": "https://registry.npmjs.org/@protobufjs/base64/-/base64-1.1.2.tgz",
552 "integrity": "sha512-AZkcAA5vnN/v4PDqKyMR5lx7hZttPDgClv83E//FMNhR2TMcLUhfRUBHCmSl0oi9zMgDDqRUJkSxO3wm85+XLg==",
553 "license": "BSD-3-Clause"
554 },
555 "node_modules/@protobufjs/codegen": {
556 "version": "2.0.5",
557 "resolved": "https://registry.npmjs.org/@protobufjs/codegen/-/codegen-2.0.5.tgz",
558 "integrity": "sha512-zgXFLzW3Ap33e6d0Wlj4MGIm6Ce8O89n/apUaGNB/jx+hw+ruWEp7EwGUshdLKVRCxZW12fp9r40E1mQrf/34g==",
559 "license": "BSD-3-Clause"
560 },
561 "node_modules/@protobufjs/eventemitter": {
562 "version": "1.1.1",
563 "resolved": "https://registry.npmjs.org/@protobufjs/eventemitter/-/eventemitter-1.1.1.tgz",
564 "integrity": "sha512-vW1GmwMZNnL+gMRaovlh9yZX74kc+TTU3FObkkurpMaRtBfLP3ldjS9KQWlwZgraRE0+dheEEoAxdzcJQ8eXZg==",
565 "license": "BSD-3-Clause"
566 },
567 "node_modules/@protobufjs/fetch": {
568 "version": "1.1.1",
569 "resolved": "https://registry.npmjs.org/@protobufjs/fetch/-/fetch-1.1.1.tgz",
570 "integrity": "sha512-GpptLrs57adMSuHi3VNj0mAF8dwh36LMaYF6XyJ6JMWlVsc+t42tm1HSEDmOs3A8fC9yyeisgLhsTVQokOZ0zw==",
571 "license": "BSD-3-Clause",
572 "dependencies": {
573 "@protobufjs/aspromise": "^1.1.1"
574 }
575 },
576 "node_modules/@protobufjs/float": {
577 "version": "1.0.2",
578 "resolved": "https://registry.npmjs.org/@protobufjs/float/-/float-1.0.2.tgz",
579 "integrity": "sha512-Ddb+kVXlXst9d+R9PfTIxh1EdNkgoRe5tOX6t01f1lYWOvJnSPDBlG241QLzcyPdoNTsblLUdujGSE4RzrTZGQ==",
580 "license": "BSD-3-Clause"
581 },
582 "node_modules/@protobufjs/path": {
583 "version": "1.1.2",
584 "resolved": "https://registry.npmjs.org/@protobufjs/path/-/path-1.1.2.tgz",
585 "integrity": "sha512-6JOcJ5Tm08dOHAbdR3GrvP+yUUfkjG5ePsHYczMFLq3ZmMkAD98cDgcT2iA1lJ9NVwFd4tH/iSSoe44YWkltEA==",
586 "license": "BSD-3-Clause"
587 },
588 "node_modules/@protobufjs/pool": {
589 "version": "1.1.0",
590 "resolved": "https://registry.npmjs.org/@protobufjs/pool/-/pool-1.1.0.tgz",
591 "integrity": "sha512-0kELaGSIDBKvcgS4zkjz1PeddatrjYcmMWOlAuAPwAeccUrPHdUqo/J6LiymHHEiJT5NrF1UVwxY14f+fy4WQw==",
592 "license": "BSD-3-Clause"
593 },
594 "node_modules/@protobufjs/utf8": {
595 "version": "1.1.2",
596 "resolved": "https://registry.npmjs.org/@protobufjs/utf8/-/utf8-1.1.2.tgz",
597 "integrity": "sha512-b1UQwcEZ4yCnMCD8DAL1VlbvBJE9/IX4FTIp7BG1xYpf29SLazLSrqUkj4w7Y5y7cCVP6E5tcqqcI0xemPkHug==",
598 "license": "BSD-3-Clause"
599 },
600 "node_modules/@silvia-odwyer/photon": {
601 "version": "0.3.3",
602 "resolved": "https://registry.npmjs.org/@silvia-odwyer/photon/-/photon-0.3.3.tgz",
603 "integrity": "sha512-8BhUjEch4slwRe8uXnaA4vcA5uiiOTT90UMsxulOj2gN98X1p0q9Z4Ysk4DkD05uNgbR9XoSqtZ37w+33w4QKQ==",
604 "license": "Apache-2.0"
605 },
606 "node_modules/@smithy/core": {
607 "version": "3.40.0",
608 "resolved": "https://registry.npmjs.org/@smithy/core/-/core-3.40.0.tgz",
609 "integrity": "sha512-DssGno52pzZ5m6RlDtyKuBIpZNPg9pqgs0CnNDKz9IatxCsmvNmJNn5Zn6rf77MthZo9wf89OvZFhTY/RwxhxQ==",
610 "license": "Apache-2.0",
611 "dependencies": {
612 "@smithy/types": "^4.20.0",
613 "tslib": "^2.6.2"
614 },
615 "engines": {
616 "node": ">=18.0.0"
617 }
618 },
619 "node_modules/@smithy/credential-provider-imds": {
620 "version": "4.5.2",
621 "resolved": "https://registry.npmjs.org/@smithy/credential-provider-imds/-/credential-provider-imds-4.5.2.tgz",
622 "integrity": "sha512-A9uSdn72ozbRUSit0eib0TW7nXuNPlaeM0zcGkJ+nE6tFcSDbnmtwoxbTCFBukVQcszDAyvsd7+rTduPTXpygg==",
623 "license": "Apache-2.0",
624 "dependencies": {
625 "@smithy/core": "^3.33.2",
626 "@smithy/types": "^4.17.2",
627 "tslib": "^2.6.2"
628 },
629 "engines": {
630 "node": ">=18.0.0"
631 }
632 },
633 "node_modules/@smithy/fetch-http-handler": {
634 "version": "5.8.1",
635 "resolved": "https://registry.npmjs.org/@smithy/fetch-http-handler/-/fetch-http-handler-5.8.1.tgz",
636 "integrity": "sha512-h8BdMUrUBhMhMaeK7QqAdINRZezCGuYOCpcOZZ1ewxbHST9rdTd09xwNpvLTYfzDRehxQiReK4SKbdYZxBA+ew==",
637 "license": "Apache-2.0",
638 "dependencies": {
639 "@smithy/core": "^3.39.0",
640 "@smithy/types": "^4.20.0",
641 "tslib": "^2.6.2"
642 },
643 "engines": {
644 "node": ">=18.0.0"
645 }
646 },
647 "node_modules/@smithy/node-http-handler": {
648 "version": "4.12.1",
649 "resolved": "https://registry.npmjs.org/@smithy/node-http-handler/-/node-http-handler-4.12.1.tgz",
650 "integrity": "sha512-ThMkboGeONWXAelq9FvGsuJC4rOi+qyC4/zhUF58xYpxUg5sQKx2VXZYJmtNjr4dSuBJ1HeJXETQILCz3wOHvw==",
651 "license": "Apache-2.0",
652 "dependencies": {
653 "@smithy/core": "^3.33.3",
654 "@smithy/types": "^4.18.0",
655 "tslib": "^2.6.2"
656 },
657 "engines": {
658 "node": ">=18.0.0"
659 }
660 },
661 "node_modules/@smithy/signature-v4": {
662 "version": "5.7.5",
663 "resolved": "https://registry.npmjs.org/@smithy/signature-v4/-/signature-v4-5.7.5.tgz",
664 "integrity": "sha512-WPjdr5oWOk1LArpI4pavu+fSo+/evi0Re1olxGvqwuZopd4gYR1UGCi+Soyn/IjmafqbWs+ZC+3AKxJS3ZpwUg==",
665 "license": "Apache-2.0",
666 "dependencies": {
667 "@smithy/core": "^3.38.0",
668 "@smithy/types": "^4.19.0",
669 "tslib": "^2.6.2"
670 },
671 "engines": {
672 "node": ">=18.0.0"
673 }
674 },
675 "node_modules/@smithy/types": {
676 "version": "4.20.0",
677 "resolved": "https://registry.npmjs.org/@smithy/types/-/types-4.20.0.tgz",
678 "integrity": "sha512-lCA6QG22dPk9ecHbv91jDQZsmtPUjdS1aE2Il6NNPqe7DrYc0dZQi6DhcESk2KYXH2sp5xbAcGdYMZDFnuzA2A==",
679 "license": "Apache-2.0",
680 "dependencies": {
681 "tslib": "^2.6.2"
682 },
683 "engines": {
684 "node": ">=18.0.0"
685 }
686 },
687 "node_modules/@stablelib/base64": {
688 "version": "1.0.1",
689 "resolved": "https://registry.npmjs.org/@stablelib/base64/-/base64-1.0.1.tgz",
690 "integrity": "sha512-1bnPQqSxSuc3Ii6MhBysoWCg58j97aUjuCSZrGSmDxNqtytIi0k8utUenAwTZN4V5mXXYGsVUI9zeBqy+jBOSQ==",
691 "license": "MIT"
692 },
693 "node_modules/@types/node": {
694 "version": "26.6.6",
695 "resolved": "https://registry.npmjs.org/@types/node/-/node-26.6.6.tgz",
696 "integrity": "sha512-MzQj+8Kx3XI40OmUAE6Qoh58ZMNstNNMwn2nfd3qWsfe7nDNSqJNzes4njhz6AHwrSHOffSLwXU6yb474Q4aog==",
697 "license": "MIT",
698 "dependencies": {
699 "undici-types": "~8.9.0"
700 }
701 },
702 "node_modules/@types/retry": {
703 "version": "0.12.0",
704 "resolved": "https://registry.npmjs.org/@types/retry/-/retry-0.12.0.tgz",
705 "integrity": "sha512-wWKOClTTiizcZhXnPY4wikVAwmdYHp8q6DmC+EJUzAMsycb7HB32Kh9RN4+0gExjmPmZSAQjgURXIGATPegAvA==",
706 "license": "MIT"
707 },
708 "node_modules/agent-base": {
709 "version": "9.0.0",
710 "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-9.0.0.tgz",
711 "integrity": "sha512-TQf59BsZnytt8GdJKLPfUZ54g/iaUL2OWDSFCCvMOhsHduDQxO8xC4PNeyIkVcA5KwL2phPSv0douC0fgWzmnA==",
712 "license": "MIT",
713 "engines": {
714 "node": ">= 20"
715 }
716 },
717 "node_modules/base64-js": {
718 "version": "1.5.1",
719 "resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz",
720 "integrity": "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==",
721 "funding": [
722 {
723 "type": "github",
724 "url": "https://github.com/sponsors/feross"
725 },
726 {
727 "type": "patreon",
728 "url": "https://www.patreon.com/feross"
729 },
730 {
731 "type": "consulting",
732 "url": "https://feross.org/support"
733 }
734 ],
735 "license": "MIT"
736 },
737 "node_modules/bignumber.js": {
738 "version": "9.3.1",
739 "resolved": "https://registry.npmjs.org/bignumber.js/-/bignumber.js-9.3.1.tgz",
740 "integrity": "sha512-Ko0uX15oIUS7wJ3Rb30Fs6SkVbLmPBAKdlm7q9+ak9bbIeFf0MwuBsQV6z7+X768/cHsfg+WlysDWJcmthjsjQ==",
741 "license": "MIT",
742 "engines": {
743 "node": "*"
744 }
745 },
746 "node_modules/bowser": {
747 "version": "2.15.0",
748 "resolved": "https://registry.npmjs.org/bowser/-/bowser-2.15.0.tgz",
749 "integrity": "sha512-xic6KSZglg/I4ymp45fdM4GWfYpBK79Fxd/TOvJktlaPgQqqDxvmGwOPZl2V0dyeS3Lj5c180bLhXF43iyAjZQ==",
750 "license": "MIT"
751 },
752 "node_modules/buffer-equal-constant-time": {
753 "version": "1.0.1",
754 "resolved": "https://registry.npmjs.org/buffer-equal-constant-time/-/buffer-equal-constant-time-1.0.1.tgz",
755 "integrity": "sha512-zRpUiDwd/xk6ADqPMATG8vc9VPrkck7T07OIx0gnjmJAnHnTVXNQG3vfvWNuiZIkwu9KrKdA1iJKfsfTVxE6NA==",
756 "license": "BSD-3-Clause"
757 },
758 "node_modules/data-uri-to-buffer": {
759 "version": "4.0.1",
760 "resolved": "https://registry.npmjs.org/data-uri-to-buffer/-/data-uri-to-buffer-4.0.1.tgz",
761 "integrity": "sha512-0R9ikRb668HB7QDxT1vkpuUBtqc53YyAwMwGeUFKRojY/NWKvdZ+9UYtRfGmhqNbRkTSVpMbmyhXipFFv2cb/A==",
762 "license": "MIT",
763 "engines": {
764 "node": ">= 12"
765 }
766 },
767 "node_modules/debug": {
768 "version": "4.4.3",
769 "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz",
770 "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==",
771 "license": "MIT",
772 "dependencies": {
773 "ms": "^2.1.3"
774 },
775 "engines": {
776 "node": ">=6.0"
777 },
778 "peerDependenciesMeta": {
779 "supports-color": {
780 "optional": true
781 }
782 }
783 },
784 "node_modules/diff": {
785 "version": "8.0.4",
786 "resolved": "https://registry.npmjs.org/diff/-/diff-8.0.4.tgz",
787 "integrity": "sha512-DPi0FmjiSU5EvQV0++GFDOJ9ASQUVFh5kD+OzOnYdi7n3Wpm9hWWGfB/O2blfHcMVTL5WkQXSnRiK9makhrcnw==",
788 "license": "BSD-3-Clause",
789 "engines": {
790 "node": ">=0.3.1"
791 }
792 },
793 "node_modules/ecdsa-sig-formatter": {
794 "version": "1.0.11",
795 "resolved": "https://registry.npmjs.org/ecdsa-sig-formatter/-/ecdsa-sig-formatter-1.0.11.tgz",
796 "integrity": "sha512-nagl3RYrbNv6kQkeJIpt6NJZy8twLB/2vtz6yN9Z4vRKHN4/QZJIEbqohALSgwKdnksuY3k5Addp5lg8sVoVcQ==",
797 "license": "Apache-2.0",
798 "dependencies": {
799 "safe-buffer": "^5.0.1"
800 }
801 },
802 "node_modules/extend": {
803 "version": "3.0.2",
804 "resolved": "https://registry.npmjs.org/extend/-/extend-3.0.2.tgz",
805 "integrity": "sha512-fjquC59cD7CyW6urNXK0FBufkZcoiGG80wTuPujX590cB5Ttln20E2UB4S/WARVqhXffZl2LNgS+gQdPIIim/g==",
806 "license": "MIT"
807 },
808 "node_modules/fast-sha256": {
809 "version": "1.3.0",
810 "resolved": "https://registry.npmjs.org/fast-sha256/-/fast-sha256-1.3.0.tgz",
811 "integrity": "sha512-n11RGP/lrWEFI/bWdygLxhI+pVeo1ZYIVwvvPkW7azl/rOy+F3HYRZ2K5zeE9mmkhQppyv9sQFx0JM9UabnpPQ==",
812 "license": "Unlicense"
813 },
814 "node_modules/fetch-blob": {
815 "version": "3.2.0",
816 "resolved": "https://registry.npmjs.org/fetch-blob/-/fetch-blob-3.2.0.tgz",
817 "integrity": "sha512-7yAQpD2UMJzLi1Dqv7qFYnPbaPx7ZfFK6PiIxQ4PfkGPyNyl2Ugx+a/umUonmKqjhM4DnfbMvdX6otXq83soQQ==",
818 "funding": [
819 {
820 "type": "github",
821 "url": "https://github.com/sponsors/jimmywarting"
822 },
823 {
824 "type": "paypal",
825 "url": "https://paypal.me/jimmywarting"
826 }
827 ],
828 "license": "MIT",
829 "dependencies": {
830 "node-domexception": "^1.0.0",
831 "web-streams-polyfill": "^3.0.3"
832 },
833 "engines": {
834 "node": "^12.20 || >= 14.13"
835 }
836 },
837 "node_modules/formdata-polyfill": {
838 "version": "4.0.10",
839 "resolved": "https://registry.npmjs.org/formdata-polyfill/-/formdata-polyfill-4.0.10.tgz",
840 "integrity": "sha512-buewHzMvYL29jdeQTVILecSaZKnt/RJWjoZCF5OW60Z67/GmSLBkOFM7qh1PI3zFNtJbaZL5eQu1vLfazOwj4g==",
841 "license": "MIT",
842 "dependencies": {
843 "fetch-blob": "^3.1.2"
844 },
845 "engines": {
846 "node": ">=12.20.0"
847 }
848 },
849 "node_modules/gaxios": {
850 "version": "7.3.1",
851 "resolved": "https://registry.npmjs.org/gaxios/-/gaxios-7.3.1.tgz",
852 "integrity": "sha512-kB3rzJV7d9juLZh8/56QTXCwQfxyhdOMdyYk1HdQKFtF8TJTDTZQJtixWIwXdE9Jji91mC41DUNpjleo4L4eAQ==",
853 "license": "Apache-2.0",
854 "dependencies": {
855 "extend": "^3.0.2",
856 "https-proxy-agent": "^7.0.1",
857 "node-fetch": "^3.3.2"
858 },
859 "engines": {
860 "node": ">=18"
861 }
862 },
863 "node_modules/gaxios/node_modules/agent-base": {
864 "version": "7.1.4",
865 "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-7.1.4.tgz",
866 "integrity": "sha512-MnA+YT8fwfJPgBx3m60MNqakm30XOkyIoH1y6huTQvC0PwZG7ki8NacLBcrPbNoo8vEZy7Jpuk7+jMO+CUovTQ==",
867 "license": "MIT",
868 "engines": {
869 "node": ">= 14"
870 }
871 },
872 "node_modules/gaxios/node_modules/https-proxy-agent": {
873 "version": "7.0.6",
874 "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-7.0.6.tgz",
875 "integrity": "sha512-vK9P5/iUfdl95AI+JVyUuIcVtd4ofvtrOr3HNtM2yxC9bnMbEdp3x01OhQNnjb8IJYi38VlTE3mBXwcfvywuSw==",
876 "license": "MIT",
877 "dependencies": {
878 "agent-base": "^7.1.2",
879 "debug": "4"
880 },
881 "engines": {
882 "node": ">= 14"
883 }
884 },
885 "node_modules/gcp-metadata": {
886 "version": "8.1.2",
887 "resolved": "https://registry.npmjs.org/gcp-metadata/-/gcp-metadata-8.1.2.tgz",
888 "integrity": "sha512-zV/5HKTfCeKWnxG0Dmrw51hEWFGfcF2xiXqcA3+J90WDuP0SvoiSO5ORvcBsifmx/FoIjgQN3oNOGaQ5PhLFkg==",
889 "license": "Apache-2.0",
890 "dependencies": {
891 "gaxios": "^7.0.0",
892 "google-logging-utils": "^1.0.0",
893 "json-bigint": "^1.0.0"
894 },
895 "engines": {
896 "node": ">=18"
897 }
898 },
899 "node_modules/google-auth-library": {
900 "version": "10.9.1",
901 "resolved": "https://registry.npmjs.org/google-auth-library/-/google-auth-library-10.9.1.tgz",
902 "integrity": "sha512-i1ydyHrqcIxXkWh/uBmVkzCvIuq5yiK2ATndIe5XxKholrG/MTYP9xGYka4sQhrbIAgGjL2B6NOE7rFaiF3fXw==",
903 "license": "Apache-2.0",
904 "dependencies": {
905 "base64-js": "^1.3.0",
906 "ecdsa-sig-formatter": "^1.0.11",
907 "gaxios": "^7.1.4",
908 "gcp-metadata": "8.1.2",
909 "google-logging-utils": "1.1.3",
910 "jws": "^4.0.0"
911 },
912 "engines": {
913 "node": ">=18"
914 }
915 },
916 "node_modules/google-logging-utils": {
917 "version": "1.1.3",
918 "resolved": "https://registry.npmjs.org/google-logging-utils/-/google-logging-utils-1.1.3.tgz",
919 "integrity": "sha512-eAmLkjDjAFCVXg7A1unxHsLf961m6y17QFqXqAXGj/gVkKFrEICfStRfwUlGNfeCEjNRa32JEWOUTlYXPyyKvA==",
920 "license": "Apache-2.0",
921 "engines": {
922 "node": ">=14"
923 }
924 },
925 "node_modules/http-proxy-agent": {
926 "version": "9.1.0",
927 "resolved": "https://registry.npmjs.org/http-proxy-agent/-/http-proxy-agent-9.1.0.tgz",
928 "integrity": "sha512-2NxoveTT58mjYT4n3RPTEfCZGLMbidoO8XEieXfpSYxu+PQJ1qpx4ypwH6N+uF9twBPIvRRgvkvW5HUTYWENig==",
929 "license": "MIT",
930 "dependencies": {
931 "agent-base": "9.0.0",
932 "debug": "^4.3.4",
933 "proxy-agent-negotiate": "1.1.0"
934 },
935 "engines": {
936 "node": ">= 20"
937 }
938 },
939 "node_modules/https-proxy-agent": {
940 "version": "9.1.0",
941 "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-9.1.0.tgz",
942 "integrity": "sha512-ag87y7cJJ9/3+GxFr8Oy4O5faDsGRGnBGsJj/YjOSsSx/5eadKLYTMPlzuR6obgoCDDm0abAAZitXXQkMOPSpA==",
943 "license": "MIT",
944 "dependencies": {
945 "agent-base": "9.0.0",
946 "debug": "^4.3.4",
947 "proxy-agent-negotiate": "1.1.0"
948 },
949 "engines": {
950 "node": ">= 20"
951 }
952 },
953 "node_modules/json-bigint": {
954 "version": "1.0.0",
955 "resolved": "https://registry.npmjs.org/json-bigint/-/json-bigint-1.0.0.tgz",
956 "integrity": "sha512-SiPv/8VpZuWbvLSMtTDU8hEfrZWg/mH/nV/b4o0CYbSxu1UIQPLdwKOCIyLQX+VIPO5vrLX3i8qtqFyhdPSUSQ==",
957 "license": "MIT",
958 "dependencies": {
959 "bignumber.js": "^9.0.0"
960 }
961 },
962 "node_modules/json-schema-to-ts": {
963 "version": "3.1.1",
964 "resolved": "https://registry.npmjs.org/json-schema-to-ts/-/json-schema-to-ts-3.1.1.tgz",
965 "integrity": "sha512-+DWg8jCJG2TEnpy7kOm/7/AxaYoaRbjVB4LFZLySZlWn8exGs3A4OLJR966cVvU26N7X9TWxl+Jsw7dzAqKT6g==",
966 "license": "MIT",
967 "dependencies": {
968 "@babel/runtime": "^7.18.3",
969 "ts-algebra": "^2.0.0"
970 },
971 "engines": {
972 "node": ">=16"
973 }
974 },
975 "node_modules/jwa": {
976 "version": "2.0.1",
977 "resolved": "https://registry.npmjs.org/jwa/-/jwa-2.0.1.tgz",
978 "integrity": "sha512-hRF04fqJIP8Abbkq5NKGN0Bbr3JxlQ+qhZufXVr0DvujKy93ZCbXZMHDL4EOtodSbCWxOqR8MS1tXA5hwqCXDg==",
979 "license": "MIT",
980 "dependencies": {
981 "buffer-equal-constant-time": "^1.0.1",
982 "ecdsa-sig-formatter": "1.0.11",
983 "safe-buffer": "^5.0.1"
984 }
985 },
986 "node_modules/jws": {
987 "version": "4.0.1",
988 "resolved": "https://registry.npmjs.org/jws/-/jws-4.0.1.tgz",
989 "integrity": "sha512-EKI/M/yqPncGUUh44xz0PxSidXFr/+r0pA70+gIYhjv+et7yxM+s29Y+VGDkovRofQem0fs7Uvf4+YmAdyRduA==",
990 "license": "MIT",
991 "dependencies": {
992 "jwa": "^2.0.1",
993 "safe-buffer": "^5.0.1"
994 }
995 },
996 "node_modules/long": {
997 "version": "5.3.2",
998 "resolved": "https://registry.npmjs.org/long/-/long-5.3.2.tgz",
999 "integrity": "sha512-mNAgZ1GmyNhD7AuqnTG3/VQ26o760+ZYBPKjPvugO8+nLbYfX6TVpJPseBvopbdY+qpZ/lKUnmEc1LeZYS3QAA==",
1000 "license": "Apache-2.0"
1001 },
1002 "node_modules/ms": {
1003 "version": "2.1.3",
1004 "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",
1005 "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==",
1006 "license": "MIT"
1007 },
1008 "node_modules/node-domexception": {
1009 "version": "1.0.0",
1010 "resolved": "https://registry.npmjs.org/node-domexception/-/node-domexception-1.0.0.tgz",
1011 "integrity": "sha512-/jKZoMpw0F8GRwl4/eLROPA3cfcXtLApP0QzLmUT/HuPCZWyB7IY9ZrMeKw2O/nFIqPQB3PVM9aYm0F312AXDQ==",
1012 "deprecated": "Use your platform's native DOMException instead",
1013 "funding": [
1014 {
1015 "type": "github",
1016 "url": "https://github.com/sponsors/jimmywarting"
1017 },
1018 {
1019 "type": "github",
1020 "url": "https://paypal.me/jimmywarting"
1021 }
1022 ],
1023 "license": "MIT",
1024 "engines": {
1025 "node": ">=10.5.0"
1026 }
1027 },
1028 "node_modules/node-fetch": {
1029 "version": "3.3.2",
1030 "resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-3.3.2.tgz",
1031 "integrity": "sha512-dRB78srN/l6gqWulah9SrxeYnxeddIG30+GOqK/9OlLVyLg3HPnr6SqOWTWOXKRwC2eGYCkZ59NNuSgvSrpgOA==",
1032 "license": "MIT",
1033 "dependencies": {
1034 "data-uri-to-buffer": "^4.0.0",
1035 "fetch-blob": "^3.1.4",
1036 "formdata-polyfill": "^4.0.10"
1037 },
1038 "engines": {
1039 "node": "^12.20.0 || ^14.13.1 || >=16.0.0"
1040 },
1041 "funding": {
1042 "type": "opencollective",
1043 "url": "https://opencollective.com/node-fetch"
1044 }
1045 },
1046 "node_modules/openai": {
1047 "version": "7.19.0",
1048 "resolved": "https://registry.npmjs.org/openai/-/openai-7.19.0.tgz",
1049 "integrity": "sha512-MX2s3u2L5racTO0CC/SWpCOasJQBCJrqLKXK+l82cAhdeF8mPMBEe/gxMm0ZFa2xpKpOFLRjxv5afYEZbBXmbQ==",
1050 "license": "Apache-2.0",
1051 "engines": {
1052 "node": ">=22.0.0"
1053 },
1054 "peerDependencies": {
1055 "@aws-sdk/credential-provider-node": ">=3.972.0 <4",
1056 "@smithy/hash-node": ">=4.3.0 <5",
1057 "@smithy/signature-v4": ">=5.4.0 <6",
1058 "undici": ">=5 <9",
1059 "ws": "^8.21.0",
1060 "zod": "^3.25 || ^4.0"
1061 },
1062 "peerDependenciesMeta": {
1063 "@aws-sdk/credential-provider-node": {
1064 "optional": true
1065 },
1066 "@smithy/hash-node": {
1067 "optional": true
1068 },
1069 "@smithy/signature-v4": {
1070 "optional": true
1071 },
1072 "undici": {
1073 "optional": true
1074 },
1075 "ws": {
1076 "optional": true
1077 },
1078 "zod": {
1079 "optional": true
1080 }
1081 }
1082 },
1083 "node_modules/p-retry": {
1084 "version": "4.6.2",
1085 "resolved": "https://registry.npmjs.org/p-retry/-/p-retry-4.6.2.tgz",
1086 "integrity": "sha512-312Id396EbJdvRONlngUx0NydfrIQ5lsYu0znKVUzVvArzEIt08V1qhtyESbGVd1FGX7UKtiFp5uwKZdM8wIuQ==",
1087 "license": "MIT",
1088 "dependencies": {
1089 "@types/retry": "0.12.0",
1090 "retry": "^0.13.1"
1091 },
1092 "engines": {
1093 "node": ">=8"
1094 }
1095 },
1096 "node_modules/partial-json": {
1097 "version": "0.1.7",
1098 "resolved": "https://registry.npmjs.org/partial-json/-/partial-json-0.1.7.tgz",
1099 "integrity": "sha512-Njv/59hHaokb/hRUjce3Hdv12wd60MtM9Z5Olmn+nehe0QDAsRtRbJPvJ0Z91TusF0SuZRIvnM+S4l6EIP8leA==",
1100 "license": "MIT"
1101 },
1102 "node_modules/protobufjs": {
1103 "version": "7.6.6",
1104 "resolved": "https://registry.npmjs.org/protobufjs/-/protobufjs-7.6.6.tgz",
1105 "integrity": "sha512-dYDWdjSl5RNb7SgPxGQcRU+GtvP7s2fpkrY0r432PcOIaZ0/rBcxEZnQN67iJhFuQiVw754JDoPruPCNdGsbjg==",
1106 "hasInstallScript": true,
1107 "license": "BSD-3-Clause",
1108 "dependencies": {
1109 "@protobufjs/aspromise": "^1.1.2",
1110 "@protobufjs/base64": "^1.1.2",
1111 "@protobufjs/codegen": "^2.0.5",
1112 "@protobufjs/eventemitter": "^1.1.1",
1113 "@protobufjs/fetch": "^1.1.1",
1114 "@protobufjs/float": "^1.0.2",
1115 "@protobufjs/path": "^1.1.2",
1116 "@protobufjs/pool": "^1.1.0",
1117 "@protobufjs/utf8": "^1.1.1",
1118 "@types/node": ">=13.7.0",
1119 "long": "^5.3.2"
1120 },
1121 "engines": {
1122 "node": ">=12.0.0"
1123 }
1124 },
1125 "node_modules/proxy-agent-negotiate": {
1126 "version": "1.1.0",
1127 "resolved": "https://registry.npmjs.org/proxy-agent-negotiate/-/proxy-agent-negotiate-1.1.0.tgz",
1128 "integrity": "sha512-N8IBcM3UgCVzz2L2Lqv8DVntDnnC8/hiV4nEDUPkqq72TPUgYWjQc+bdZlBPZK9LzPAvOY//gAt0S0DApoOXWQ==",
1129 "license": "MIT",
1130 "engines": {
1131 "node": ">= 20"
1132 },
1133 "peerDependencies": {
1134 "kerberos": "^2.0.0"
1135 },
1136 "peerDependenciesMeta": {
1137 "kerberos": {
1138 "optional": true
1139 }
1140 }
1141 },
1142 "node_modules/quickjs-wasi": {
1143 "version": "3.6.2",
1144 "resolved": "https://registry.npmjs.org/quickjs-wasi/-/quickjs-wasi-3.6.2.tgz",
1145 "integrity": "sha512-FCqGtGOrMgzUiIrMNMA2YnsOxCNwo31dzqXvclXUC6xeT35NJLKXQJsvbeCTjvoFAwZgEAPg8U6+KAPDGXn8Mg==",
1146 "license": "MIT"
1147 },
1148 "node_modules/retry": {
1149 "version": "0.13.1",
1150 "resolved": "https://registry.npmjs.org/retry/-/retry-0.13.1.tgz",
1151 "integrity": "sha512-XQBQ3I8W1Cge0Seh+6gjj03LbmRFWuoszgK9ooCpwYIrhhoO80pfq4cUkU5DkknwfOfFteRwlZ56PYOGYyFWdg==",
1152 "license": "MIT",
1153 "engines": {
1154 "node": ">= 4"
1155 }
1156 },
1157 "node_modules/safe-buffer": {
1158 "version": "5.2.1",
1159 "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz",
1160 "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==",
1161 "funding": [
1162 {
1163 "type": "github",
1164 "url": "https://github.com/sponsors/feross"
1165 },
1166 {
1167 "type": "patreon",
1168 "url": "https://www.patreon.com/feross"
1169 },
1170 {
1171 "type": "consulting",
1172 "url": "https://feross.org/support"
1173 }
1174 ],
1175 "license": "MIT"
1176 },
1177 "node_modules/standardwebhooks": {
1178 "version": "1.1.1",
1179 "resolved": "https://registry.npmjs.org/standardwebhooks/-/standardwebhooks-1.1.1.tgz",
1180 "integrity": "sha512-bCbX9ZEyFkWPsRz7Bl3NuQUJohmwGSev/yhr7vhaGPlc4AfIrspIRa6cPTBuI1ItmrTDJ4d/S2hCsfe4+vQGnQ==",
1181 "license": "MIT",
1182 "dependencies": {
1183 "@stablelib/base64": "^1.0.0",
1184 "fast-sha256": "^1.3.0"
1185 }
1186 },
1187 "node_modules/ts-algebra": {
1188 "version": "2.0.0",
1189 "resolved": "https://registry.npmjs.org/ts-algebra/-/ts-algebra-2.0.0.tgz",
1190 "integrity": "sha512-FPAhNPFMrkwz76P7cdjdmiShwMynZYN6SgOujD1urY4oNm80Ou9oMdmbR45LotcKOXoy7wSmHkRFE6Mxbrhefw==",
1191 "license": "MIT"
1192 },
1193 "node_modules/tslib": {
1194 "version": "2.9.1",
1195 "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.9.1.tgz",
1196 "integrity": "sha512-a4Ux9VKuIMHsOS7ENbEq6hK2ZGYIT27Rtl0E4eD9KqwxhKiQeMZE/9xb3IdYwWaSOyIBQLExhQgXDTYoiCxnWA==",
1197 "license": "0BSD"
1198 },
1199 "node_modules/undici-types": {
1200 "version": "8.9.0",
1201 "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-8.9.0.tgz",
1202 "integrity": "sha512-KTDyRTYX8sWmKXAikPHHSyc63CRPETMctyjKFupcC6OBLXT3xsN0e9aF7m+mIXutFWpUXuedtowG7iLOzp0kQg==",
1203 "license": "MIT"
1204 },
1205 "node_modules/web-streams-polyfill": {
1206 "version": "3.3.3",
1207 "resolved": "https://registry.npmjs.org/web-streams-polyfill/-/web-streams-polyfill-3.3.3.tgz",
1208 "integrity": "sha512-d2JWLCivmZYTSIoge9MsgFCZrt571BikcWGYkjC1khllbTeDlGqZ2D8vD8E/lJa8WGWbb7Plm8/XJYV7IJHZZw==",
1209 "license": "MIT",
1210 "engines": {
1211 "node": ">= 8"
1212 }
1213 },
1214 "node_modules/ws": {
1215 "version": "8.21.0",
1216 "resolved": "https://registry.npmjs.org/ws/-/ws-8.21.0.tgz",
1217 "integrity": "sha512-Vsp28b7DRcimFQvrqu2Wek3z1iYxDCWqHYB8Qsnk/S4RfaCQzPGPyBNuVjJV3cd6UiKtUtp6sNM77gWvzcCH+g==",
1218 "license": "MIT",
1219 "engines": {
1220 "node": ">=10.0.0"
1221 },
1222 "peerDependencies": {
1223 "bufferutil": "^4.0.1",
1224 "utf-8-validate": ">=5.0.2"
1225 },
1226 "peerDependenciesMeta": {
1227 "bufferutil": {
1228 "optional": true
1229 },
1230 "utf-8-validate": {
1231 "optional": true
1232 }
1233 }
1234 }
1235 }

neovim/pivi/package.json

Added
new file mode 100644

+18 / −0 text lines

1{
2 "name": "pivi",
3 "private": true,
4 "type": "module",
5 "engines": {
6 "node": ">=22.19.0"
7 },
8 "scripts": {
9 "test": "node --test test/*.test.mjs"
10 },
11 "dependencies": {
12 "@earendil-works/pi-durable": "1.5.2",
13 "@earendil-works/pi-ai": "1.5.2",
14 "@earendil-works/pi-codemode": "1.5.2",
15 "@earendil-works/pi-schema": "1.5.2",
16 "@earendil-works/chord": "1.5.2"
17 }
18}

neovim/pivi/test/credentials.test.mjs

Added
new file mode 100644

+49 / −0 text lines

1import assert from 'node:assert/strict';
2import { mkdtemp, readFile, rm, stat } from 'node:fs/promises';
3import { tmpdir } from 'node:os';
4import { join } from 'node:path';
5import test from 'node:test';
6import { fileCredentials } from '../credentials.mjs';
7
8async function temporary(t) {
9 const directory = await mkdtemp(join(tmpdir(), 'pivi-auth-'));
10 t.after(() => rm(directory, { recursive: true, force: true }));
11 return join(directory, 'state', 'auth.json');
12}
14test('credentials persist privately and are visible to another store on the same file', async (t) => {
15 const path = await temporary(t);
16 const store = fileCredentials(path);
17 assert.equal(await store.read('a'), undefined);
18 assert.deepEqual(await store.list(), []);
19 await store.modify('a', async () => ({ type: 'api_key', key: 'secret' }));
20 assert.equal((await stat(path)).mode & 0o777, 0o600);
21 const other = fileCredentials(path);
22 assert.deepEqual(await other.read('a'), { type: 'api_key', key: 'secret' });
23 assert.deepEqual(await other.list(), [{ providerId: 'a', type: 'api_key' }]);
24 assert.deepEqual(await other.modify('a', async () => undefined), { type: 'api_key', key: 'secret' });
25 await other.delete('a');
26 assert.equal(await store.read('a'), undefined);
27 assert.deepEqual(JSON.parse(await readFile(path, 'utf8')), {});
28});
30test('concurrent writers through separate stores never lose an update', async (t) => {
31 const path = await temporary(t);
32 const stores = [fileCredentials(path), fileCredentials(path), fileCredentials(path)];
33 const bump = (store) => store.modify('counter', async (current) => {
34 await new Promise((resolve) => setTimeout(resolve, 2));
35 return { type: 'api_key', key: String(Number(current?.key ?? 0) + 1) };
36 });
37 await Promise.all(Array.from({ length: 30 }, (_, index) => bump(stores[index % stores.length])));
38 assert.equal((await stores[0].read('counter')).key, '30');
39});
41test('a failing change leaves the stored credential and the lock untouched', async (t) => {
42 const path = await temporary(t);
43 const store = fileCredentials(path);
44 await store.modify('a', async () => ({ type: 'api_key', key: 'kept' }));
45 await assert.rejects(store.modify('a', async () => { throw new Error('refresh failed'); }), /refresh failed/);
46 assert.equal((await store.read('a')).key, 'kept');
47 await store.modify('a', async () => ({ type: 'api_key', key: 'next' }));
48 assert.equal((await store.read('a')).key, 'next');
49});

neovim/pivi/test/editor_config.mjs

Added
new file mode 100644

+45 / −0 text lines

1import { createModels } from '@earendil-works/pi-ai/models';
2import { fauxProvider, fauxAssistantMessage, fauxToolCall } from '@earendil-works/pi-ai/providers/faux';
3import { gatedProvider } from './gated.mjs';
4
5export default function ({ credentials }) {
6 const faux = fauxProvider({
7 provider: 'pivi-test', models: [{ id: 'editor' }, { id: 'recovered' }],
8 tokensPerSecond: Number(process.env.PIVI_TEST_STREAMING) || Infinity,
9 });
10 const models = createModels({ credentials });
11 models.setProvider(faux.provider);
12 models.setProvider(gatedProvider());
13 const respond = (transcript, options, state, model) => {
14 if (model.id === 'recovered') return fauxAssistantMessage('Recovered without resubmitting the prompt');
15 const last = transcript.messages.at(-1);
16 if (last?.role === 'toolResult') {
17 return fauxAssistantMessage('Observed live editor: ' + last.content.map((item) => item.text ?? '').join(''));
18 }
19 const text = typeof last?.content === 'string' ? last.content : JSON.stringify(last?.content);
20 if (text?.includes('worker-crash')) process.exit(23);
21 if (text?.includes('provider-throttled')) {
22 return fauxAssistantMessage('', { stopReason: 'error', errorMessage: '429 rate limit exceeded: retry later' });
23 }
24 if (text?.includes('provider-denied')) {
25 return fauxAssistantMessage('Partial response retained', {
26 stopReason: 'error', errorMessage: '401 invalid_api_key: test credential rejected',
27 });
28 }
29 if (text?.includes('broken-tool')) {
30 return fauxAssistantMessage(fauxToolCall('nvim_lua', { code: 'error("fixture tool failed")' }), {
31 stopReason: 'toolUse',
32 });
33 }
34 if (text?.includes('slow')) {
35 const call = fauxToolCall('nvim_lua', { code: 'return system("sleep 33.3; echo never")' });
36 return fauxAssistantMessage(call, { stopReason: 'toolUse' });
37 }
38 const code = text?.includes('mutate')
39 ? 'vim.api.nvim_buf_set_lines(vim.g.pivi_test_buffer, 0, 1, false, {"agent edit"}); return "edited"'
40 : 'return table.concat(vim.api.nvim_buf_get_lines(vim.g.pivi_test_buffer, 0, -1, false), "\\n")';
41 return fauxAssistantMessage(fauxToolCall('nvim_lua', { code }), { stopReason: 'toolUse' });
42 };
43 faux.setResponses(Array(100).fill(respond));
44 return { models };
45}

neovim/pivi/test/gated.mjs

Added
new file mode 100644

+30 / −0 text lines

1import { fauxProvider } from '@earendil-works/pi-ai/providers/faux';
2
3export function gatedProvider() {
4 const { provider } = fauxProvider({ provider: 'gated', models: [{ id: 'locked' }] });
5 return {
6 ...provider,
7 name: 'Gated Test',
8 auth: {
9 apiKey: {
10 name: 'Gated API key',
11 login: async (interaction) => ({
12 type: 'api_key',
13 key: await interaction.prompt({ type: 'secret', message: 'Gated API key' }),
14 }),
15 resolve: async ({ credential }) =>
16 credential?.key ? { auth: { apiKey: credential.key }, source: 'stored key' } : undefined,
17 },
18 oauth: {
19 name: 'Gated account',
20 async login(interaction) {
21 interaction.notify({ type: 'auth_url', url: 'https://example.test/authorize?state=1' });
22 const code = await interaction.prompt({ type: 'manual_code', message: 'Paste the code' });
23 return { type: 'oauth', access: code, refresh: 'refresh', expires: Date.now() + 3_600_000 };
24 },
25 refresh: async (credential) => credential,
26 toAuth: async (credential) => ({ apiKey: credential.access }),
27 },
28 },
29 };
30}

neovim/pivi/test/harness.test.mjs

Added
new file mode 100644

+237 / −0 text lines

1import assert from 'node:assert/strict';
2import { existsSync } from 'node:fs';
3import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';
4import { tmpdir } from 'node:os';
5import { join } from 'node:path';
6import test from 'node:test';
7import { BACKGROUND_CONTEXT as context } from '@earendil-works/chord/context';
8import { createModels } from '@earendil-works/pi-ai/models';
9import { LiveDoc } from '@earendil-works/pi-durable';
10import { fauxProvider, fauxAssistantMessage, fauxToolCall } from '@earendil-works/pi-ai/providers/faux';
11import { fileCredentials } from '../credentials.mjs';
12import { openPivi } from '../harness.mjs';
13import { gatedProvider } from './gated.mjs';
15async function fixture(t, editor = async () => ({ text: 'unsaved buffer' }), cwd = undefined) {
16 const directory = await mkdtemp(join(tmpdir(), 'pivi-test-'));
17 const faux = fauxProvider({ models: [{ id: 'test' }], tokensPerSecond: Infinity });
18 const models = createModels();
19 models.setProvider(faux.provider);
20 let runtime;
21 const reopen = async () => {
22 runtime = await openPivi({ database: join(directory, 'session.sqlite'), models, editor, cwd });
23 return runtime;
24 };
25 t.after(async () => {
26 if (runtime) await runtime.close();
27 await rm(directory, { recursive: true, force: true });
28 });
29 await reopen();
30 const model = faux.getModel();
31 await runtime.commands.configure({ model: { provider: model.provider, modelId: model.id } });
32 return { runtime, faux, reopen };
33}
35test('only editor tools and codemode are enabled; direct editor effects reach model', async (t) => {
36 const codes = [];
37 const editor = async (name, { code }) => { codes.push([name, code]); return { text: 'unsaved' }; };
38 const { runtime, faux } = await fixture(t, editor);
39 const agent = await runtime.conversation.agent(context);
40 assert.deepEqual(agent.tools.map((tool) => tool.name).sort(), [
41 'codemode', 'diagnostics', 'edit', 'lsp', 'nvim_lua', 'read', 'save', 'write',
42 ]);
43 faux.setResponses([
44 fauxAssistantMessage(
45 fauxToolCall('nvim_lua', { code: 'return vim.api.nvim_get_current_buf()' }), { stopReason: 'toolUse' },
46 ),
47 fauxAssistantMessage('Read unsaved content.'),
48 ]);
49 const accepted = await runtime.commands.submit({ content: 'Inspect buffer' });
50 await runtime.conversation.waitForIdle(context);
51 const settled = await (await runtime.harness.submission(accepted.id, context)).wait(context);
52 assert.equal(settled.status, 'done');
53 assert.equal(codes.length, 1);
54 const transcript = await runtime.conversation.context(context);
55 assert.ok(transcript.messages.some((message) => message.role === 'toolResult'
56 && message.content.some((block) => block.text === 'unsaved')));
57});
59test('failed compaction retains history and clears its failure only after a successful retry', async (t) => {
60 const { runtime, faux } = await fixture(t);
61 await runtime.conversation.configure({ compaction: { keepRecentTokens: 10, reserveTokens: 128 } }, context);
62 faux.setResponses([fauxAssistantMessage('first answer '.repeat(40)), fauxAssistantMessage('second answer '.repeat(40))]);
63 for (const content of ['first prompt', 'second prompt']) {
64 await runtime.commands.submit({ content });
65 await runtime.conversation.waitForIdle(context);
66 }
67 const before = (await runtime.conversation.context(context)).entries;
68 faux.setResponses([fauxAssistantMessage('', { stopReason: 'error', errorMessage: '401 compaction credential rejected' })]);
69 let task = await runtime.conversation.compact(undefined, context);
70 await runtime.harness.waitForTask(task, context);
71 let live = await runtime.harness.snapshot(LiveDoc, runtime.conversation.id, context);
72 assert.match(live.compactionFailure.error, /401 compaction credential rejected/);
73 assert.deepEqual((await runtime.conversation.context(context)).entries, before);
74 faux.setResponses([fauxAssistantMessage('Summary of first exchange.')]);
75 task = await runtime.conversation.compact(undefined, context);
76 await runtime.harness.waitForTask(task, context);
77 live = await runtime.harness.snapshot(LiveDoc, runtime.conversation.id, context);
78 assert.equal(live.compactionFailure, undefined);
79 assert.ok((await runtime.conversation.context(context)).entries.some((entry) => entry.kind === 'pi.compaction'));
80});
82test('codemode invokes same editor capability', async (t) => {
83 let calls = 0;
84 const { runtime, faux } = await fixture(t, async () => { calls++; return { text: 'live' }; });
85 faux.setResponses([
86 fauxAssistantMessage(
87 fauxToolCall('codemode', { code: 'text(await tools.nvim_lua({code: "return 42"}));' }), { stopReason: 'toolUse' },
88 ),
89 fauxAssistantMessage('Done.'),
90 ]);
91 await runtime.commands.submit({ content: 'Inspect through codemode' });
92 await runtime.conversation.waitForIdle(context);
93 assert.equal(calls, 1);
94 const { messages } = await runtime.conversation.context(context);
95 const result = messages.find((message) => message.role === 'toolResult');
96 assert.equal(result.isError, false);
97});
99test('new and fork stay in same storage; active conversation survives reopen', async (t) => {
100 const { runtime, faux, reopen } = await fixture(t);
101 faux.setResponses([fauxAssistantMessage('First answer.')]);
102 await runtime.commands.submit({ content: 'First question' });
103 await runtime.conversation.waitForIdle(context);
104 const first = runtime.conversation.id;
105 const { entries } = await runtime.conversation.context(context);
106 const user = entries.find((entry) => entry.kind === 'pi.user');
107 await runtime.commands.fork({ entry: user.id });
108 const fork = runtime.conversation.id;
109 assert.notEqual(fork, first);
110 assert.equal((await runtime.conversation.context(context)).messages.at(-1).role, 'user');
111 await runtime.close();
112 const restored = await reopen();
113 assert.equal(restored.conversation.id, fork);
114 await restored.commands.new();
115 assert.notEqual(restored.conversation.id, fork);
116 assert.equal((await restored.conversation.context(context)).messages.length, 0);
117});
119test('sign-in unlocks a provider, survives reopen, can be cancelled, and sign-out locks it again', async (t) => {
120 const directory = await mkdtemp(join(tmpdir(), 'pivi-test-'));
121 const credentials = fileCredentials(join(directory, 'auth.json'));
122 const models = createModels({ credentials });
123 models.setProvider(gatedProvider());
124 const events = [];
125 let prompts = 0;
126 const interact = {
127 notify: (event) => events.push(event.type),
128 prompt: ({ type, signal }) => {
129 prompts++;
130 if (type === 'secret') return Promise.resolve('secret-key');
131 return new Promise((_, reject) => signal.addEventListener('abort', () => reject(new Error('cancelled'))));
132 },
133 };
134 const database = join(directory, 'session.sqlite');
135 const open = () => openPivi({ database, credentials, models, interact, editor() {} });
136 let runtime = await open();
137 t.after(async () => {
138 await runtime.close();
139 await rm(directory, { recursive: true, force: true });
140 });
141 const gated = async () => (await runtime.immediate.providers()).find((provider) => provider.id === 'gated');
143 assert.deepEqual((await gated()).methods.map((method) => method.type), ['oauth', 'api_key']);
144 assert.equal((await gated()).stored, undefined);
145 assert.deepEqual(await runtime.commands.models(), []);
147 const pending = runtime.immediate.login({ provider: 'gated', method: 'oauth' });
148 await assert.rejects(runtime.immediate.login({ provider: 'gated', method: 'api_key' }), /in progress/);
149 while (prompts === 0) await new Promise((resolve) => setTimeout(resolve, 5));
150 await runtime.immediate.cancel();
151 await assert.rejects(pending);
152 assert.deepEqual(events, ['auth_url']);
153 assert.equal((await gated()).stored, undefined);
155 await runtime.immediate.login({ provider: 'gated', method: 'api_key' });
156 assert.equal((await gated()).stored, 'api_key');
157 assert.equal((await gated()).source, 'stored key');
158 assert.deepEqual(await runtime.commands.models(), [{ provider: 'gated', modelId: 'locked' }]);
160 await runtime.close();
161 runtime = await open();
162 assert.deepEqual(await runtime.commands.models(), [{ provider: 'gated', modelId: 'locked' }]);
163 await runtime.immediate.logout({ provider: 'gated' });
164 assert.deepEqual(await runtime.commands.models(), []);
165});
167test('stop cancels a running tool, marks the request interrupted, and leaves the conversation usable', async (t) => {
168 let cancelled = false;
169 const hang = (signal) => new Promise((_, reject) => {
170 signal.addEventListener('abort', () => { cancelled = true; reject(new Error('cancelled')); });
171 });
172 const editor = (name, _args, { abortSignal }) => (name === 'nvim_lua' ? hang(abortSignal) : Promise.resolve({}));
173 const { runtime, faux } = await fixture(t, editor);
174 const texts = async () => (await runtime.conversation.context(context)).messages
175 .filter((message) => message.role === 'user')
176 .map((message) => (typeof message.content === 'string' ? message.content : message.content[0].text));
178 await runtime.immediate.abort();
179 assert.deepEqual(await texts(), []);
181 faux.setResponses([
182 fauxAssistantMessage(fauxToolCall('nvim_lua', { code: 'return system("sleep 600")' }), { stopReason: 'toolUse' }),
183 fauxAssistantMessage('Fresh answer.'),
184 ]);
185 await runtime.commands.submit({ content: 'Run something slow' });
186 while (!(await runtime.harness.snapshot(LiveDoc, runtime.conversation.id, context))?.tools?.length) {
187 await new Promise((resolve) => setTimeout(resolve, 5));
188 }
189 const started = Date.now();
190 await runtime.immediate.abort();
191 assert.ok(Date.now() - started < 1000);
192 assert.equal(cancelled, true);
193 assert.deepEqual(await texts(), ['Run something slow', '[interrupted]']);
194 assert.equal((await runtime.harness.snapshot(LiveDoc, runtime.conversation.id, context)).run, undefined);
196 const next = await runtime.commands.submit({ content: 'Something else' });
197 const settled = await (await runtime.harness.submission(next.id, context)).wait(context);
198 assert.equal(settled.status, 'done');
199});
201test('stock file tools act on editor buffers, not disk', async (t) => {
202 const project = await mkdtemp(join(tmpdir(), 'pivi-project-'));
203 t.after(() => rm(project, { recursive: true, force: true }));
204 await writeFile(join(project, 'a.txt'), 'on disk\n');
205 const buffers = new Map([[join(project, 'a.txt'), 'unsaved in editor\n']]);
206 const editor = async (name, args) => {
207 if (name === 'unsaved_text') return buffers.has(args.path) ? { text: buffers.get(args.path) } : {};
208 if (name === 'set_text') buffers.set(args.path, args.content);
209 return {};
210 };
211 const { runtime, faux } = await fixture(t, editor, project);
212 const call = (name, args) => fauxAssistantMessage(fauxToolCall(name, args), { stopReason: 'toolUse' });
213 faux.setResponses([
214 call('read', { path: 'a.txt' }),
215 call('edit', { path: 'a.txt', edits: [{ oldText: 'unsaved', newText: 'edited' }] }),
216 call('write', { path: 'new/b.txt', content: 'brand new\n' }),
217 fauxAssistantMessage('Done.'),
218 ]);
219 await runtime.commands.submit({ content: 'Work on the files' });
220 await runtime.conversation.waitForIdle(context);
221 const results = (await runtime.conversation.context(context)).messages
222 .filter((message) => message.role === 'toolResult')
223 .map((message) => [message.isError, message.content.map((part) => part.text).join('')]);
224 assert.deepEqual(results.map(([failed]) => failed), [false, false, false]);
225 assert.match(results[0][1], /unsaved in editor/);
226 assert.equal(buffers.get(join(project, 'a.txt')), 'edited in editor\n');
227 assert.equal(buffers.get(join(project, 'new/b.txt')), 'brand new\n');
228 assert.equal(await readFile(join(project, 'a.txt'), 'utf8'), 'on disk\n');
229 assert.equal(existsSync(join(project, 'new/b.txt')), false);
230});
232test('missing model rejects before admitting user input', async (t) => {
233 const { runtime } = await fixture(t);
234 await runtime.conversation.configure({ model: null }, context);
235 await assert.rejects(runtime.commands.submit({ content: 'Keep this draft' }), /Choose a model/);
236 assert.equal((await runtime.conversation.context(context)).messages.length, 0);
237});

neovim/pivi/tools.mjs

Added
new file mode 100644

+119 / −0 text lines

1import { defineExtension, defineTool, section } from '@earendil-works/pi-durable';
2import { arr, bool, num, obj, oneOf, opt, str } from '@earendil-works/pi-schema';
3
4const GUIDE = `You are pivi, a coding agent living inside the user's running Neovim.
5
6Buffers are the truth. A buffer may hold unsaved changes that its file on disk lacks.
7- read, edit and write work on Neovim buffers: they see unsaved changes, and what they change stays unsaved
8 and undoable.
9- nvim_lua runs Lua inside the editor with the whole vim API. It is also how you run programs:
10 local r = system('nvim -l check.lua') returns code, stdout and stderr without freezing the editor.
11 Programs see saved files only; the output names the unsaved buffers they could not see.
12- save writes buffers to disk. Save only when the user asks or a command must see your change, and say that you saved.
13- lsp asks the language server: definitions, references, hover, symbols, rename. It sees unsaved changes.
14 Prefer it over text search for code navigation.
15- find lists files, search searches file contents - both without a shell. Reach for nvim_lua's system() only
16 when a real program must run (git, a build, a script); never for listing or searching files.
17- diagnostics lists what the language servers report.
19The editor belongs to the user. Do not change their window, current buffer, cursor, working directory, options,
20registers or global Lua state unless they ask. To point at code, name the file and line.
21Each user message starts with an automatic [editor: ...] note saying where the user is. Use it; never repeat it.
22A message "[interrupted]" means the user stopped the request before it. Do not continue that request unless asked.
24Do not claim execution or verification you did not perform.
26You run inside pivi, a Neovim plugin whose source lives in this repository: lua/bugabinga/pivi/ (editor side)
27and pivi/ (worker, tests, README). When asked to change pivi itself, read those files first - bindings are listed
28in view.lua (ACTIONS), commands in init.lua. You can edit pivi while it runs; changes to lua/ take effect after
29the user runs :PiviReload, changes to pivi/*.mjs on the same reload (the worker restarts with it). Ask the user
30to reload between turns - reloading mid-request breaks the running agent turn.`;
32const path = (description) => str({ description: `${description} (relative to the working directory, or absolute)` });
34const TOOLS = [
35 {
36 name: 'find',
37 description: 'List files by glob, newest first, without a shell. Use this instead of ls or find: '
38 + 'it excludes .git, node_modules and build output, and returns paths relative to the working directory.',
39 parameters: obj({
40 glob: opt(str({ description: 'Glob for the file name, e.g. "*.lua" or "*.spec.ts"; default all files' })),
41 path: opt(path('Directory to search, default the working directory')),
42 limit: opt(num({ description: 'Maximum number of files, default 100' })),
43 }),
44 },
45 {
46 name: 'search',
47 description: 'Search file contents with ripgrep, without a shell. Use this instead of grep or rg on the command '
48 + 'line: it sees saved files only (name the unsaved buffers in your reasoning), never touches unsaved ones, '
49 + 'and returns path:line:col matches with the source line.',
50 parameters: obj({
51 pattern: str({ description: 'Regular expression (or literal text with literal: true)' }),
52 literal: opt(bool({ description: 'Match the pattern as literal text, not a regular expression' })),
53 path: opt(path('File or directory to search, default the working directory')),
54 glob: opt(str({ description: 'Restrict to file names matching this glob, e.g. "*.lua"' })),
55 max: opt(num({ description: 'Maximum number of matches, default 100' })),
56 }),
57 },
58 {
59 name: 'save',
60 description: 'Write the named buffers to disk, creating parent directories.',
61 executionMode: 'sequential',
62 parameters: obj({ paths: arr(path('Buffer to save')) }),
63 },
64 {
65 name: 'lsp',
66 description: 'Ask the language server attached in Neovim. It sees unsaved changes. '
67 + 'Locations come back as path:line:col with the source line. rename edits buffers and leaves them unsaved.',
68 executionMode: 'sequential',
69 parameters: obj({
70 operation: oneOf([
71 'definition', 'references', 'implementation', 'type_definition', 'hover', 'rename', 'symbols',
72 'workspace_symbols',
73 ], { description: 'symbols outlines one file; workspace_symbols searches the project by name' }),
74 path: opt(path('File; required except for workspace_symbols')),
75 line: opt(num({ description: 'Line of the symbol, 1-indexed; required for position operations' })),
76 symbol: opt(str({ description: 'The symbol text as written on that line, to locate the column' })),
77 newName: opt(str({ description: 'New name, for rename' })),
78 query: opt(str({ description: 'Name to search, for workspace_symbols' })),
79 }),
80 },
81 {
82 name: 'diagnostics',
83 description: 'List diagnostics (errors, warnings) that Neovim holds, for one file or for all loaded buffers. '
84 + 'They come from language servers and can lag behind fresh edits.',
85 parameters: obj({ path: opt(path('File to check, default all loaded buffers')) }),
86 },
87 {
88 name: 'nvim_lua',
89 description: 'Run a Lua chunk inside the live Neovim and get its return value back. The full vim API, vim.uv and '
90 + 'plugins are available. The chunk runs as a coroutine, so it can wait without freezing the editor:\n'
91 + '- system(command, { cwd, stdin, timeout }) runs a shell command string or an argv table, streams its '
92 + 'output, and returns { code, signal, timed_out, stdout, stderr }. Programs see saved files only.\n'
93 + '- await(function(resolve) ... end) suspends until resolve(value) is called from any callback and returns '
94 + 'that value; return a function from the starter to be run if the user stops the request.\n'
95 + '- sleep(milliseconds).\n'
96 + 'Blocking calls are refused: vim.wait, vim.system(...):wait(), vim.fn.system. '
97 + 'A chunk that computes for 10 s without yielding is stopped. '
98 + 'system() closes stdin and kills the whole process group on timeout (default 60 s; pass a shorter one when you can). '
99 + 'Never put multiline code on a command line - write a script file and run it (nvim -l script.lua); '
100 + 'a program stuck at an interactive prompt blocks until the timeout kills it. '
101 + 'Ex commands: vim.api.nvim_exec2(command, { output = true }).output',
102 executionMode: 'sequential',
103 outputLimits: { retain: 'tail' },
104 parameters: obj({ code: str({ description: 'Lua chunk; return a compact JSON-compatible value' }) }),
105 },
106];
108export const neovim = (editor) => defineExtension({
109 name: 'pivi.neovim',
110 sections: [section('pivi', () => GUIDE)],
111 tools: TOOLS.map((tool) => defineTool({
112 ...tool,
113 async execute(args, api, callContext) {
114 const result = await editor(tool.name, args, callContext, (text) => api.output(text));
115 const output = result?.text === undefined ? undefined : [{ type: 'text', text: result.text }];
116 return { ...(output && { output }), isError: result?.error === true };
117 },
118 })),
119});

neovim/pivi/worker.mjs

Added
new file mode 100644

+105 / −0 text lines

1import { mkdir } from 'node:fs/promises';
2import { dirname, join } from 'node:path';
3import { pathToFileURL } from 'node:url';
4import { fileCredentials } from './credentials.mjs';
5import { openPivi } from './harness.mjs';
6
7const [database, authentication, config] = process.argv.slice(2);
8if (!database || !authentication) throw new Error('Session database and credential file paths are required.');
9
10const send = (record) => new Promise((done) => process.stdout.write(JSON.stringify(record) + '\n', done));
12const pending = new Map();
13let sequence = 0;
14let closing = false;
16function ask(record, signal, onProgress) {
17 return new Promise((resolve, reject) => {
18 if (closing || signal?.aborted) return reject(new Error('Neovim request cancelled.'));
19 const id = ++sequence;
20 const abort = () => {
21 send({ type: 'cancel', id });
22 finish(false, 'Neovim request cancelled.');
23 };
24 const finish = (ok, result) => {
25 pending.delete(id);
26 signal?.removeEventListener('abort', abort);
27 ok ? resolve(result) : reject(new Error(result));
28 };
29 pending.set(id, { finish, onProgress });
30 signal?.addEventListener('abort', abort, { once: true });
31 send({ ...record, id });
32 });
33}
35let shown;
36function show({ items, ...view }) {
37 if (items !== shown) view.items = shown = items;
38 return send({ type: 'view', view });
39}
41await mkdir(dirname(database), { recursive: true });
42const credentials = fileCredentials(authentication);
43const modelsFile = join(dirname(authentication), 'models.json');
44const options = config ? await (await import(pathToFileURL(config).href)).default({ credentials }) : {};
45const runtime = await openPivi({
46 ...options, database, credentials, modelFile: modelsFile, onView: show,
47 editor: (name, args, context, onProgress) => ask({ type: 'tool', name, args }, context.abortSignal, onProgress),
48 interact: {
49 prompt: ({ signal, ...prompt }) => ask({ type: 'prompt', prompt }, signal),
50 notify: (event) => send({ type: 'auth', event }),
51 },
52 onNotice: (message) => send({ type: 'notice', message }),
53 onReport: (report) => send({ type: 'report', error: String(report.error ?? report.kind) }),
54});
55runtime.harness.closed.then((end) => {
56 if (end.kind !== 'failed') return;
57 console.error(end.error);
58 process.exit(1);
59});
60await send({ type: 'ready' });
62async function respond({ id, method, params = {} }, operations) {
63 try {
64 await send({ type: 'response', id, ok: true, result: (await operations[method](params)) ?? null });
65 } catch (error) {
66 await send({ type: 'response', id, ok: false, error: error.message });
67 }
68}
70let commands = Promise.resolve();
71function receive(line) {
72 const record = JSON.parse(line);
73 if (record.type === 'reply') {
74 pending.get(record.id)?.finish(record.ok, record.ok ? record.result : record.error);
75 } else if (record.type === 'progress') {
76 pending.get(record.id)?.onProgress?.(record.text);
77 } else if (Object.hasOwn(runtime.immediate, record.method)) {
78 respond(record, runtime.immediate);
79 } else if (Object.hasOwn(runtime.commands, record.method)) {
80 commands = commands.then(() => respond(record, runtime.commands));
81 } else {
82 send({ type: 'response', id: record.id, ok: false, error: `Unknown pivi operation: ${record.method}` });
83 }
84}
86let tail = '';
87process.stdin.setEncoding('utf8');
88process.stdin.on('data', (chunk) => {
89 const lines = (tail + chunk).split('\n');
90 tail = lines.pop();
91 for (const line of lines) if (line) receive(line);
92});
94async function shutdown() {
95 if (closing) return;
96 closing = true;
97 for (const { finish } of [...pending.values()]) finish(false, 'Neovim disconnected.');
98 await runtime.immediate.cancel();
99 await commands;
100 await runtime.close();
101 await new Promise((flushed) => process.stdout.write('', flushed));
102 process.stdin.destroy();
103}
104process.stdin.on('end', shutdown);
105process.on('SIGTERM', shutdown);

neovim/puk.nu

Modified

+328 / −61 text lines

11# an out-of-band plugin manager for neovim.
22# cannot do a lot, compared to "normal" neovim plugin managers, but:
3# - it does not depend on git, only on tar and curl (and nushell right now, but that could change)
4# - tar and curl should be available on any system that neovim is installed, even win32
53# - does not incur runtime costs on neovim
64# - uses built-in vim packages
5let tar_command = if $nu.os-info.name == 'windows' {
6 [$env.SystemRoot System32 tar.exe] | path join
7} else { 'tar' }
8
9let compiler = if $nu.os-info.name == 'android' and ($env.TERMUX_VERSION? != null) { 'clang' } else { 'zig' }
11def require-compiler [] {
12 if (which $compiler | is-empty) {
13 let name = if $compiler == 'clang' { 'Clang' } else { 'Zig' }
14 error make { msg: $"puk requires ($name) in PATH." }
15 }
16}
18def refuse-running-neovim [] {
19 let processes = ps | where { |process|
20 let name = $process.name | path basename | str lowercase
21 $name in [ 'nvim' 'nvim.exe' ]
22 }
23 if not ($processes | is-empty) {
24 let pids = $processes.pid | each { into string } | str join ', '
25 [
26 $"Error: Neovim is running, PIDs: ($pids). Plugin installation stopped."
27 'Why: updating Treesitter parsers while Neovim holds parser DLLs can leave stale files and break health checks.'
28 'Action: close every Neovim instance, then rerun `just puk`.'
29 ] | str join (char nl) | print --stderr
30 exit 1
31 }
32}
734def main [] {
8 let data_path = nvim --headless --clean +'lua print(vim.fn.stdpath "data")' +q | complete | get stderr
9 let cache_path = nvim --headless --clean +'lua print(vim.fn.stdpath "cache")' +q | complete | get stderr
35 require-compiler
36 refuse-running-neovim
37 let paths_result = (nvim --headless --clean --cmd 'lua io.stdout:write(vim.json.encode({ data = vim.fn.stdpath("data"), cache = vim.fn.stdpath("cache") }))' +q | complete)
38 if $paths_result.exit_code != 0 {
39 error make { msg: $"Neovim path lookup failed: ($paths_result.stderr)" }
40 }
41 let paths = $paths_result.stdout | from json
42 let data_path = $paths.data
43 let cache_path = $paths.cache
1044 if not ($cache_path | path exists) {
1145 print $"creating cache path: ($cache_path)"
1246 mkdir $cache_path
1347 }
1448 let plugins_path = [ $data_path site pack puk opt ] | path join
15 let plugin_specs = open puk.plugins.nuon
16 let total = $plugin_specs | length
17 print $"Installing plugins from puk.plugins.nuon. total: ($total)"
18 let errors = $plugin_specs | par-each { install-spec $in $plugins_path $cache_path } | flatten
49 let site_path = [ $data_path site ] | path join
50 let base = $env.PWD
51 let plugin_specs = (open ($base | path join puk.plugins.nuon) | collect)
52 let parser_specs = (open ($base | path join puk.parsers.nuon) | collect)
53 if (not ($parser_specs | is-empty)) and ((which tree-sitter | is-empty)) {
54 print "puk.parsers.nuon declares parsers but the tree-sitter CLI is not in PATH."
55 print "Install tree-sitter-cli (>= 0.26) first."
56 exit 1
57 }
58 let all_specs = ($plugin_specs | append $parser_specs)
59 let total = $all_specs | length
60 print $"Installing plugins and parsers from puk.*.nuon. total: ($total)"
61 let pending_hooks = $plugin_specs | where { |spec|
62 ($spec.post_install? | default null) != null and not (plugin-is-installed $spec $plugins_path)
63 }
64 let plugin_errors = $plugin_specs | par-each { install-spec $in $plugins_path $site_path $cache_path } | flatten
65 let hook_errors = $pending_hooks | where { |spec| $spec.name not-in $plugin_errors.name } | each { |spec|
66 finish-plugin $spec $plugins_path
67 } | flatten
68 let parser_errors = $parser_specs | each { install-spec $in $plugins_path $site_path $cache_path } | flatten
69 let errors = ($plugin_errors | append $hook_errors | append $parser_errors)
1970 print 'Cleaning plugins, that are not part of puk.plugins.nuon.'
2071 clean-plugins $plugins_path $plugin_specs
2172 print 'Cleaning stale cache archives.'
22 clean-cache $cache_path $plugin_specs
73 clean-cache $cache_path $all_specs
2374 # plugins need to be packadded before helptags can be generated
2475 print 'Generating helptags.'
2576 mut packs = $plugin_specs | par-each { | spec |
3788# check online for fresh commits. Does not actually mutate or update anything.
3889# updated plugin specs will be written to a new file.
3990def 'main update' [] {
40 print "Checking for fresh commits of plugins online..."
41 let plugin_specs = open puk.plugins.nuon
91 require-compiler
92 update-file puk.plugins.nuon
93 update-file puk.parsers.nuon
94}
43 let updated = $plugin_specs |
96# check one spec nuon file for fresh upstream commits; writes updated specs to a new file.
97def update-file [
98 path: string # nuon file with plugin or parser specs
99] {
100 print $"Checking for fresh commits of specs in ($path)..."
101 let specs = open $path
102 let updated = $specs |
44103 update commit {
45104 |spec|
46105 let fresh_commit = find-latest-commit $spec
47106 if ($fresh_commit != $spec.commit) {
48 print $"Found fresh commit for ($spec.name):($fresh_commit)!"
49 return $fresh_commit
107 print $"Found fresh commit for ($spec.name): ($fresh_commit)!"
108 $fresh_commit
109 } else {
110 $spec.commit
50111 }
51 return $spec.commit
52112 }
54 if not ($plugin_specs == $updated) {
55 $plugin_specs |
56 merge $updated |
114 if not ($specs == $updated) {
115 let target = ($path | str replace '.nuon' '.updated.nuon')
116 $updated |
57117 to nuon --indent 2 |
58 save --force puk.plugins.updated.nuon
59 print "Written updated puk.plugins into puk.plugins.updated.nuon!"
118 save --force $target
119 print $"Written updated specs into ($target)!"
60120 } else {
61121 print "Nothing to do."
62122 }
72132 let existing_plugin_name = $row.name | path basename
73133 if ( $plugin_specs | where name == $existing_plugin_name | is-empty) {
74134 print $"Found plugin, that is not part of the specs: ($existing_plugin_name)"
75 rm --trash --recursive $row.name
135 rm --recursive $row.name
76136 }
77137 }
84144] {
85145 let expected = $plugin_specs | each { |spec| (make-archive-path $spec $cache_path | path basename) }
86146 try {
87 glob $"($cache_path)/*.tar.gz" | each { |path|
147 glob $"($cache_path | str replace --all '\' '/')/*.tar.gz" | each { |path|
88148 let name = $path | path basename
89149 if ($expected | where $it == $name | is-empty) {
90150 print $"Removing stale cache: ($name)"
206266] {
207267 let archive_path = make-archive-path $spec $cache_path
208268 if ($archive_path | path exists) {
209 print $"($spec.name) already cached in ($archive_path)"
210 return $archive_path
269 let checked = (run-external $tar_command '--list' '--file' $archive_path | complete)
270 if $checked.exit_code == 0 {
271 print $"($spec.name) already cached in ($archive_path)"
272 return $archive_path
273 }
274 rm $archive_path
211275 }
212276 let url = generate-download-url $spec
277 let partial_path = mktemp --tmpdir-path $cache_path 'puk-download.XXXXXX'
213278 try {
214 http get --raw --max-time 5sec $url | save $archive_path
215 } catch {
216 print $"Download of ($spec.name) timed out, retrying..."
217 http get --raw --max-time 10sec $url | save $archive_path
279 try {
280 http get --raw --max-time 5sec $url | save --force $partial_path
281 } catch {
282 print $"Download of ($spec.name) failed, retrying..."
283 http get --raw --max-time 10sec $url | save --force $partial_path
284 }
285 let checked = (run-external $tar_command '--list' '--file' $partial_path | complete)
286 if $checked.exit_code != 0 {
287 error make { msg: $"($spec.name): invalid archive: ($checked.stderr)" }
288 }
289 mv $partial_path $archive_path
290 $archive_path
291 } finally {
292 if ($partial_path | path exists) { rm $partial_path }
218293 }
219 $archive_path
294}
296def tree-hash [dir: path] {
297 glob $"($dir | str replace --all '\' '/')/**/*" | where { |f| ($f | path type) == file } | each { |f|
298 { rel: ($f | path relative-to $dir), h: (open --raw $f | hash sha256) }
299 }
300}
302def diff-hashes [base: path, hashes: list, label: string, name: string] {
303 let now = (tree-hash $base)
304 $hashes | each { |x|
305 let y = ($now | where rel == $x.rel)
306 if ($y | is-empty) { $"VERIFY ($name) ($label): missing ($x.rel)" } else if ($y | first | get h) != $x.h { $"VERIFY ($name) ($label): content ($x.rel)" } else { '' }
307 } | where { |s| $s != '' }
222310def unpack-plugin-archive [
224312 archive_path: path # path to a plugin archive
225313] {
226314 let tmp_path = mktemp --directory
227 # hopefully strip-componets works on win32 as well
228 print $archive_path $tmp_path
229 tar --extract --file $archive_path --directory $tmp_path --strip-components=1
231 if $spec.build != null {
232 print $"Build step for plugin ($spec.name) detected! Executing now..."
233 cd $tmp_path
234 run-external $spec.build.0 ...($spec.build | slice 1.. )
315 try {
316 let extracted = (run-external $tar_command '--extract' '--file' $archive_path '--directory' $tmp_path '--strip-components=1' | complete)
317 if $extracted.exit_code != 0 {
318 error make { msg: $"($spec.name): extraction failed: ($extracted.stderr)" }
319 }
320 if $spec.build != null {
321 print $"Build step for plugin ($spec.name) detected! Executing now..."
322 run-nu-in-dir $tmp_path $spec.build
323 }
324 $tmp_path
325 } catch { |e|
326 rm --recursive $tmp_path
327 error make { msg: $e.msg }
235328 }
236 $tmp_path
239let allowed_shared_lib_type = match ( sys host | get name ) {
240 $name if $name =~ 'Windows' => { 'dll' },
241 $name if $name =~ 'Linux' => { 'so' },
242 $name if $name =~ 'NixOS' => { 'so' },
243 $name if $name =~ 'Mac' => { 'dylib' },
244 $name if $name =~ 'Pixel' => { 'so' },
245 _ => { error make { msg: 'unknown operating system' } },
331let allowed_shared_lib_type = match $nu.os-info.name {
332 windows => 'dll',
333 macos => 'dylib',
334 _ => 'so',
247336let base_filetypes = [ lua vim scm txt $allowed_shared_lib_type ]
266355 let tmp_path = [$plugins_path $".tmp.($spec.name)"] | path join
267356 try { rm --recursive $tmp_path }
268357 mkdir $tmp_path
269 cd $folder_path
270358 let filetypes = if ($spec.extra_extensions? | default null) != null {
271359 $base_filetypes | append $spec.extra_extensions
272360 } else {
273361 $base_filetypes
274362 }
275 glob $"**/*.{($filetypes | str join ',')}" --exclude $exclusions |
276 path relative-to (pwd) |
277 par-each { | file |
278 let rebased_parent = [$tmp_path ($file | path dirname | to text)] | path join
363 let copied = (glob $"($folder_path | str replace --all '\' '/')/**/*.{($filetypes | str join ',')}" --exclude $exclusions | each { |f| { rel: ($f | path relative-to $folder_path), h: (open --raw $f | hash sha256) } })
364 $copied | each { | entry |
365 let rebased_parent = [$tmp_path ($entry.rel | path dirname)] | path join
279366 mkdir $rebased_parent
280 cp $file $rebased_parent
367 cp ([$folder_path $entry.rel] | path join) $rebased_parent
281368 }
282 let commit_file_path = make-commit-file-path $tmp_path
283 $spec.commit | save --force $commit_file_path
284 try { rm --trash --recursive $plugin_path }
369 let copy_problems = (diff-hashes $tmp_path $copied 'copy' $spec.name)
370 if not ($copy_problems | is-empty) {
371 error make { msg: $"($spec.name) copy verification failed: ($copy_problems | str join ', ')" }
372 }
373 try { rm --recursive $plugin_path }
285374 mv $tmp_path $plugin_path
375 let move_problems = (diff-hashes $plugin_path $copied 'move' $spec.name)
376 if not ($move_problems | is-empty) {
377 rm --recursive $plugin_path
378 error make { msg: $"($spec.name) move verification failed: ($move_problems | str join ', ')" }
379 }
286380 $plugin_path
289def install-spec [
290 spec: record # a plugin to install
291 plugins_path: path # folder to install plugins into
383def run-nu-in-dir [
384 dir: path
385 command: string
386] {
387 cd $dir
388 let result = (run-external $nu.current-exe '--no-config-file' '--commands' $command | complete)
389 print --no-newline $result.stdout
390 print --stderr --no-newline $result.stderr
391 if $result.exit_code != 0 {
392 error make { msg: $"Build failed with exit code ($result.exit_code)" }
393 }
394}
396# the tree-sitter CLI compiles parsers with cc-rs, which takes only the program
397# name from the CC env var and drops everything after it. 'zig cc' therefore
398# needs a wrapper script, to carry the subcommand into the compiler call.
399def make-compiler-wrapper [
400 cache_path: path # folder to cache the compiler wrapper into
401] {
402 let is_windows = ($nu.os-info.name == 'windows')
403 let wrapper = if $is_windows {
404 [$cache_path 'puk-zig-cc.cmd'] | path join
405 } else {
406 [$cache_path 'puk-zig-cc.sh'] | path join
407 }
408 let script = if $is_windows {
409 ['@zig cc %*']
410 } else {
411 ['#!/bin/sh', 'exec zig cc "$@"']
412 }
413 $script | save --force $wrapper
414 if not $is_windows {
415 run-external chmod '+x' $wrapper
416 }
417 $wrapper
418}
420def install-spec-parser [
421 spec: record # a parser to install
422 site_path: path # nvim site dir (parsers/queries install root)
292423 cache_path: path # folder to cache downloaded archives into
293424] {
425 let parser_so = [$site_path parser $"($spec.name).so"] | path join
426 let pin_path = [$site_path parser $".($spec.name).commit.puk"] | path join
427 let queries_target = [$site_path queries $spec.name] | path join
428 let has_queries = ($spec.queries? | default null) != null
429 let queries_ready = if $has_queries {
430 (glob $"($queries_target | str replace --all '\' '/')/*.scm" | length) > 0
431 } else { true }
432 if ($parser_so | path type) == file and $queries_ready and ($pin_path | path type) == file and ((open --raw $pin_path | str trim) == $spec.commit) {
433 return []
434 }
435 try {
436 print $"Downloading parser ($spec.name)..."
437 let archive_path = download-plugin $spec $cache_path
438 print $"Unpacking parser ($spec.name)..."
439 let unpacked_path = unpack-plugin-archive { name: $spec.name, build: null } $archive_path
440 try {
441 let root = if ($spec.location? | default null) != null { [$unpacked_path $spec.location] | path join } else { $unpacked_path }
442 let source_ready = if $spec.generate {
443 ($root | path join src grammar.json | path exists) or ($root | path join grammar.js | path exists)
444 } else { $root | path join src parser.c | path exists }
445 if not $source_ready {
446 error make { msg: $"($spec.name): tarball is missing parser source or grammar" }
447 }
448 if $spec.generate {
449 print $"Generating parser ($spec.name)..."
450 let grammar = if ($root | path join src grammar.json | path exists) {
451 $root | path join src grammar.json
452 } else {
453 $root | path join grammar.js
454 }
455 let gen = (tree-sitter generate $grammar '--output' ($root | path join src) | complete)
456 if $gen.exit_code != 0 {
457 error make { msg: $"($spec.name): tree-sitter generate failed: ($gen.stderr)" }
458 }
459 }
460 print $"Compiling parser ($spec.name)..."
461 let so_tmp = ($root | path join $"($spec.name).so")
462 let compiler_env = {
463 CC: (if $compiler == 'clang' { 'clang' } else { (make-compiler-wrapper $cache_path) }),
464 CRATE_CC_NO_DEFAULTS: '1',
465 CFLAGS: (if $nu.os-info.name == 'windows' { $"-target ($nu.os-info.arch)-windows-gnu -O2" } else { '-O2 -fPIC' })
466 }
467 let built = with-env $compiler_env {
468 tree-sitter build '--output' $so_tmp $root | complete
469 }
470 if $built.exit_code != 0 {
471 error make { msg: $"($spec.name): tree-sitter build failed: ($built.stderr)" }
472 }
473 if not ($so_tmp | path exists) {
474 error make { msg: $"($spec.name): compile produced no .so" }
475 }
476 let staged_queries = [$unpacked_path '.puk-queries'] | path join
477 if $has_queries {
478 let queries = glob $"([$root $spec.queries] | path join | str replace --all '\' '/')/*.scm"
479 if ($queries | is-empty) {
480 error make { msg: $"($spec.name): no .scm queries found" }
481 }
482 mkdir $staged_queries
483 $queries | each { |f| cp $f $staged_queries } | ignore
484 }
485 mkdir ($site_path | path join parser)
486 let old_parser = [$unpacked_path '.puk-old-parser'] | path join
487 let old_queries = [$unpacked_path '.puk-old-queries'] | path join
488 let old_pin = if ($pin_path | path type) == file { open --raw $pin_path } else { null }
489 if ($parser_so | path exists) { cp $parser_so $old_parser }
490 mut queries_replaced = false
491 let failure = try {
492 if $has_queries {
493 mkdir ($queries_target | path dirname)
494 if ($queries_target | path exists) { mv $queries_target $old_queries }
495 $queries_replaced = true
496 mv $staged_queries $queries_target
497 }
498 cp --force $so_tmp $parser_so
499 $spec.commit | save --force $pin_path
500 null
501 } catch { |e| $e }
502 if $failure != null {
503 if ($old_parser | path exists) {
504 cp --force $old_parser $parser_so
505 } else if ($parser_so | path exists) { rm $parser_so }
506 if $queries_replaced {
507 if ($queries_target | path exists) { rm --recursive $queries_target }
508 if ($old_queries | path exists) { mv $old_queries $queries_target }
509 }
510 if $old_pin != null {
511 $old_pin | save --force $pin_path
512 } else if ($pin_path | path type) == file { rm $pin_path }
513 error make { msg: $failure.msg }
514 }
515 print $"Parser ($spec.name) installed into ($parser_so)!"
516 []
517 } finally {
518 rm --recursive $unpacked_path
519 }
520 } catch {
521 |e|
522 print $"FAILED parser ($spec.name): ($e.msg)"
523 return [{ name: $spec.name, error: $e.msg }]
524 }
525}
527def install-spec [
528 spec: record # a plugin or parser to install
529 plugins_path: path # folder to install plugins into
530 site_path: path # nvim site dir (parser install root)
531 cache_path: path # folder to cache downloaded archives into
532] {
533 if ($spec.generate? != null) {
534 return (install-spec-parser $spec $site_path $cache_path)
535 }
294536 if (plugin-is-installed $spec $plugins_path) {
295537 return []
296538 }
299541 let archive_path = download-plugin $spec $cache_path
300542 print $"Unpacking ($spec.name)..."
301543 let unpacked_path = unpack-plugin-archive $spec $archive_path
302 print $"Installing ($spec.name)..."
303 let installed_plugin_path = install-plugin $spec $unpacked_path $plugins_path
304 print $"Plugin ($spec.name) installed into ($installed_plugin_path)!"
305 return []
544 try {
545 print $"Installing ($spec.name)..."
546 let installed_plugin_path = install-plugin $spec $unpacked_path $plugins_path
547 if ($spec.post_install? | default null) == null {
548 $spec.commit | save --force (make-commit-file-path $installed_plugin_path)
549 }
550 print $"Plugin ($spec.name) installed into ($installed_plugin_path)!"
551 []
552 } finally {
553 rm --recursive $unpacked_path
554 }
306555 } catch {
307556 |e|
308557 print $"FAILED ($spec.name): ($e.msg)"
309558 return [{ name: $spec.name, error: $e.msg }]
310559 }
562def finish-plugin [spec: record, plugins_path: path] {
563 try {
564 print $"Running post-install for ($spec.name)..."
565 let commands = $spec.post_install | each { |cmd| $cmd | to json --raw } | str join ', '
566 let script = 'lua for _, command in ipairs({%s}) do local ok, err = pcall(vim.cmd, command); if not ok then vim.api.nvim_err_writeln(tostring(err)); vim.cmd.cquit(1) end end' | str replace '%s' $commands
567 let result = (nvim --headless -c $script +qa | complete)
568 print --no-newline $result.stdout
569 print --stderr --no-newline $result.stderr
570 if $result.exit_code != 0 {
571 error make { msg: $"($spec.name) post-install failed with exit code ($result.exit_code)" }
572 }
573 $spec.commit | save --force (make-commit-file-path (make-plugin-path $spec $plugins_path))
574 []
575 } catch { |e|
576 [{ name: $spec.name, error: $e.msg }]
577 }
578}

neovim/puk.parsers.nuon

Added
new file mode 100644

+6 / −0 text lines

1[
2 [name, source, repo, branch, commit, generate, queries, location];
3 ["d2", github, "ravsii/tree-sitter-d2", main, "7bba28221d8c466d28b725124494bf89219326fd", true, queries, null],
4 [gherkin, github, binhtddev/tree-sitter-gherkin, main, "6bd665dd7d4159c63c0b7a9f69d784f3315328c1", false, null, null],
5 [asciidoc, github, cathaysia/tree-sitter-asciidoc, master, "882e43173427b831cd0d98ab3525501bed6ea214", false, queries, tree-sitter-asciidoc]
6]No final newline

neovim/puk.plugins.nuon

Modified

+35 / −39 text lines

11[
2 [name, source, repo, branch, commit, build];
3 [nvim-treesitter, github, nvim-treesitter/nvim-treesitter, main, "4916d6592ede8c07973490d9322f187e07dfefac", [
4 nvim,
5 --headless,
6 -u,
7 NONE,
8 "+packadd nvim-treesitter",
9 "lua require 'bugabinga.treesitter'",
10 "+:TSUpdate",
11 +q
2 [name, source, repo, branch, commit, build, post_install];
3 [nvim-treesitter, github, nvim-treesitter/nvim-treesitter, main, "37e52c733ada9d8d544d53a763140ef1ba404353", null, [
4 "packadd nvim-treesitter",
5 "lua require 'bugabinga.treesitter'.post_install()"
126 ]],
13 [nvim-treesitter-textobjects, github, nvim-treesitter/nvim-treesitter-textobjects, main, "851e865342e5a4cb1ae23d31caf6e991e1c99f1e", null],
14 [nvim-ts-autotag, github, windwp/nvim-ts-autotag, main, "88c1453db4ba7dd24131086fe51fdf74e587d275", null],
15 [oil, github, "stevearc/oil.nvim", master, "0fcc83805ad11cf714a949c98c605ed717e0b83e", null],
16 [nvim-surround, github, kylechui/nvim-surround, main, "9291040de8cd8a4439eb64c441e8d5d2bf884a5a", null],
17 [conform, github, "stevearc/conform.nvim", master, "dca1a190aa85f9065979ef35802fb77131911106", null],
18 [plenary, github, "nvim-lua/plenary.nvim", master, "74b06c6c75e4eeb3108ec01852001636d85a932b", null],
19 ["mini.splitjoin", github, "echasnovski/mini.splitjoin", main, "8bd5a3d581b9f3dd3bc91fe495e210b8b0ee981d", null],
20 ["mini.pick", github, "echasnovski/mini.pick", main, "437d44eb57312f23e6b931704694fc294922cd88", null],
21 ["mini.extra", github, "echasnovski/mini.extra", main, "bc4e872500fd6d2ce252604e0ffa100f64f02280", null],
22 ["mini.hipatterns", github, "echasnovski/mini.hipatterns", main, "9eff319bbe66adfaf781a0d0e174baa08ba94909", null],
23 ["mini.clue", github, "echasnovski/mini.clue", main, "43bd6cf1c3ccdea46d403c32dbc4629fa6afa09d", null],
24 ["mini.bracketed", github, "echasnovski/mini.bracketed", main, "efb969a6a9583a5d48bfbe36363769351e38f967", null],
25 ["mini.diff", github, "echasnovski/mini.diff", main, "ab11575a6c147ecfba894d676d0c93e855021d34", null],
26 ["mini.jump2d", github, "echasnovski/mini.jump2d", main, "c0df3170873b712b61951781aeee9942a92ba1f1", null],
27 ["mini.move", github, "echasnovski/mini.move", main, "74d140143b1bb905c3d0aebcfc2f216fd237080e", null],
28 ["mini.icons", github, "echasnovski/mini.icons", main, "bac6317300e205335df425296570d84322730067", null],
29 [nvim-autopairs, github, windwp/nvim-autopairs, master, "59bce2eef357189c3305e25bc6dd2d138c1683f5", null],
30 [specs, github, "cxwx/specs.nvim", main, "4a2f6f71eaa054a9355a2f424b4723e68f7ce22c", null],
31 [rulebook, github, chrisgrieser/nvim-rulebook, main, "083dd66b498bc142386a7c96dddab73acbf4ec20", null],
32 [profile, github, "stevearc/profile.nvim", master, "30433d7513f0d14665c1cfcea501c90f8a63e003", null],
33 [grug-far, github, "MagicDuck/grug-far.nvim", main, "21790e59dd0109a92a70cb874dd002af186314f5", null],
34 [incline, github, "b0o/incline.nvim", main, "8b54c59bcb23366645ae10edca6edfb9d3a0853e", null],
35 [dap, github, mfussenegger/nvim-dap, master, "45a69eba683a2c448dd9ecfc4de89511f0646b5f", null],
36 [dapui, github, rcarriga/nvim-dap-ui, master, "1a66cabaa4a4da0be107d5eda6d57242f0fe7e49", null],
37 [nio, github, nvim-neotest/nvim-nio, master, "21f5324bfac14e22ba26553caf69ec76ae8a7662", null],
38 [dap-disasm, github, Jorenar/nvim-dap-disasm, master, "1119f3f2b22e411adcd123cdcf6d0425b61a31a7", null],
39 [nvim-dap-virtual-text, github, theHamsta/nvim-dap-virtual-text, master, "fbdb48c2ed45f4a8293d0d483f7730d24467ccb6", null],
40 ["mini.notify", github, "echasnovski/mini.notify", main, "9e68ab0a54f90567b4fec2de22c851dba8480439", null]
41]
7 [nvim-treesitter-textobjects, github, nvim-treesitter/nvim-treesitter-textobjects, main, "5c7b0263797dfd1bd6202f2b219f3b53a80b2187", null, null],
8 [nvim-ts-autotag, github, windwp/nvim-ts-autotag, main, "d7220b55e16ed3c04e88086256def5d282429493", null, null],
9 [oil, github, "stevearc/oil.nvim", master, "d3733d933833a0e59b813ecec99341527adf0c28", null, null],
10 [nvim-surround, github, kylechui/nvim-surround, main, "8b47db616ef658b8fc27e61db2896aa2f40134de", null, null],
11 [otter, github, "jmbuhr/otter.nvim", main, "6f05811621460eca983bf2cd877e63c59a40720e", null, null],
12 [conform, github, "stevearc/conform.nvim", master, "016802de402556da54c36bd7359b441266b01cdd", null, null],
13 [plenary, github, "nvim-lua/plenary.nvim", master, "74b06c6c75e4eeb3108ec01852001636d85a932b", null, null],
14 [wezterm-types, github, "DrKJeff16/wezterm-types", main, "1e6a0b7ac2206b197c741240743e981af37ce292", null, null],
15 ["mini.splitjoin", github, "echasnovski/mini.splitjoin", main, "ea8c7d0e7d0ab184e8e82b88a777e50277eba744", null, null],
16 ["mini.pick", github, "echasnovski/mini.pick", main, "406d41308e58486ea5c3352f5821c4cd9992af65", null, null],
17 ["mini.extra", github, "echasnovski/mini.extra", main, "8ed483ebaea4610c4b5e7b0fcc28854225946ddd", null, null],
18 ["mini.hipatterns", github, "echasnovski/mini.hipatterns", main, "7a79e5f000beb530ade0fa9faec70f01469dbcb3", null, null],
19 ["mini.clue", github, "echasnovski/mini.clue", main, "c8f246f080d4a7907990199151464978b43c9406", null, null],
20 ["mini.bracketed", github, "echasnovski/mini.bracketed", main, "ee8888fe7eda8a187bd2bfa0a992213451745ecd", null, null],
21 ["mini.diff", github, "echasnovski/mini.diff", main, "91d6ce4b7f400439fe761f01a58280f2c0f99c01", null, null],
22 ["mini.jump2d", github, "echasnovski/mini.jump2d", main, "6b451bfa93a801f5d0d4118a62298a178050a46f", null, null],
23 ["mini.move", github, "echasnovski/mini.move", main, "24d9bb2af6b6f747205fb5da0ec51a7d621077d7", null, null],
24 ["mini.icons", github, "echasnovski/mini.icons", main, "fc90b3925a2a68282be06e28cfe0cbb366c75dad", null, null],
25 [nvim-autopairs, github, windwp/nvim-autopairs, master, "3172f40c16563db871a58f20d205c710ad782311", null, null],
26 ["mini.animate", github, "echasnovski/mini.animate", main, "74d003a30c0c37c23015032516237c8cad09af9f", null, null],
27 [rulebook, github, chrisgrieser/nvim-rulebook, main, "0572382adde2eb03bde68da23c2aaac3577f503a", null, null],
28 [profile, github, "stevearc/profile.nvim", master, "30433d7513f0d14665c1cfcea501c90f8a63e003", null, null],
29 [grug-far, github, "MagicDuck/grug-far.nvim", main, "91b7e58b6ffc6ddad5acb7a7c1df21257724449e", null, null],
30 [incline, github, "b0o/incline.nvim", main, "debd628e9395f7a9da57bdc31ce75ca6b40a880b", null, null],
31 [dap, github, mfussenegger/nvim-dap, master, "cfa2d58f4537aca6ca83e2de1a0d9f1491121264", null, null],
32 [dapui, github, rcarriga/nvim-dap-ui, master, "cc9dd33aade7f20bae414d0cba163bc60d4d4b43", null, null],
33 [nio, github, nvim-neotest/nvim-nio, master, "edcc181a875301dd21840189aa2f2f9ad69fc172", null, null],
34 [dap-disasm, github, Jorenar/nvim-dap-disasm, master, "44c6eb0ec369962316b3d7c35d109be66666c6c1", null, null],
35 [nvim-dap-virtual-text, github, theHamsta/nvim-dap-virtual-text, master, "fbdb48c2ed45f4a8293d0d483f7730d24467ccb6", null, null],
36 ["mini.notify", github, "echasnovski/mini.notify", main, "7e89272723320a059d46faa3b67cf8220675bf21", null, null]
37]No final newline

neovim/queries/gherkin/highlights.scm

Added
new file mode 100644

+25 / −0 text lines

1(feature_line (feature_kw) @keyword)
2(feature_line (context) @title)
3
4(scenario_line (scenario_kw) @keyword)
5(scenario_outline_line (scenario_outline_kw) @keyword)
6(scenario_line (context) @title)
7(scenario_outline_line (context) @title)
8
9(rule_line (rule_kw) @keyword)
10(rule_line (context) @title)
12(background_line (background_kw) @keyword)
13(background_line (context) @title)
15(examples_line (examples_kw) @keyword)
17(given_line (given_kw) @keyword)
18(when_line (when_kw) @keyword)
19(then_line (then_kw) @keyword)
20(and_line (and_kw) @keyword)
21(but_line (but_kw) @keyword)
23(tags (tag) @tag)
24(comment) @comment @spell
25(doc_string) @string

neovim/sample_files/A.prg

Modified

+4 / −4 text lines

1CLEAR
2? "Hello, you glorious bastard of a world!"
3
4QUIT
1CLEAR
2? "Hello, you glorious bastard of a world!"
3
4QUIT

neovim/sample_files/test.container

Added
new file mode 100644

+2 / −0 text lines

1[Container]
2Image=docker.io/library/alpine:latest

neovim/sample_files/test.dockerfile

Added
new file mode 100644

+2 / −0 text lines

1FROM alpine
2RUN echo hi

neovim/sample_files/test.feature

Added
new file mode 100644

+42 / −0 text lines

1# language: en
2# Canonical Gherkin constructs from the cucumber.io reference — used to
3# validate the tree-sitter-gherkin parser against real syntax.
4
5Feature: Beverages
6 Users can pay for beverages and receive change
7 Step definitions live in the drink service
8
9 Background:
10 Given a customer named "barry"
11 And a coffee named "espresso" priced at 2
13 @golden @smoke
14 Scenario: Buying a coffee
15 Given barry has bought an "espresso"
16 When barry drinks the espresso
17 Then barry should be "happy"
19 Scenario Outline: Free refills
20 Given the season is <season>
21 When barry orders a <drink>
22 Then barry pays <price>
24 Examples:
25 | season | drink | price |
26 | summer | iced latte | 3 |
27 | winter | espresso | 2 |
29 Rule: Happy hour discounts apply
31 @happy-hour
32 Scenario: Discounted espresso between 16:00 and 17:00
33 Given the time is "16:30"
34 When barry orders an espresso
35 Then the receipt contains:
36 """
37 espresso 1.00
38 discount -1.00
39 """
40 And the price list looks like:
41 | drink | price |
42 | espresso | 1 |

neovim/sample_files/test.go

Added
new file mode 100644

+7 / −0 text lines

1package main
2
3import "fmt"
4
5func main() {
6 fmt.Println("hi")
7}

neovim/sample_files/test.java

Added
new file mode 100644

+5 / −0 text lines

1public class Test {
2 public static void main(String[] args) {
3 System.out.println("hi");
4 }
5}

neovim/sample_files/test.jsonc

Added
new file mode 100644

+4 / −0 text lines

1{
2 // jsonc comment
3 "a": 1
4}

neovim/sample_files/test.just

Added
new file mode 100644

+2 / −0 text lines

1default:
2 echo hi

neovim/sample_files/test.kdl

Modified

+1 / −1 text lines

1111 timeout 30
1212 }
14 tags ["alpha" "beta" "release"]
14 tags "alpha" "beta" "release"
1616 nested {
1717 key "value"

neovim/sample_files/test.lua

Added
new file mode 100644

+2 / −0 text lines

1local x = 1
2print(x)

neovim/sample_files/test.nu

Added
new file mode 100644

+2 / −0 text lines

1def main [] { print "hi" }
2main

neovim/sample_files/test.proto

Added
new file mode 100644

+5 / −0 text lines

1syntax = "proto3";
2
3message Test {
4 string name = 1;
5}

neovim/sample_files/test.py

Added
new file mode 100644

+2 / −0 text lines

1def main():
2 print("hi")

neovim/sample_files/test.rs

Added
new file mode 100644

+3 / −0 text lines

1fn main() {
2 println!("hi");
3}

neovim/sample_files/test.service

Added
new file mode 100644

+6 / −0 text lines

1[Unit]
2Description=Test unit
3
4[Service]
5ExecStart=/usr/bin/true
6Restart=on-failure

neovim/sample_files/test.sh

Added
new file mode 100644

+2 / −0 text lines

1#!/usr/bin/env sh
2echo hi

neovim/sample_files/test.tf

Added
new file mode 100644

+5 / −0 text lines

1resource "null_resource" "test" {
2 triggers = {
3 ok = "yes"
4 }
5}

neovim/sample_files/test.tofu

Added
new file mode 100644

+1 / −0 text lines

1resource "null_resource" "test" {}

neovim/sample_files/test.toml

Added
new file mode 100644

+3 / −0 text lines

1[tool]
2name = "test"
3version = "0.1.0"

neovim/sample_files/test.xml

Added
new file mode 100644

+4 / −0 text lines

1<?xml version="1.0"?>
2<root>
3 <item id="1">value</item>
4</root>

neovim/sample_files/test.zig

Added
new file mode 100644

+5 / −0 text lines

1const std = @import("std");
2pub fn main() void {
3 std.debug.print("hi
4", .{});
5}

neovim/spell/de.utf-8.add

Deleted
deleted file mode 100644

+0 / −3 text lines

1Enums
2Skripte
3startuptime

neovim/spell/de.utf-8.add.spl

Deleted
deleted file mode 100644

Binary size (old → new): 74 → 0 bytes.

neovim/spell/de.utf-8.spl

Deleted
deleted file mode 100644

Binary size (old → new): 570932 → 0 bytes.

neovim/spell/en.utf-8.add

Deleted
deleted file mode 100644

+0 / −1 text lines

neovim/spell/en.utf-8.add.spl

Deleted
deleted file mode 100644

Binary size (old → new): 41 → 0 bytes.

neovim/spell/nerd.utf-8.add

Deleted
deleted file mode 100644

+0 / −160 text lines

1bugabinga
2neovim
3lua
4api
5nugu
6ftplugin
7ai
8todo
9pandoc
10nushell
11ltex
12nvim
13github
14vimpreviewpandoc
15Shirou
16Emiya
17KKG
18isp
19insoft
20KKG5
21KKG6
22lspconfig
23neoconf
24lsp
25autopairs
26cterm/!
27navic
28winbar
29resession
30configs
31BufNewFile
32LuaLS
33editorconfig
34exrc
35localrc
36signcolumn
37togglers
38ripgrep
39prequire
40pcall
41args
42ipairs
43setmetatable
44colorscheme
45cmdline
46treesitter
47cmd
48popups
49neovide
50wezterm
51fullscreen
52checkhealth
53pls
54stylua
55eol
56kool
57grepprg
58makeprg
59modulepath
60FFI
61jdtls
62href
63DocumentUri
64sinnfrei
65Asciidoc
66AsciidocFX
67GraalVM
68Validierung
69JUnit4
70Nullability
71EclipseStore
72gRPC
73UUIDs
74FKs
75FIXMEs
76JSpecify
77aerc
78yazi
79magit
80gitu
81sk
82Bugabinga's
83inlyne
84mdcat
85nuon
86LSPs
87golang
88presenterm
89bartib
90rbwsearch
91Muratori
92dorkfile
93hx
94zellij
95difftastic
96weechat
97tarsnap
98mux
99icepuma
100traefik
101tclock
102sbyte
103httm
104handlr
105sd
106diskonaut
107mdsh
108ast-grep
109JavaDoc
110CiaoCiao
111EntwicklerQuiz
112Toolchain
113Rätselantworten
114minidlna
115systemd
116filetype
117Libcyber
118REPL
119Bézier
120Tailscale
121tailscale
122PopOs
123Mailinabox
124wluma
125stylix
126nixvim
127Krylow
128Entwicklerfrühstück
129Prozess
130NixOs
131thymeleaf
132htmx
133Präsi
134Produktlandschaft
135io
136Log4J2
137Vorhand
138Rückhandbelag
139Vorhandbelag
140Fastarc
141Nittaku
142Griffform
143Noppen
144Tibhar
145Kopfgröße
146Alfaview
147Sammelphase
148Susann
149Gruppenschulungen
150Teilnehmeranzahl
151Stundenkontingente
152Hinduismus
153Buddhismus
154Glaubensregeln
155oss
156jqwik
157vendored
158Testbarkeit
159Glossar
160subsidization

neovim/spell/nerd.utf-8.add.spl

Deleted
deleted file mode 100644

Binary size (old → new): 2368 → 0 bytes.

neovim/spell/nerd.utf-8.spl

Deleted
deleted file mode 100644

Binary size (old → new): 69071 → 0 bytes.