dotfiles
bugabingas dorkfiles
Compare 189752fd37bb7c3a8f77b320a6b9632f71c81d2b → HEAD
Changed files (1147)
+133277 / −32871 text lines · all files grouped into 32 bars · 2 metadata-only · 22 binary (striped old/new sizes in 64-byte units, not churn) · lines and sizes scale separately · double caps mark values above 4096 lines
Remaining file details omitted: diff output limit reached.
.gitattributes
Addednew file mode 100644+19 / −0 text lines
* text=auto eol=lf# BEGIN bootstripper secretsMusicBrainz/Picard.ini -text filter=dotfiles-aes -diff merge=dotfiles-aeszed/settings.json -text filter=dotfiles-aes -diff merge=dotfiles-aesssh/github.key -text filter=dotfiles-aes -diff merge=dotfiles-aesssh/box.bugabinga.net.key -text filter=dotfiles-aes -diff merge=dotfiles-aesssh/klops.key -text filter=dotfiles-aes -diff merge=dotfiles-aesssh/tini.key -text filter=dotfiles-aes -diff merge=dotfiles-aesssh/hetzner.key -text filter=dotfiles-aes -diff merge=dotfiles-aesssh/aur.key -text filter=dotfiles-aes -diff merge=dotfiles-aesssh/bugabinga.net.key -text filter=dotfiles-aes -diff merge=dotfiles-aesssh/code.isp-insoft.de -text filter=dotfiles-aes -diff merge=dotfiles-aesgh/hosts.yml -text filter=dotfiles-aes -diff merge=dotfiles-aesaerc/accounts.conf -text filter=dotfiles-aes -diff merge=dotfiles-aesbash/secrets.bash -text filter=dotfiles-aes -diff merge=dotfiles-aesnushell/secrets.nu -text filter=dotfiles-aes -diff merge=dotfiles-aespi/google-workspace/tokens/o.krylow%40isp-insoft.de.json -text filter=dotfiles-aes -diff merge=dotfiles-aes# END bootstripper secrets.gitignore
Modified+41 / −21 text lines
chawan/history.urissh/config.localfonts/# Quickshell LSP scratch/config generated by qs.**/.qmlls.ini.superpowers/# Generated/local app state**/target//pi/agent/install/pi/agent/binpi/agent/installpi/agent/models-store.jsonpi/agent/crashes.jsonpi/agent/mcp-auth.jsonpi/agent/overkill-runspi/agent/tmppi/agent/binyazi/plugins/MusicBrainz/.Picard.ini.synclock.gitleaks.toml
Addednew file mode 100644+10 / −0 text lines
[extend]useDefault = true[[allowlists]]description = "Public Git signing-key fingerprint in historical host configuration"condition = "AND"targetRules = ["generic-api-key"]regexTarget = "line"paths = ['''^git/\.gitconfig\.EJ-PC-00363$''']regexes = ['''(?i)^\s*singingkey\s*=\s*[0-9a-f]{40}\s*$'''].gitmodules
Deleteddeleted file mode 100644+0 / −8 text lines
.miserc.toml
Addednew file mode 100644+1 / −0 text lines
auto_env = true.pi/settings.json
Addednew file mode 100644+5 / −0 text lines
.secrets
Modified+3 / −0 text lines
.system/MISSION.md
Addednew file mode 100644+3 / −0 text lines
.system/RULES.md
Addednew file mode 100644+57 / −0 text lines
# RULES## StandardsZero warnings, isolated evidence, reviewed output. Rigor over velocity claims.## Repository- Run repo commands from the dotfiles root; nested project commands run from their project root.- Check `git status --short` before edits; preserve unrelated dirty work.- Never run privileged, root, or elevated commands.- Do not delete noisy research, cache, or untracked files unless explicitly asked.- Prefer repo paths (`pi/agent/...`) over `$HOME` paths.## Secrets- `.secrets` is plaintext and lists repo-relative paths to encrypt; the `dotfiles-aes` Git filter does the encryption.- New secret flow: 1. edit `.secrets` 2. `java bootstripper.java check` 3. `git add .secrets .gitattributes` 4. `git check-attr -a -- path/to/secret`- Required attrs: `filter: dotfiles-aes`, `text: unset`, `diff: unset`.- A `.secrets` path must not match any ignore rule; `check` fails otherwise because `git add -A` would silently skip it.- Never `git add -A` new secret-looking files before that flow.- 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`.- Never print decrypted secrets; never ask for or expose `DOTFILES_AES_PASSPHRASE` unless I explicitly initiate setup.- Secret paths include `ssh/*.key`, `gh/hosts.yml`, `pi/agent/auth.json`, `nushell/secrets.nu`, app private settings.## Git- `rebase.autostash` and `merge.autostash` stay `false`; `mise run check` asserts it. Dirty worktree: commit first, or stash explicitly and pop it yourself.- The `dotfiles-aes` filter and `pre-commit`/`pre-push` hooks can abort Git midway; never pass `--no-verify`.- Commits and pushes require `gitleaks` on Git's `PATH`; missing Gitleaks blocks the Git operation, not the worktree.## Symlinks- Manifest pairs stay ordered and complete; blank line between pairs.- Managed symlinks never point outside HOME; no `/usr`, no `/etc`. Outside-HOME symlinks are errors: do not relink or delete them.## Repo commandsSafe checks: `mise run check`, `mise run secrets-scan`.Heavy integration: `mise run ci` (needs host Podman).Crypto and hooks: `java bootstripper.java check | pre-commit | pre-push | install-hooks | init-crypto | setup-crypto`.HOME-mutating, only on explicit request: `mise run link`, `mise run clean`.`link` validates manifests, converges crypto idempotently, installs or repairs hooks, and creates symlinks; restoration refuses staged changes, deletions, symlinks, changed ciphertext, or mixed states.## Nested Systems- `quickshell/nuguland/.system/` governs the shell; its law applies there, not here.- Do not duplicate nested law in this System.## Docs- `.system/` cores and specs are agent authority; read RULES and the relevant spec before governed work.- READMEs are human overview; agent-only knowledge belongs in `.system/`..system/SYSTEM.md
Addednew file mode 100644+24 / −0 text lines
# SYSTEM## RepoDorkfiles. One Git repository, several machines.Host bootstrap assumes Git and mise; mise supplies Java; other tools come from the system package manager.`bootstripper.java` converges the Git filter, attributes, and hooks that keep secrets encrypted and commits gated.Symlink manifests are `repo/path` + `~/target/path` pairs; the hostname chooses `<host>.symlinks`.Nested Systems, each governing its own subtree:- `quickshell/nuguland/` — desktop shell, own System with `NL` IDs.- `neovim/` — own subtree; not yet initialized.Also in this repo:- `pi/agent/` — Pi settings, models, modes, skills; extension sources under `pi-ext/extensions/`.- Nugu palettes and themes — load the `nugu` skill before palette work.## Docs hierarchyThis System and RULES are repo authority below nested Systems.READMEs are human overview and carry no binding rules..system/board.json
Addednew file mode 100644+4 / −0 text lines
.system/config.json
Addednew file mode 100644+5 / −0 text lines
AGENTS.md
Deleteddeleted file mode 100644+0 / −36 text lines
# DotfilesDorkfiles repo.Preserve unrelated dirty work.Never print decrypted secrets.## Secrets`.secrets` is plaintext.It lists repo-relative paths to encrypt.Encryption comes from local Git filter `dotfiles-aes` via `.git/info/attributes`.`bootstripper` generates that file from `.secrets`.For a new secret:```sh$EDITOR .secretsjava bootstripper.java checkgit check-attr -a -- path/to/secret```Required attrs:```textfilter: dotfiles-aestext: unsetdiff: unset```Do not `git add -A` new secret-looking files before this.For private keys, verify staged content is not plaintext:```shgit cat-file -p :path/to/key | LC_ALL=C grep -q 'BEGIN .*PRIVATE KEY' && exit 1```ArchLinux-dev.symlinks
Addednew file mode 100644+89 / −0 text lines
pi~/.pidprint/dprint.jsonc~/.config/dprint/dprint.jsoncgit/gitconfig~/.config/git/configgit/gitattributes~/.config/git/gitattributesgit/allowed_signers~/.config/git/allowed_signersgit/gitconfig.isp~/.config/git/.gitconfig.includegh~/.config/ghcargo/config.toml~/.cargo/config.tomlbat/config~/.config/bat/configbash/bash_profile~/.bash_profilebash/bashrc~/.bashrcbash~/.config/bashtmux~/.config/tmuxnushell~/.config/nushelltopgrade/topgrade.toml~/.config/topgrade.tomltopgrade/wsl.toml~/.config/topgrade.d/wsl.tomlparu/paru.conf~/.config/paru/paru.confssh~/.sshneovim~/.config/nvimzed~/.config/zedghostty~/.config/ghosttyjj~/.config/jjglow~/.config/glowmise~/.config/miseclaude/settings.json~/.claude/settings.jsonclaude/statusline.js~/.claude/statusline.jsclaude/cc-statusline-hook.js~/.claude/cc-statusline-hook.jsclaude/CLAUDE.md~/.claude/CLAUDE.mdclaude/RTK.md~/.claude/RTK.mdcodex/config.toml~/.codex/config.tomlMangoHud/MangoHud.conf
Modified+6 / −24 text lines
MangoHud/presets.conf
Addednew file mode 100644+43 / −0 text lines
# Left Shift + F10 cycles Minimal -> Performance -> Diagnostic.# Minimal: FPS and numeric frame time.[preset 1]legacy_layout=0cpu_stats=0gpu_stats=0fpsframetime# Performance: load, temperatures, memory and frame pacing.[preset 2]legacy_layout=0gpu_statsgpu_tempvramcpu_statscpu_tempramprocmemfpsframetimeframe_timing# Diagnostic: Performance plus clocks, power and per-core load.[preset 3]legacy_layout=0gpu_statsgpu_tempgpu_core_clockgpu_mem_clockgpu_powervramcpu_statscpu_tempcpu_mhzcore_loadramprocmemfpsframetimeframe_timingengine_versionNB-00718.symlinks
Modified+107 / −71 text lines
forgejo-cli
~/AppData/Roaming/Cyborus/forgejo-cli/config
Notes
~/Notes
pi
~/.pi
wezterm
~/.config/wezterm
neovim
~/AppData/Local/nvim
nushell
~/AppData/Roaming/nushell
bat/config
~/AppData/Roaming/bat/config
bottom
~/AppData/Roaming/bottom
git/gitconfig
~/.config/git/config
git/gitattributes
~/.config/git/gitattributes
git/gitconfig.isp
~/.config/git/.gitconfig.include
gh
~/AppData/Roaming/GitHub CLI
cargo/config.toml
~/.cargo/config.toml
neovide
~/AppData/Roaming/neovide
zed
~/AppData/Roaming/zed
helix
~/AppData/Roaming/helix
jj/config.toml
~/AppData/Roaming/jj/config.toml
glow/glow.yml
~/AppData/Local/glow/Config/glow.yml
mise
~/.config/mise
ssh
~/.ssh
topgrade/topgrade.toml
~/AppData/Roaming/topgrade.toml
topgrade/win32.toml
~/AppData/Roaming/topgrade.d/win32.toml
mpv
~/AppData/Roaming/mpv
rbw
~/AppData/Roaming/rbw
forgejo-cli~/AppData/Roaming/Cyborus/forgejo-cli/configclaude/settings.json~/.claude/settings.jsonclaude/cc-statusline-hook.js~/.claude/cc-statusline-hook.jsclaude/statusline.js~/.claude/statusline.jsclaude/CLAUDE.md~/.claude/CLAUDE.mdclaude/RTK.md~/.claude/RTK.mdcodex/config.toml~/.codex/config.tomlpi~/.pidprint/dprint.jsonc~/AppData/Roaming/dprint/dprint.jsoncwezterm~/.config/weztermneovim~/AppData/Local/nvimnushell~/AppData/Roaming/nushellbat/config~/AppData/Roaming/bat/configbottom~/AppData/Roaming/bottomgit/gitconfig~/.config/git/configgit/gitattributes~/.config/git/gitattributesgit/allowed_signers~/.config/git/allowed_signersgit/gitconfig.isp~/.config/git/.gitconfig.includegh~/AppData/Roaming/GitHub CLIcargo/config.toml~/.cargo/config.tomlneovide~/AppData/Roaming/neovidezed~/AppData/Roaming/zedjj/config.toml~/AppData/Roaming/jj/config.tomlglow/glow.yml~/AppData/Local/glow/Config/glow.ymlyazi/windows/yazi.toml~/AppData/Roaming/yazi/config/yazi.tomlyazi/keymap.toml~/AppData/Roaming/yazi/config/keymap.tomlyazi/init.lua~/AppData/Roaming/yazi/config/init.luayazi/theme.toml~/AppData/Roaming/yazi/config/theme.tomlyazi/package.toml~/AppData/Roaming/yazi/config/package.tomlyazi/flavors~/AppData/Roaming/yazi/config/flavorsmise~/.config/misessh~/.sshtopgrade/topgrade.toml~/AppData/Roaming/topgrade.tomltopgrade/win32.toml~/AppData/Roaming/topgrade.d/win32.tomlmpv~/AppData/Roaming/mpvrbw~/AppData/Roaming/rbwNotes
Deleteddeleted file mode 160000Link change (old → new): 67f79b6f417e95cb9598b7783db4e3f873f36f69 → absent.
README.md
Modified+10 / −24 text lines
: config modules. in aggregation, defines all of the config. can depend on itself, std and plugins.* add fonts to dotfiles (how to keep size under control?)* write plugin to parse lsp settings locally and apply them* is there a use case for a plugin that parses local plugin configuration overrides?* kill custom lsp stuff in favor of lspconfig and try neoconf + nvim-java* does status bar fail to display if lsp fails to load?* pandoc with lua filters for diagrams for generating documents and previewing --> https://github.com/tex/vimpreviewpandoc* use gen.ai to generate docs* learn marks and refactor mark.lua* use ltex-ls for markdown, code comments and commit messages* create a floating window that shows plugins, that have commands, as reminder* setup DAP* add nu-check to nvim-lint* create facade over vim.api.nvim_create_user_command* create skeleton-plugin for default file content based on file type* add support for Java multi line string in autopairs* nvim spell for camel case wordsTODO.md
Addednew file mode 100644+1 / −0 text lines
- can we run on mise run link: git submodule update --init; switch to trunk? fast idempotetn?aerc/accounts.conf
Addednew file mode 100644Binary size (old → new): 0 → 886 bytes.
aerc/aerc.conf
Modified+746 / −751 text lines
#
# aerc main configuration
[general]
#
# Used as a default path for save operations if no other path is specified.
# ~ is expanded to the current user home dir.
#
default-save-path=~/Downloads
# If set to "gpg", aerc will use system gpg binary and keystore for all crypto
# operations. If set to "internal", the internal openpgp keyring will be used.
# If set to "auto", the system gpg will be preferred unless the internal
# keyring already exists, in which case the latter will be used.
#
# Default: auto
#pgp-provider=auto
# By default, the file permissions of accounts.conf must be restrictive and
# only allow reading by the file owner (0600). Set this option to true to
# ignore this permission check. Use this with care as it may expose your
# credentials.
#
# Default: false
#unsafe-accounts-conf=false
# Output log messages to specified file. A path starting with ~/ is expanded to
# the user home dir. When redirecting aerc's output to a file using > shell
# redirection, this setting is ignored and log messages are printed to stdout.
#
#log-file=
# Only log messages above the specified level to log-file. Supported levels
# are: trace, debug, info, warn and error. When redirecting aerc's output to
# a file using > shell redirection, this setting is ignored and the log level
# is forced to trace.
#
# Default: info
#log-level=info
# Set the $TERM environment variable used for the embedded terminal.
#
# Default: xterm-256color
#term=xterm-256color
# Display OSC8 strings in the embedded terminal
#
# Default: false
enable-osc8=true
# Default shell command to use for :menu. This will be executed with sh -c and
# will run in an popover dialog.
#
# Any occurrence of %f will be replaced by a temporary file path where the
# command is expected to write output lines to be consumed by :menu. Otherwise,
# the lines will be read from the command's standard output.
#
# Examples:
# default-menu-cmd=fzf
# default-menu-cmd=fzf --multi
# default-menu-cmd=dmenu -l 20
# default-menu-cmd=ranger --choosefiles=%f
#
default-menu-cmd=yazi --chooser-file %f
[ui]
#
# Describes the format for each row in a mailbox view. This is a comma
# separated list of column names with an optional align and width suffix. After
# the column name, one of the '<' (left), ':' (center) or '>' (right) alignment
# characters can be added (by default, left) followed by an optional width
# specifier. The width is either an integer representing a fixed number of
# characters, or a percentage between 1% and 99% representing a fraction of the
# terminal width. It can also be one of the '*' (auto) or '=' (fit) special
# width specifiers. Auto width columns will be equally attributed the remaining
# terminal width. Fit width columns take the width of their contents. If no
# width specifier is set, '*' is used by default.
#
# Default: date<20,name<17,flags>4,subject<*
index-columns=date<6,flags>4,name<24,subject<*
#
# Each name in index-columns must have a corresponding column-$name setting.
# All column-$name settings accept golang text/template syntax. See
# aerc-templates(7) for available template attributes and functions.
#
# Here are some examples to show the To field instead of the From field for
# an email (modifying column-name):
#
# 1. a generic one
# column-name={{ .Peer | names | join ", " }}
# 2. based upon the selected folder
# column-name={{if match .Folder "^(Gesendet|Sent)$"}}{{index (.To | names) 0}}{{else}}{{index (.From | names) 0}}{{end}}
#
# Default settings
#column-date={{.DateAutoFormat .Date.Local}}
#column-name={{index (.From | names) 0}}
#column-flags={{.Flags | join ""}}
#column-subject={{.ThreadPrefix}}{{if .ThreadFolded}}{{printf "{%d}" .ThreadCount}}{{end}}{{.Subject}}
#
# String separator inserted between columns. When the column width specifier is
# an exact number of characters, the separator is added to it (i.e. the exact
# width will be fully available for the column contents).
#
# Default: " "
#column-separator=" "
#
# See time.Time#Format at https://godoc.org/time#Time.Format
#
# Default: 2006-01-02 03:04 PM (ISO 8601 + 12 hour time)
#timestamp-format=2006-01-02 03:04 PM
timestamp-format=02.01.2006 03:04h
# FIXME it would be nice to have different formats for the viewer
#
# Index-only time format for messages that were received/sent today.
# If this is not specified, timestamp-format is used instead.
#
this-day-time-format=03:04h
#
# Index-only time format for messages that were received/sent within the last
# 7 days. If this is not specified, timestamp-format is used instead.
#
this-week-time-format=02.01
#
# Index-only time format for messages that were received/sent this year.
# If this is not specified, timestamp-format is used instead.
#
this-year-time-format=01.2006
#
# Width of the sidebar, including the border.
#
# Default: 20
sidebar-width=24
#
# Message to display when viewing an empty folder.
#
# Default: (no messages)
#empty-message=(no messages)
# Message to display when no folders exists or are all filtered
#
# Default: (no folders)
#empty-dirlist=(no folders)
#
# Value to set {{.Subject}} template to when subject is empty.
#
# Default: (no subject)
#empty-subject=(no subject)
# Enable mouse events in the ui, e.g. clicking and scrolling with the mousewheel
#
# Default: false
mouse-enabled=true
#
# Ring the bell when new messages are received
#
# Default: true
#new-message-bell=true
#
# Template to use for Account tab titles
#
# Default: {{.Account}}
#tab-title-account={{.Account}}
# Marker to show before a pinned tab's name.
#
# Default: `
#pinned-tab-marker='`'
# Template for the left side of the directory list.
# See aerc-templates(7) for all available fields and functions.
#
# Default: {{.Folder}}
dirlist-left={{.Folder}}{{if .Recent}} {{end}}
# Template for the right side of the directory list.
# See aerc-templates(7) for all available fields and functions.
#
# Default: {{if .Unread}}{{humanReadable .Unread}}/{{end}}{{if .Exists}}{{humanReadable .Exists}}{{end}}
#dirlist-right={{if .Unread}}{{humanReadable .Unread}}/{{end}}{{if .Exists}}{{humanReadable .Exists}}{{end}}
# Delay after which the messages are actually listed when entering a directory.
# This avoids loading messages when skipping over folders and makes the UI more
# responsive. If you do not want that, set it to 0s.
#
# Default: 200ms
dirlist-delay=100ms
# Display the directory list as a foldable tree that allows to collapse and
# expand the folders.
#
# Default: false
dirlist-tree=true
# If dirlist-tree is enabled, set level at which folders are collapsed by
# default. Set to 0 to disable.
#
# Default: 0
dirlist-collapse=3
# List of space-separated criteria to sort the messages by, see *sort*
# command in *aerc*(1) for reference. Prefixing a criterion with "-r "
# reverses that criterion.
#
# Example: "from -r date"
#
sort=-r date from
# Moves to next message when the current message is deleted
#
# Default: true
#next-message-on-delete=true
# Automatically set the "seen" flag when a message is opened in the message
# viewer.
#
# Default: true
#auto-mark-read=true
# The directories where the stylesets are stored. It takes a colon-separated
# list of directories. If this is unset or if a styleset cannot be found, the
# following paths will be used as a fallback in that order:
#
# ${XDG_CONFIG_HOME:-~/.config}/aerc/stylesets
# ${XDG_DATA_HOME:-~/.local/share}/aerc/stylesets
# /usr/local/share/aerc/stylesets
# /usr/share/aerc/stylesets
#
#stylesets-dirs=
# Uncomment to use box-drawing characters for vertical and horizontal borders.
#
# Default: " "
border-char-vertical="│"
border-char-horizontal="─"
# Sets the styleset to use for the aerc ui elements.
#
# Default: default
styleset-name=nugu-dark
# Activates fuzzy search in commands and their arguments: the typed string is
# searched in the command or option in any position, and need not be
# consecutive characters in the command or option.
#
# Default: false
fuzzy-complete=true
# How long to wait after the last input before auto-completion is triggered.
#
# Default: 250ms
#completion-delay=250ms
# The minimum required characters to allow auto-completion to be triggered after
# completion-delay.
#
# Setting this to "manual" disables automatic completion, leaving only the
# manually triggered completion with the $complete key (see aerc-binds(5) for
# more details).
#
# Default: 1
#completion-min-chars=1
#
# Global switch for completion popovers
#
# Default: true
#completion-popovers=true
# Uncomment to use UTF-8 symbols to indicate PGP status of messages
#
# Default: ASCII
icon-unencrypted=
icon-encrypted=✔
icon-signed=✔
icon-signed-encrypted=✔
icon-unknown=✘
icon-invalid=⚠
# Reverses the order of the message list. By default, the message list is
# ordered with the newest (highest UID) message on top. Reversing the order
# will put the oldest (lowest UID) message on top. This can be useful in cases
# where the backend does not support sorting.
#
# Default: false
#reverse-msglist-order = false
# Reverse display of the mesage threads. Default order is the the intial
# message is on the top with all the replies being displayed below. The
# reverse option will put the initial message at the bottom with the
# replies on top.
#
# Default: false
#reverse-thread-order=false
# Sort the thread siblings according to the sort criteria for the messages. If
# sort-thread-siblings is false, the thread siblings will be sorted based on
# the message UID in ascending order. This option is only applicable for
# client-side threading with a backend that enables sorting. Note that there's
# a performance impact when sorting is activated.
#
# Default: false
#sort-thread-siblings=false
[ui:account=oliver]
#
# Enable a threaded view of messages. If this is not supported by the backend
# (IMAP server or notmuch), threads will be built by the client.
#
# Default: false
threading-enabled=true
# Force client-side thread building
#
# Default: false
#force-client-threads=false
# Show thread context enables messages which do not match the current query (or
# belong to the current mailbox) to be shown for context. These messages can be
# styled separately using "msglist_thread_context" in a styleset. This feature
# is not supported by all backends
#
# Default: false
#show-thread-context=false
# Debounce client-side thread building
#
# Default: 50ms
#client-threads-delay=50ms
#
# Thread prefix customization:
#
# Customize the thread prefix appearance by selecting the arrow head.
#
# Default: ">"
#thread-prefix-tip = ">"
#
# Customize the thread prefix appearance by selecting the arrow indentation.
#
# Default: " "
#thread-prefix-indent = " "
#
# Customize the thread prefix appearance by selecting the vertical extension of
# the arrow.
#
# Default: "│"
#thread-prefix-stem = "│"
#
# Customize the thread prefix appearance by selecting the horizontal extension
# of the arrow.
#
# Default: ""
#thread-prefix-limb = ""
#
# Customize the thread prefix appearance by selecting the folded thread
# indicator.
#
# Default: ""
#thread-prefix-folded = ""
#
# Customize the thread prefix appearance by selecting the unfolded thread
# indicator.
#
# Default: ""
#thread-prefix-unfolded = ""
#
# Customize the thread prefix appearance by selecting the first child connector.
#
# Default: ""
#thread-prefix-first-child = ""
#
# Customize the thread prefix appearance by selecting the connector used if
# the message has siblings.
#
# Default: "├─"
#thread-prefix-has-siblings = "├─"
#
# Customize the thread prefix appearance by selecting the connector used if the
# message has no parents and no children.
#
# Default: ""
#thread-prefix-lone = ""
#
# Customize the thread prefix appearance by selecting the connector used if the
# message has no parents and has children.
#
# Default: ""
#thread-prefix-orphan = ""
#
# Customize the thread prefix appearance by selecting the connector for the last
# sibling.
#
# Default: "└─"
#thread-prefix-last-sibling = "└─"
#
# Customize the reversed thread prefix appearance by selecting the connector for
# the last sibling.
#
# Default: "┌─"
#thread-prefix-last-sibling-reverse = "┌─"
#
# Customize the reversed thread prefix appearance by selecting the first child
# connector.
#
# Default: ""
#thread-prefix-first-child-reverse = ""
#
# Customize the reversed thread prefix appearance by selecting the connector
# used if the message has no parents and has children.
#
# Default: ""
#thread-prefix-orphan-reverse = ""
[statusline]
#
# Describes the format for the status line. This is a comma separated list of
# column names with an optional align and width suffix. See [ui].index-columns
# for more details. To completely mute the status line except for push
# notifications, explicitly set status-columns to an empty string.
#
# Default: left<*,center:=,right>*
#status-columns=left<*,center:=,right>*
#
# Each name in status-columns must have a corresponding column-$name setting.
# All column-$name settings accept golang text/template syntax. See
# aerc-templates(7) for available template attributes and functions.
#
# Default settings
#column-left=[{{.Account}}] {{.StatusInfo}}
#column-center={{.PendingKeys}}
#column-right={{.TrayInfo}}
#
# String separator inserted between columns.
# See [ui].column-separator for more details.
#
#column-separator=" "
# Specifies the separator between grouped statusline elements.
#
# Default: " | "
#separator=" | "
# Defines the mode for displaying the status elements.
# Options: text, icon
#
# Default: text
#display-mode=text
[viewer]
#
# Specifies the pager to use when displaying emails. Note that some filters
# may add ANSI codes to add color to rendered emails, so you may want to use a
# pager which supports ANSI codes.
#
# Default: less -Rc
#pager=less -Rc
#
# If an email offers several versions (multipart), you can configure which
# mimetype to prefer. For example, this can be used to prefer plaintext over
# html emails.
#
# Default: text/plain,text/html
#alternatives=text/plain,text/html
#
# Default setting to determine whether to show full headers or only parsed
# ones in message viewer.
#
# Default: false
#show-headers=false
#
# Layout of headers when viewing a message. To display multiple headers in the
# same row, separate them with a pipe, e.g. "From|To". Rows will be hidden if
# none of their specified headers are present in the message.
#
# Default: From|To,Cc|Bcc,Date,Subject
#header-layout=From|To,Cc|Bcc,Date,Subject
# Whether to always show the mimetype of an email, even when it is just a single part
#
# Default: false
#always-show-mime=false
# Define the maximum height of the mimetype switcher before a scrollbar is used.
# The height of the mimetype switcher is restricted to half of the display
# height. If the provided value for the height is zero, the number of parts will
# be used as the height of the type switcher.
#
# Default: 0
#max-mime-height = 0
# Parses and extracts http links when viewing a message. Links can then be
# accessed with the open-link command.
#
# Default: true
#parse-http-links=true
[compose]
#
# Specifies the command to run the editor with. It will be shown in an embedded
# terminal, though it may also launch a graphical window if the environment
# supports it. Defaults to $EDITOR, or vi.
editor=nvim
#
# When set, aerc will create and read .eml files for composing that have
# non-standard \n linebreaks. This is only relevant if the used editor does not
# support CRLF linebreaks.
#
#lf-editor=false
#
# Default header fields to display when composing a message. To display
# multiple headers in the same row, separate them with a pipe, e.g. "To|From".
#
# Default: To|From,Subject
#header-layout=To|From,Subject
#
# Edit headers into the text editor instead than separate fields.
#
# When this is true, address-book-cmd is not supported and address completion
# is left to the editor itself. Also, displaying multiple headers on the same
# line is not possible.
#
# Default: false
#edit-headers=false
#
# Specifies the command to be used to tab-complete email addresses. Any
# occurrence of "%s" in the address-book-cmd will be replaced with what the
# user has typed so far.
#
# The command must output the completions to standard output, one completion
# per line. Each line must be tab-delimited, with an email address occurring as
# the first field. Only the email address field is required. The second field,
# if present, will be treated as the contact name. Additional fields are
# ignored.
#
# This parameter can also be set per account in accounts.conf.
#address-book-cmd=
# Specifies the command to be used to select attachments. Any occurrence of
# '%s' in the file-picker-cmd will be replaced with the argument <arg>
# to :attach -m <arg>. Any occurence of '%f' will be replaced by the
# location of a temporary file, from which aerc will read the selected files.
#
# If '%f' is not present, the command must output the selected files to
# standard output, one file per line. If it is present, then aerc does not
# capture the standard output and instead reads the files from the temporary
# file which should have the same format.
file-picker-cmd=yazi --chooser-file %f
#
# Allow to address yourself when replying
#
# Default: true
#reply-to-self=true
# Warn before sending an email with an empty subject.
#
# Default: false
empty-subject-warning=true
#
# Warn before sending an email that matches the specified regexp but does not
# have any attachments. Leave empty to disable this feature.
#
# Uses Go's regexp syntax, documented at https://golang.org/s/re2syntax. The
# "(?im)" flags are set by default (case-insensitive and multi-line).
#
# Example:
# no-attachment-warning=^[^>]*attach(ed|ment)
#
no-attachment-warning=^[^>]*(attach|attached|attachment|anhang)
#
# When set, aerc will generate "format=flowed" bodies with a content type of
# "text/plain; format=flowed" as described in RFC3676. This format is easier to
# handle for some mailing software, and generally just looks like ordinary
# text. To actually make use of this format's features, you'll need support in
# your editor.
#
format-flowed=true
[multipart-converters]
#
# Converters allow to generate multipart/alternative messages by converting the
# main text/plain part into any other MIME type. Only exact MIME types are
# accepted. The commands are invoked with sh -c and are expected to output
# valid UTF-8 text.
#
# Example (obviously, this requires that you write your main text/plain body
# using the markdown syntax):
#text/html=pandoc -f markdown -t html --standalone
[filters]
#
# Filters allow you to pipe an email body through a shell command to render
# certain emails differently, e.g. highlighting them with ANSI escape codes.
#
# The commands are invoked with sh -c. The following folders are prepended to
# the system $PATH to allow referencing filters from their name only:
#
# ${XDG_CONFIG_HOME:-~/.config}/aerc/filters
# ~/.local/libexec/aerc/filters
# ${XDG_DATA_HOME:-~/.local/share}/aerc/filters
# $PREFIX/libexec/aerc/filters
# $PREFIX/share/aerc/filters
# /usr/libexec/aerc/filters
# /usr/share/aerc/filters
#
# If you want to run a program in your default $PATH which has the same name
# as a builtin filter (e.g. /usr/bin/colorize), use its absolute path.
#
# The following variables are defined in the filter command environment:
#
# AERC_MIME_TYPE the part MIME type/subtype
# AERC_FORMAT the part content type format= parameter
# AERC_FILENAME the attachment filename (if any)
# AERC_SUBJECT the message Subject header value
# AERC_FROM the message From header value
#
# The first filter which matches the email's mimetype will be used, so order
# them from most to least specific.
#
# You can also match on non-mimetypes, by prefixing with the header to match
# against (non-case-sensitive) and a comma, e.g. subject,text will match a
# subject which contains "text". Use header,~regex to match against a regex.
#
text/plain=colorize
text/calendar=calendar
message/delivery-status=colorize
message/rfc822=colorize
text/html=pandoc -f html -t plain | colorize
#text/html=html | colorize
#text/*=bat -fP --file-name="$AERC_FILENAME"
#application/x-sh=bat -fP -l sh
image/*=wezterm imgcat --width $(tput cols)
#subject,~Git(hub|lab)=lolcat -f
#from,thatguywhodoesnothardwraphismessages=wrap -w 100 | colorize
# This special filter is only used to post-process email headers when
# [viewer].show-headers=true
# By default, headers are piped directly into the pager.
#
.headers=colorize
[openers]
#
# Openers allow you to specify the command to use for the :open and :open-link
# actions on a per-MIME-type basis. The :open-link URL scheme is used to
# determine the MIME type as follows: x-scheme-handler/<scheme>.
#
# {} is expanded as the temporary filename or URL to be opened with proper
# shell quoting. If it is not encountered in the command, the filename/URL will
# be appended to the end of the command. The command will then be executed with
# `sh -c`.
#
# Like [filters], openers support basic shell globbing. The first opener which
# matches the part's MIME type (or URL scheme handler MIME type) will be used,
# so order them from most to least specific.
#
# Examples:
x-scheme-handler/irc=weechat
# x-scheme-handler/http*=printf '%s' {} | wl-copy
# text/html=surf -dfgms
# text/plain=gvim {} +125
# message/rfc822=thunderbird
[hooks]
#
# Hooks are triggered whenever the associated event occurs.
#
# Executed when a new email arrives in the selected folder
mail-received=notify-send "📫 [$AERC_ACCOUNT/$AERC_FOLDER] New mail from $AERC_FROM_NAME" "$AERC_SUBJECT"
#
# Executed when mail is deleted from a folder
#mail-deleted=mbsync "$AERC_ACCOUNT:$AERC_FOLDER" &
#
# Executed when aerc adds mail to a folder
#mail-added=mbsync "$AERC_ACCOUNT:$AERC_FOLDER" &
#
# Executed when aerc starts
#aerc-startup=aerc :terminal calcurse && aerc :next-tab
#
# Executed when aerc shuts down.
#aerc-shutdown=
[templates]
# Templates are used to populate email bodies automatically.
#
# The directories where the templates are stored. It takes a colon-separated
# list of directories. If this is unset or if a template cannot be found, the
# following paths will be used as a fallback in that order:
#
# ${XDG_CONFIG_HOME:-~/.config}/aerc/templates
# ${XDG_DATA_HOME:-~/.local/share}/aerc/templates
# /usr/local/share/aerc/templates
# /usr/share/aerc/templates
#
#template-dirs=
# The default template to be used for new messages.
#
# default: new_message
#new-message=new_message
# The default template to be used for quoted replies.
#
# default: quoted_reply
#quoted-reply=quoted_reply
# The default template to be used for forward as body.
#
# default: forward_as_body
#forwards=forward_as_body
## aerc main configuration[general]## Used as a default path for save operations if no other path is specified.# ~ is expanded to the current user home dir.#default-save-path=~/Downloads# If set to "gpg", aerc will use system gpg binary and keystore for all crypto# operations. If set to "internal", the internal openpgp keyring will be used.# If set to "auto", the system gpg will be preferred unless the internal# keyring already exists, in which case the latter will be used.## Default: auto#pgp-provider=auto# By default, the file permissions of accounts.conf must be restrictive and# only allow reading by the file owner (0600). Set this option to true to# ignore this permission check. Use this with care as it may expose your# credentials.## Default: false#unsafe-accounts-conf=false# Output log messages to specified file. A path starting with ~/ is expanded to# the user home dir. When redirecting aerc's output to a file using > shell# redirection, this setting is ignored and log messages are printed to stdout.##log-file=# Only log messages above the specified level to log-file. Supported levels# are: trace, debug, info, warn and error. When redirecting aerc's output to# a file using > shell redirection, this setting is ignored and the log level# is forced to trace.## Default: info#log-level=info# Set the $TERM environment variable used for the embedded terminal.## Default: xterm-256color#term=xterm-256color# Default shell command to use for :menu. This will be executed with sh -c and# will run in an popover dialog.## Any occurrence of %f will be replaced by a temporary file path where the# command is expected to write output lines to be consumed by :menu. Otherwise,# the lines will be read from the command's standard output.## Examples:# default-menu-cmd=fzf# default-menu-cmd=fzf --multi# default-menu-cmd=dmenu -l 20# default-menu-cmd=ranger --choosefiles=%f#default-menu-cmd=yazi --chooser-file %f[ui]## Describes the format for each row in a mailbox view. This is a comma# separated list of column names with an optional align and width suffix. After# the column name, one of the '<' (left), ':' (center) or '>' (right) alignment# characters can be added (by default, left) followed by an optional width# specifier. The width is either an integer representing a fixed number of# characters, or a percentage between 1% and 99% representing a fraction of the# terminal width. It can also be one of the '*' (auto) or '=' (fit) special# width specifiers. Auto width columns will be equally attributed the remaining# terminal width. Fit width columns take the width of their contents. If no# width specifier is set, '*' is used by default.## Default: date<20,name<17,flags>4,subject<*index-columns=date<6,flags>4,name<24,subject<*## Each name in index-columns must have a corresponding column-$name setting.# All column-$name settings accept golang text/template syntax. See# aerc-templates(7) for available template attributes and functions.## Here are some examples to show the To field instead of the From field for# an email (modifying column-name):## 1. a generic one# column-name={{ .Peer | names | join ", " }}# 2. based upon the selected folder# column-name={{if match .Folder "^(Gesendet|Sent)$"}}{{index (.To | names) 0}}{{else}}{{index (.From | names) 0}}{{end}}## Default settings#column-date={{.DateAutoFormat .Date.Local}}#column-name={{index (.From | names) 0}}#column-flags={{.Flags | join ""}}#column-subject={{.ThreadPrefix}}{{if .ThreadFolded}}{{printf "{%d}" .ThreadCount}}{{end}}{{.Subject}}## String separator inserted between columns. When the column width specifier is# an exact number of characters, the separator is added to it (i.e. the exact# width will be fully available for the column contents).## Default: " "column-separator=" 𝄀"## See time.Time#Format at https://godoc.org/time#Time.Format## Default: 2006-01-02 03:04 PM (ISO 8601 + 12 hour time)#timestamp-format=2006-01-02 03:04 PMtimestamp-format=02.01.2006 03:04h# FIXME it would be nice to have different formats for the viewer## Index-only time format for messages that were received/sent today.# If this is not specified, timestamp-format is used instead.#this-day-time-format=03:04h## Index-only time format for messages that were received/sent within the last# 7 days. If this is not specified, timestamp-format is used instead.#this-week-time-format=02.01## Index-only time format for messages that were received/sent this year.# If this is not specified, timestamp-format is used instead.#this-year-time-format=01.2006## Width of the sidebar, including the border.## Default: 20sidebar-width=24## Message to display when viewing an empty folder.## Default: (no messages)#empty-message=(no messages)# Message to display when no folders exists or are all filtered## Default: (no folders)#empty-dirlist=(no folders)## Value to set {{.Subject}} template to when subject is empty.## Default: (no subject)#empty-subject=(no subject)# Enable mouse events in the ui, e.g. clicking and scrolling with the mousewheel## Default: falsemouse-enabled=true## Ring the bell when new messages are received## Default: true#new-message-bell=true## Template to use for Account tab titles## Default: {{.Account}}#tab-title-account={{.Account}}# Marker to show before a pinned tab's name.## Default: `#pinned-tab-marker='`'# Template for the left side of the directory list.# See aerc-templates(7) for all available fields and functions.## Default: {{.Folder}}dirlist-left={{.Folder}}{{if .Recent}} {{end}}# Template for the right side of the directory list.# See aerc-templates(7) for all available fields and functions.## Default: {{if .Unread}}{{humanReadable .Unread}}/{{end}}{{if .Exists}}{{humanReadable .Exists}}{{end}}#dirlist-right={{if .Unread}}{{humanReadable .Unread}}/{{end}}{{if .Exists}}{{humanReadable .Exists}}{{end}}# Delay after which the messages are actually listed when entering a directory.# This avoids loading messages when skipping over folders and makes the UI more# responsive. If you do not want that, set it to 0s.## Default: 200msdirlist-delay=100ms# Display the directory list as a foldable tree that allows to collapse and# expand the folders.## Default: falsedirlist-tree=true# If dirlist-tree is enabled, set level at which folders are collapsed by# default. Set to 0 to disable.## Default: 0dirlist-collapse=3# List of space-separated criteria to sort the messages by, see *sort*# command in *aerc*(1) for reference. Prefixing a criterion with "-r "# reverses that criterion.## Example: "from -r date"#sort=-r date from# Moves to next message when the current message is deleted## Default: true#next-message-on-delete=true# Automatically set the "seen" flag when a message is opened in the message# viewer.## Default: true#auto-mark-read=true# The directories where the stylesets are stored. It takes a colon-separated# list of directories. If this is unset or if a styleset cannot be found, the# following paths will be used as a fallback in that order:## ${XDG_CONFIG_HOME:-~/.config}/aerc/stylesets# ${XDG_DATA_HOME:-~/.local/share}/aerc/stylesets# /usr/local/share/aerc/stylesets# /usr/share/aerc/stylesets#stylesets-dirs=~/.nugu-runtime/aerc# Uncomment to use box-drawing characters for vertical and horizontal borders.## Default: " "border-char-vertical="│"border-char-horizontal="─"# Sets the styleset to use for the aerc ui elements.## Default: defaultstyleset-name=nugu# Activates fuzzy search in commands and their arguments: the typed string is# searched in the command or option in any position, and need not be# consecutive characters in the command or option.## Default: falsefuzzy-complete=true# How long to wait after the last input before auto-completion is triggered.## Default: 250ms#completion-delay=250ms# The minimum required characters to allow auto-completion to be triggered after# completion-delay.## Setting this to "manual" disables automatic completion, leaving only the# manually triggered completion with the $complete key (see aerc-binds(5) for# more details).## Default: 1#completion-min-chars=1## Global switch for completion popovers## Default: true#completion-popovers=true# Uncomment to use UTF-8 symbols to indicate PGP status of messages## Default: ASCIIicon-unencrypted=icon-encrypted=✔icon-signed=✔icon-signed-encrypted=✔icon-unknown=✘icon-invalid=⚠# Reverses the order of the message list. By default, the message list is# ordered with the newest (highest UID) message on top. Reversing the order# will put the oldest (lowest UID) message on top. This can be useful in cases# where the backend does not support sorting.## Default: false#reverse-msglist-order = false# Reverse display of the mesage threads. Default order is the the intial# message is on the top with all the replies being displayed below. The# reverse option will put the initial message at the bottom with the# replies on top.## Default: false#reverse-thread-order=false# Sort the thread siblings according to the sort criteria for the messages. If# sort-thread-siblings is false, the thread siblings will be sorted based on# the message UID in ascending order. This option is only applicable for# client-side threading with a backend that enables sorting. Note that there's# a performance impact when sorting is activated.## Default: false#sort-thread-siblings=false[ui:account=oliver]## Enable a threaded view of messages. If this is not supported by the backend# (IMAP server or notmuch), threads will be built by the client.## Default: falsethreading-enabled=true# Force client-side thread building## Default: false#force-client-threads=false# Show thread context enables messages which do not match the current query (or# belong to the current mailbox) to be shown for context. These messages can be# styled separately using "msglist_thread_context" in a styleset. This feature# is not supported by all backends## Default: false#show-thread-context=false# Debounce client-side thread building## Default: 50ms#client-threads-delay=50ms## Thread prefix customization:## Customize the thread prefix appearance by selecting the arrow head.## Default: ">"#thread-prefix-tip = ">"## Customize the thread prefix appearance by selecting the arrow indentation.## Default: " "#thread-prefix-indent = " "## Customize the thread prefix appearance by selecting the vertical extension of# the arrow.## Default: "│"#thread-prefix-stem = "│"## Customize the thread prefix appearance by selecting the horizontal extension# of the arrow.## Default: ""#thread-prefix-limb = ""## Customize the thread prefix appearance by selecting the folded thread# indicator.## Default: ""#thread-prefix-folded = ""## Customize the thread prefix appearance by selecting the unfolded thread# indicator.## Default: ""#thread-prefix-unfolded = ""## Customize the thread prefix appearance by selecting the first child connector.## Default: ""#thread-prefix-first-child = ""## Customize the thread prefix appearance by selecting the connector used if# the message has siblings.## Default: "├─"#thread-prefix-has-siblings = "├─"## Customize the thread prefix appearance by selecting the connector used if the# message has no parents and no children.## Default: ""#thread-prefix-lone = ""## Customize the thread prefix appearance by selecting the connector used if the# message has no parents and has children.## Default: ""#thread-prefix-orphan = ""## Customize the thread prefix appearance by selecting the connector for the last# sibling.## Default: "└─"#thread-prefix-last-sibling = "└─"## Customize the reversed thread prefix appearance by selecting the connector for# the last sibling.## Default: "┌─"#thread-prefix-last-sibling-reverse = "┌─"## Customize the reversed thread prefix appearance by selecting the first child# connector.## Default: ""#thread-prefix-first-child-reverse = ""## Customize the reversed thread prefix appearance by selecting the connector# used if the message has no parents and has children.## Default: ""#thread-prefix-orphan-reverse = ""[statusline]## Describes the format for the status line. This is a comma separated list of# column names with an optional align and width suffix. See [ui].index-columns# for more details. To completely mute the status line except for push# notifications, explicitly set status-columns to an empty string.## Default: left<*,center:=,right>*#status-columns=left<*,center:=,right>*## Each name in status-columns must have a corresponding column-$name setting.# All column-$name settings accept golang text/template syntax. See# aerc-templates(7) for available template attributes and functions.## Default settings#column-left=[{{.Account}}] {{.StatusInfo}}#column-center={{.PendingKeys}}#column-right={{.TrayInfo}}## String separator inserted between columns.# See [ui].column-separator for more details.##column-separator=" "# Specifies the separator between grouped statusline elements.## Default: " | "#separator=" | "# Defines the mode for displaying the status elements.# Options: text, icon## Default: text#display-mode=text[viewer]## Specifies the pager to use when displaying emails. Note that some filters# may add ANSI codes to add color to rendered emails, so you may want to use a# pager which supports ANSI codes.## Default: less -Rc#pager=less -Rc## If an email offers several versions (multipart), you can configure which# mimetype to prefer. For example, this can be used to prefer plaintext over# html emails.## Default: text/plain,text/html#alternatives=text/plain,text/html## Default setting to determine whether to show full headers or only parsed# ones in message viewer.## Default: false#show-headers=false## Layout of headers when viewing a message. To display multiple headers in the# same row, separate them with a pipe, e.g. "From|To". Rows will be hidden if# none of their specified headers are present in the message.## Default: From|To,Cc|Bcc,Date,Subject#header-layout=From|To,Cc|Bcc,Date,Subject# Whether to always show the mimetype of an email, even when it is just a single part## Default: false#always-show-mime=false# Define the maximum height of the mimetype switcher before a scrollbar is used.# The height of the mimetype switcher is restricted to half of the display# height. If the provided value for the height is zero, the number of parts will# be used as the height of the type switcher.## Default: 0#max-mime-height = 0# Parses and extracts http links when viewing a message. Links can then be# accessed with the open-link command.## Default: true#parse-http-links=true[compose]## Specifies the command to run the editor with. It will be shown in an embedded# terminal, though it may also launch a graphical window if the environment# supports it. Defaults to $EDITOR, or vi.editor=nvim## When set, aerc will create and read .eml files for composing that have# non-standard \n linebreaks. This is only relevant if the used editor does not# support CRLF linebreaks.##lf-editor=false## Default header fields to display when composing a message. To display# multiple headers in the same row, separate them with a pipe, e.g. "To|From".## Default: To|From,Subject#header-layout=To|From,Subject## Edit headers into the text editor instead than separate fields.## When this is true, address-book-cmd is not supported and address completion# is left to the editor itself. Also, displaying multiple headers on the same# line is not possible.## Default: false#edit-headers=false## Specifies the command to be used to tab-complete email addresses. Any# occurrence of "%s" in the address-book-cmd will be replaced with what the# user has typed so far.## The command must output the completions to standard output, one completion# per line. Each line must be tab-delimited, with an email address occurring as# the first field. Only the email address field is required. The second field,# if present, will be treated as the contact name. Additional fields are# ignored.## This parameter can also be set per account in accounts.conf.#address-book-cmd=# Specifies the command to be used to select attachments. Any occurrence of# '%s' in the file-picker-cmd will be replaced with the argument <arg># to :attach -m <arg>. Any occurence of '%f' will be replaced by the# location of a temporary file, from which aerc will read the selected files.## If '%f' is not present, the command must output the selected files to# standard output, one file per line. If it is present, then aerc does not# capture the standard output and instead reads the files from the temporary# file which should have the same format.file-picker-cmd=yazi --chooser-file %f## Allow to address yourself when replying## Default: true#reply-to-self=true# Warn before sending an email with an empty subject.## Default: falseempty-subject-warning=true## Warn before sending an email that matches the specified regexp but does not# have any attachments. Leave empty to disable this feature.## Uses Go's regexp syntax, documented at https://golang.org/s/re2syntax. The# "(?im)" flags are set by default (case-insensitive and multi-line).## Example:# no-attachment-warning=^[^>]*attach(ed|ment)#no-attachment-warning=^[^>]*(attach|attached|attachment|anhang)## When set, aerc will generate "format=flowed" bodies with a content type of# "text/plain; format=flowed" as described in RFC3676. This format is easier to# handle for some mailing software, and generally just looks like ordinary# text. To actually make use of this format's features, you'll need support in# your editor.#format-flowed=true[multipart-converters]## Converters allow to generate multipart/alternative messages by converting the# main text/plain part into any other MIME type. Only exact MIME types are# accepted. The commands are invoked with sh -c and are expected to output# valid UTF-8 text.## Example (obviously, this requires that you write your main text/plain body# using the markdown syntax):#text/html=pandoc -f markdown -t html --standalone[filters]## Filters allow you to pipe an email body through a shell command to render# certain emails differently, e.g. highlighting them with ANSI escape codes.## The commands are invoked with sh -c. The following folders are prepended to# the system $PATH to allow referencing filters from their name only:## ${XDG_CONFIG_HOME:-~/.config}/aerc/filters# ~/.local/libexec/aerc/filters# ${XDG_DATA_HOME:-~/.local/share}/aerc/filters# $PREFIX/libexec/aerc/filters# $PREFIX/share/aerc/filters# /usr/libexec/aerc/filters# /usr/share/aerc/filters## If you want to run a program in your default $PATH which has the same name# as a builtin filter (e.g. /usr/bin/colorize), use its absolute path.## The following variables are defined in the filter command environment:## AERC_MIME_TYPE the part MIME type/subtype# AERC_FORMAT the part content type format= parameter# AERC_FILENAME the attachment filename (if any)# AERC_SUBJECT the message Subject header value# AERC_FROM the message From header value## The first filter which matches the email's mimetype will be used, so order# them from most to least specific.## You can also match on non-mimetypes, by prefixing with the header to match# against (non-case-sensitive) and a comma, e.g. subject,text will match a# subject which contains "text". Use header,~regex to match against a regex.#text/plain=colorizetext/calendar=calendarmessage/delivery-status=colorizemessage/rfc822=colorizetext/html=pandoc -f html -t plain | colorize#text/html=html | colorize#text/*=bat -fP --file-name="$AERC_FILENAME"#application/x-sh=bat -fP -l shimage/*=wezterm imgcat --width $(tput cols)#subject,~Git(hub|lab)=lolcat -f#from,thatguywhodoesnothardwraphismessages=wrap -w 100 | colorize# This special filter is only used to post-process email headers when# [viewer].show-headers=true# By default, headers are piped directly into the pager.#.headers=colorize[openers]## Openers allow you to specify the command to use for the :open and :open-link# actions on a per-MIME-type basis. The :open-link URL scheme is used to# determine the MIME type as follows: x-scheme-handler/<scheme>.## {} is expanded as the temporary filename or URL to be opened with proper# shell quoting. If it is not encountered in the command, the filename/URL will# be appended to the end of the command. The command will then be executed with# `sh -c`.## Like [filters], openers support basic shell globbing. The first opener which# matches the part's MIME type (or URL scheme handler MIME type) will be used,# so order them from most to least specific.## Examples:x-scheme-handler/irc=weechat# x-scheme-handler/http*=printf '%s' {} | wl-copy# text/html=surf -dfgms# text/plain=gvim {} +125# message/rfc822=thunderbird[hooks]## Hooks are triggered whenever the associated event occurs.## Executed when a new email arrives in the selected foldermail-received=notify-send "📫 [$AERC_ACCOUNT/$AERC_FOLDER] New mail from $AERC_FROM_NAME" "$AERC_SUBJECT"## Executed when mail is deleted from a folder#mail-deleted=mbsync "$AERC_ACCOUNT:$AERC_FOLDER" &## Executed when aerc adds mail to a folder#mail-added=mbsync "$AERC_ACCOUNT:$AERC_FOLDER" &## Executed when aerc starts#aerc-startup=aerc :terminal calcurse && aerc :next-tab## Executed when aerc shuts down.#aerc-shutdown=[templates]# Templates are used to populate email bodies automatically.## The directories where the templates are stored. It takes a colon-separated# list of directories. If this is unset or if a template cannot be found, the# following paths will be used as a fallback in that order:## ${XDG_CONFIG_HOME:-~/.config}/aerc/templates# ${XDG_DATA_HOME:-~/.local/share}/aerc/templates# /usr/local/share/aerc/templates# /usr/share/aerc/templates##template-dirs=# The default template to be used for new messages.## default: new_message#new-message=new_message# The default template to be used for quoted replies.## default: quoted_reply#quoted-reply=quoted_reply# The default template to be used for forward as body.## default: forward_as_body#forwards=forward_as_bodyaerc/binds.conf
Modified+180 / −180 text lines
# Binds are of the form <key sequence> = <command to run>
# To use '=' in a key sequence, substitute it with "Eq": "<Ctrl+Eq>"
# If you wish to bind #, you can wrap the key sequence in quotes: "#" = quit
<C-p> = :prev-tab<Enter>
<C-PgUp> = :prev-tab<Enter>
<C-n> = :next-tab<Enter>
<C-PgDn> = :next-tab<Enter>
\[t = :prev-tab<Enter>
\]t = :next-tab<Enter>
<C-t> = :term<Enter>
? = :help keys<Enter>
<C-c> = :prompt 'Quit?' quit<Enter>
<C-q> = :prompt 'Quit?' quit<Enter>
<C-z> = :suspend<Enter>
[messages]
q = :prompt 'Quit?' quit<Enter>
j = :next<Enter>
<Down> = :next<Enter>
<C-d> = :next 50%<Enter>
<C-f> = :next 100%<Enter>
<PgDn> = :next 100%<Enter>
k = :prev<Enter>
<Up> = :prev<Enter>
<C-u> = :prev 50%<Enter>
<C-b> = :prev 100%<Enter>
<PgUp> = :prev 100%<Enter>
g = :select 0<Enter>
G = :select -1<Enter>
J = :next-folder<Enter>
<C-Down> = :next-folder<Enter>
K = :prev-folder<Enter>
<C-Up> = :prev-folder<Enter>
H = :collapse-folder<Enter>
<C-Left> = :collapse-folder<Enter>
L = :expand-folder<Enter>
<C-Right> = :expand-folder<Enter>
v = :mark -t<Enter>
<Space> = :mark -t<Enter>:next<Enter>
V = :mark -v<Enter>
T = :toggle-threads<Enter>
zc = :fold<Enter>
zo = :unfold<Enter>
za = :fold -t<Enter>
zM = :fold -a<Enter>
zR = :unfold -a<Enter>
<tab> = :fold -t<Enter>
<Enter> = :view<Enter>
d = :prompt 'Really delete this message?' 'delete-message'<Enter>
D = :delete<Enter>
a = :archive flat<Enter>
A = :unmark -a<Enter>:mark -T<Enter>:archive flat<Enter>
C = :compose<Enter>
m = :compose<Enter>
rr = :reply -a<Enter>
rq = :reply -aq<Enter>
Rr = :reply<Enter>
Rq = :reply -q<Enter>
c = :cf<space>
$ = :term<space>
! = :term<space>
| = :pipe<space>
/ = :search<space>
\ = :filter<space>
n = :next-result<Enter>
N = :prev-result<Enter>
<Esc> = :clear<Enter>
s = :split<Enter>
S = :vsplit<Enter>
pl = :patch list<Enter>
pa = :patch apply <Tab>
pd = :patch drop <Tab>
pb = :patch rebase<Enter>
pt = :patch term<Enter>
ps = :patch switch <Tab>
[messages:folder=Drafts]
<Enter> = :recall<Enter>
[view]
/ = :toggle-key-passthrough<Enter>/
q = :close<Enter>
O = :open<Enter>
o = :open<Enter>
E = :pipe -p nvim -R -n -c 'setlocal ft=mail nomodifiable' -<Enter>
S = :save<space>
Y = :pipe -pb ~/.config/aerc/copy-to-clipboard current-part<Enter>
M = :pipe -mb ~/.config/aerc/copy-to-clipboard full-message<Enter>
| = :pipe<space>
D = :delete<Enter>
A = :archive flat<Enter>
<C-l> = :open-link <space>
f = :forward<Enter>
rr = :reply -a<Enter>
rq = :reply -aq<Enter>
Rr = :reply<Enter>
Rq = :reply -q<Enter>
H = :toggle-headers<Enter>
<C-k> = :prev-part<Enter>
<C-Up> = :prev-part<Enter>
<C-j> = :next-part<Enter>
<C-Down> = :next-part<Enter>
J = :next<Enter>
<C-Right> = :next<Enter>
K = :prev<Enter>
<C-Left> = :prev<Enter>
[view::passthrough]
$noinherit = true
$ex = <C-x>
<Esc> = :toggle-key-passthrough<Enter>
[compose]
# Keybindings used when the embedded terminal is not selected in the compose
# view
$noinherit = true
$ex = <C-x>
$complete = <C-o>
<C-k> = :prev-field<Enter>
<C-Up> = :prev-field<Enter>
<C-j> = :next-field<Enter>
<C-Down> = :next-field<Enter>
<A-p> = :switch-account -p<Enter>
<C-Left> = :switch-account -p<Enter>
<A-n> = :switch-account -n<Enter>
<C-Right> = :switch-account -n<Enter>
<tab> = :next-field<Enter>
<backtab> = :prev-field<Enter>
<C-p> = :prev-tab<Enter>
<C-PgUp> = :prev-tab<Enter>
<C-n> = :next-tab<Enter>
<C-PgDn> = :next-tab<Enter>
[compose::editor]
# Keybindings used when the embedded terminal is selected in the compose view
$noinherit = true
$ex = <C-x>
<C-k> = :prev-field<Enter>
<C-Up> = :prev-field<Enter>
<C-j> = :next-field<Enter>
<C-Down> = :next-field<Enter>
<C-p> = :prev-tab<Enter>
<C-PgUp> = :prev-tab<Enter>
<C-n> = :next-tab<Enter>
<C-PgDn> = :next-tab<Enter>
[compose::review]
# Keybindings used when reviewing a message to be sent
y = :send<Enter>
n = :abort<Enter>
v = :preview<Enter>
p = :postpone<Enter>
q = :choose -o d discard abort -o p postpone postpone<Enter>
e = :edit<Enter>
a = :attach<space>
d = :detach<space>
[terminal]
$noinherit = true
$ex = <C-x>
<C-p> = :prev-tab<Enter>
<C-n> = :next-tab<Enter>
<C-PgUp> = :prev-tab<Enter>
<C-PgDn> = :next-tab<Enter>
# Binds are of the form <key sequence> = <command to run># To use '=' in a key sequence, substitute it with "Eq": "<Ctrl+Eq>"# If you wish to bind #, you can wrap the key sequence in quotes: "#" = quit<C-p> = :prev-tab<Enter><C-PgUp> = :prev-tab<Enter><C-n> = :next-tab<Enter><C-PgDn> = :next-tab<Enter>\[t = :prev-tab<Enter>\]t = :next-tab<Enter><C-t> = :term<Enter>? = :help keys<Enter><C-c> = :prompt 'Quit?' quit<Enter><C-q> = :prompt 'Quit?' quit<Enter><C-z> = :suspend<Enter>[messages]q = :prompt 'Quit?' quit<Enter>j = :next<Enter><Down> = :next<Enter><C-d> = :next 50%<Enter><C-f> = :next 100%<Enter><PgDn> = :next 100%<Enter>k = :prev<Enter><Up> = :prev<Enter><C-u> = :prev 50%<Enter><C-b> = :prev 100%<Enter><PgUp> = :prev 100%<Enter>g = :select 0<Enter>G = :select -1<Enter>J = :next-folder<Enter><C-Down> = :next-folder<Enter>K = :prev-folder<Enter><C-Up> = :prev-folder<Enter>H = :collapse-folder<Enter><C-Left> = :collapse-folder<Enter>L = :expand-folder<Enter><C-Right> = :expand-folder<Enter>v = :mark -t<Enter><Space> = :mark -t<Enter>:next<Enter>V = :mark -v<Enter>T = :toggle-threads<Enter>zc = :fold<Enter>zo = :unfold<Enter>za = :fold -t<Enter>zM = :fold -a<Enter>zR = :unfold -a<Enter><tab> = :fold -t<Enter><Enter> = :view<Enter>d = :prompt 'Really delete this message?' 'delete-message'<Enter>D = :delete<Enter>a = :archive flat<Enter>A = :unmark -a<Enter>:mark -T<Enter>:archive flat<Enter>C = :compose<Enter>m = :compose<Enter>rr = :reply -a<Enter>rq = :reply -aq<Enter>Rr = :reply<Enter>Rq = :reply -q<Enter>c = :cf<space>$ = :term<space>! = :term<space>| = :pipe<space>/ = :search<space>\ = :filter<space>n = :next-result<Enter>N = :prev-result<Enter><Esc> = :clear<Enter>s = :split<Enter>S = :vsplit<Enter>pl = :patch list<Enter>pa = :patch apply <Tab>pd = :patch drop <Tab>pb = :patch rebase<Enter>pt = :patch term<Enter>ps = :patch switch <Tab>[messages:folder=Drafts]<Enter> = :recall<Enter>[view]/ = :toggle-key-passthrough<Enter>/q = :close<Enter>O = :open<Enter>o = :open<Enter>E = :pipe -p nvim -R -n -c 'setlocal ft=mail nomodifiable' -<Enter>S = :save<space>Y = :pipe -pb ~/.config/aerc/copy-to-clipboard current-part<Enter>M = :pipe -mb ~/.config/aerc/copy-to-clipboard full-message<Enter>| = :pipe<space>D = :delete<Enter>A = :archive flat<Enter><C-l> = :open-link <space>f = :forward<Enter>rr = :reply -a<Enter>rq = :reply -aq<Enter>Rr = :reply<Enter>Rq = :reply -q<Enter>H = :toggle-headers<Enter><C-k> = :prev-part<Enter><C-Up> = :prev-part<Enter><C-j> = :next-part<Enter><C-Down> = :next-part<Enter>J = :next<Enter><C-Right> = :next<Enter>K = :prev<Enter><C-Left> = :prev<Enter>[view::passthrough]$noinherit = true$ex = <C-x><Esc> = :toggle-key-passthrough<Enter>[compose]# Keybindings used when the embedded terminal is not selected in the compose# view$noinherit = true$ex = <C-x>$complete = <C-o><C-k> = :prev-field<Enter><C-Up> = :prev-field<Enter><C-j> = :next-field<Enter><C-Down> = :next-field<Enter><A-p> = :switch-account -p<Enter><C-Left> = :switch-account -p<Enter><A-n> = :switch-account -n<Enter><C-Right> = :switch-account -n<Enter><tab> = :next-field<Enter><backtab> = :prev-field<Enter><C-p> = :prev-tab<Enter><C-PgUp> = :prev-tab<Enter><C-n> = :next-tab<Enter><C-PgDn> = :next-tab<Enter>[compose::editor]# Keybindings used when the embedded terminal is selected in the compose view$noinherit = true$ex = <C-x><C-k> = :prev-field<Enter><C-Up> = :prev-field<Enter><C-j> = :next-field<Enter><C-Down> = :next-field<Enter><C-p> = :prev-tab<Enter><C-PgUp> = :prev-tab<Enter><C-n> = :next-tab<Enter><C-PgDn> = :next-tab<Enter>[compose::review]# Keybindings used when reviewing a message to be senty = :send<Enter>n = :abort<Enter>v = :preview<Enter>p = :postpone<Enter>q = :choose -o d discard abort -o p postpone postpone<Enter>e = :edit<Enter>a = :attach<space>d = :detach<space>[terminal]$noinherit = true$ex = <C-x><C-p> = :prev-tab<Enter><C-n> = :next-tab<Enter><C-PgUp> = :prev-tab<Enter><C-PgDn> = :next-tab<Enter>bash/bashrc
Modified+27 / −38 text lines
# Bash interactive config from dotfiles.export GO_HOME="$HOME/go"export PATH="$GO_HOME/bin:$PATH"export PATH="$HOME/.local/bin:$PATH"export TERMUX_X11_XSTARTUP="wezterm"eval "$(zoxide init bash)"eval "$(JUST_COMPLETE=bash just)"# Termux/Android node-gyp workaround for native npm packages like node-pty.# node-gyp's Android config expects android_ndk_path; keep this safe to source repeatedly._node_gyp_android_ndk="$HOME/.termux-node-gyp-android-ndk"mkdir -p "$_node_gyp_android_ndk/sources/android/cpufeatures" 2>/dev/null || truecase " ${GYP_DEFINES:-} " in *" android_ndk_path=$_node_gyp_android_ndk "*) ;; *) export GYP_DEFINES="android_ndk_path=$_node_gyp_android_ndk${GYP_DEFINES:+ $GYP_DEFINES}" ;;unset _node_gyp_android_ndk# Linux virtual console colors. No sudo, no effect in terminal emulators._nugu_console_theme() { [ "${TERM:-}" = linux ] || return 0 local mode="${1:-light}" local theme="$HOME/.config/bash/linux-console/nugu-$mode.sh" if [ ! -r "$theme" ]; then printf 'missing theme: %s\n' "$theme" >&2 return 1 fi . "$theme" clear}tt() { case "${1:-toggle}" in dark|light) _nugu_console_theme "$1" ;; toggle) case "${NUGU_CONSOLE_THEME:-light}" in light) _nugu_console_theme dark ;; dark) _nugu_console_theme light ;; *) _nugu_console_theme light ;; esac ;; *) printf 'usage: tt [dark|light]\n' >&2 return 2 ;; esac}_nugu_console_theme lightbash/secrets.bash
Addednew file mode 100644Binary size (old → new): 0 → 89 bytes.
bat/config
Modified+14 / −14 text lines
# apply colors from my terminal color scheme
--theme=ansi
--style=full
--tabs 2
#--show-all
#--nonprintable-notation=unicode
# use features of modern terminals
--italic-text=always
# Map some unknown file types to (hopefully similar) known ones
--map-syntax "*.nu:Rust"
--map-syntax ".stignore:Git Ignore"
# apply colors from my terminal color scheme--theme=ansi--style=full--tabs 2#--show-all#--nonprintable-notation=unicode# use features of modern terminals--italic-text=always# Map some unknown file types to (hopefully similar) known ones--map-syntax "*.nu:Rust"--map-syntax ".stignore:Git Ignore"bootstripper.java
Modified+607 / −157 text lines
import java.nio.file.AtomicMoveNotSupportedException; private final static String key_file = ".git/dotfiles-aes.key"; private final static String hook_marker = "# Managed by dorkfiles bootstripper.java"; setup_crypto(root, false); require_normal_gitdir(root); setup_crypto(root, true); if ("link".equals(command)) { var symlinks_file = symlinks_file(root); check_symlink_sources(root); converge_crypto(root); install_repo_settings(root); install_hooks(root); create_symlinks(root, symlinks_file); print_attention(false); return; } if ("setup-crypto".equals(command)) { converge_crypto(root); return; } var symlinks_file = symlinks_file(root); check_symlink_sources(root); converge_crypto(root); install_repo_settings(root); var symlinks_file = symlinks_file(root); print_attention(false); return "bootstrap".equals(argument) || "clean".equals(argument) || "check".equals(argument) || "pre-commit".equals(argument) || "install-hooks".equals(argument) || "init-crypto".equals(argument); 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); static void setup_crypto(Path root, boolean restore) throws Throwable { static List<String> setup_crypto(Path root) throws Throwable { ensure_key(root); self_test_aes(root); if (restore) restore_tracked_secrets(root, secrets); remove_local_attributes(root); static void require_normal_gitdir(Path root) throws Throwable { if (!Files.isDirectory(root.resolve(".git"))) throw fail("Expected normal .git directory. Linked worktrees are not supported yet."); static Path git_common_path(Path root, String path) throws Throwable { var common = run(root, List.of("git", "rev-parse", "--git-common-dir"), null, false).text().strip(); var common_path = Path.of(common); if (!common_path.isAbsolute()) common_path = root.resolve(common_path).normalize(); return common_path.resolve(path).toAbsolutePath(); } static Path key_path(Path root) throws Throwable { return git_common_path(root, key_file); } static String key_argument(Path root) throws Throwable { return key_path(root).toString(); } static String aes_tool_argument(Path root) throws Throwable { return git_common_path(root, aes_cache_file).toString(); } static String clean_filter_command(Path root) throws Throwable { return "java " + quote_shell(aes_tool_argument(root)) + " encrypt --key-file " + quote_shell(key_argument(root)); } static String smudge_filter_command(Path root) throws Throwable { return "java " + quote_shell(aes_tool_argument(root)) + " decrypt --key-file " + quote_shell(key_argument(root)); } static String merge_filter_command(Path root) throws Throwable { return "java " + quote_shell(aes_tool_argument(root)) + " merge --key-file " + quote_shell(key_argument(root)) + " " + quote_shell("%O") + " " + quote_shell("%A") + " " + quote_shell("%B"); if (line.contains(" ") || line.contains("\t") || line.startsWith("/") || line.contains("\\")) static void install_aes_tool(Path root) throws Throwable { var source = root.resolve("tools/aes.java"); if (!Files.isRegularFile(source, LinkOption.NOFOLLOW_LINKS)) throw fail("Expected a regular AES tool source at: {0}", source); var target = git_common_path(root, aes_cache_file); if (Files.exists(target, LinkOption.NOFOLLOW_LINKS)) { if (!Files.isRegularFile(target, LinkOption.NOFOLLOW_LINKS)) throw fail("Refusing to replace non-file cached AES tool: {0}", target); if (Files.mismatch(source, target) == -1L) return; } Files.createDirectories(target.getParent()); var temporary = Files.createTempFile(target.getParent(), "." + aes_cache_file + ".", ".tmp"); try { Files.copy(source, temporary, StandardCopyOption.REPLACE_EXISTING); try { Files.move(temporary, target, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING); } catch (AtomicMoveNotSupportedException ignored) { Files.move(temporary, target, StandardCopyOption.REPLACE_EXISTING); } } finally { Files.deleteIfExists(temporary); } } static void validate_secret_paths(Path root, List<String> secrets) throws Throwable { for (var secret : secrets) { var original = Path.of(secret); for (var component : original) if (component.toString().equals("..")) throw fail("Secret path must not contain parent components: {0}", secret); var relative = original.normalize(); if (relative.isAbsolute() || relative.startsWith("..")) throw fail("Secret path must stay inside the repository: {0}", secret); var current = root; for (var component : relative) { current = current.resolve(component); if (Files.isSymbolicLink(current)) throw fail("Secret path must not contain symlinks: {0}", secret); } if (Files.exists(current, LinkOption.NOFOLLOW_LINKS) && !Files.isRegularFile(current, LinkOption.NOFOLLOW_LINKS)) throw fail("Secret path must name a regular file: {0}", secret); } } run(root, List.of("git", "config", "--local", "filter." + filter_name + ".clean", "java tools/aes.java encrypt --key-file " + key_file), null, false); run(root, List.of("git", "config", "--local", "filter." + filter_name + ".smudge", "java tools/aes.java decrypt --key-file " + key_file), null, false); run(root, List.of("git", "config", "--local", "filter." + filter_name + ".required", "true"), null, false); set_local_config(root, "filter." + filter_name + ".clean", clean_filter_command(root)); set_local_config(root, "filter." + filter_name + ".smudge", smudge_filter_command(root)); set_local_config(root, "filter." + filter_name + ".required", "true"); set_local_config(root, "merge." + filter_name + ".driver", merge_filter_command(root)); } // Autostash is a trap in this repository: the worktree is nearly always dirty, so // every rebase or merge stashes first, and the required crypto filter plus the Git // hooks can abort the operation before the stash is restored. The changes then sit // in a silent `autostash` stash entry while the files look deleted. Refuse instead. static void install_repo_settings(Path root) throws Throwable { set_local_config(root, "rebase.autostash", "false"); set_local_config(root, "merge.autostash", "false"); } static void check_repo_settings(Path root) throws Throwable { check_local_config(root, "rebase.autostash", "false"); check_local_config(root, "merge.autostash", "false"); } static void check_local_config(Path root, String name, String value) throws Throwable { var current = run(root, List.of("git", "config", "--local", "--get", name), null, false, false); if (current.exit != 0 || !current.text().strip().equals(value)) throw fail("Local Git setting {0} must be {1}. Run `mise run link`.", name, value); } static void set_local_config(Path root, String name, String value) throws Throwable { var current = run(root, List.of("git", "config", "--local", "--get", name), null, false, false); if (current.exit != 0 || !current.text().strip().equals(value)) run(root, List.of("git", "config", "--local", name, value), null, false); } static String quote_shell(String argument) { return "'" + argument.replace("'", "'\\''") + "'"; var attributes = root.resolve(".git/info/attributes"); Files.createDirectories(attributes.getParent()); var previous = Files.exists(attributes) ? Files.readString(attributes) : ""; var attributes = root.resolve(".gitattributes"); var content = Files.exists(attributes) ? without_managed_attributes(Files.readString(attributes)) : ""; if (!content.isEmpty() && !content.endsWith("\n")) content += "\n"; var lines = new ArrayList<String>(); lines.add(attributes_begin); for (var secret : secrets) lines.add(secret + " -text filter=" + filter_name + " -diff merge=" + filter_name); lines.add(attributes_end); var desired = content + String.join("\n", lines) + "\n"; if (!Files.exists(attributes) || !Files.readString(attributes).equals(desired)) Files.writeString(attributes, desired, StandardCharsets.UTF_8); } static void remove_local_attributes(Path root) throws Throwable { var attributes = git_common_path(root, "info/attributes"); if (!Files.exists(attributes)) return; var previous = Files.readString(attributes); var content = without_managed_attributes(previous); if (!content.equals(previous)) Files.writeString(attributes, content, StandardCharsets.UTF_8); } static String without_managed_attributes(String content) { lines.add(attributes_begin); for (var secret : secrets) lines.add(secret + " -text filter=" + filter_name + " -diff"); lines.add(attributes_end); Files.writeString(attributes, String.join("\n", lines) + "\n", StandardCharsets.UTF_8); return String.join("\n", lines); var salt = read_salt(root); var passphrase = passphrase(); try { var factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256"); var spec = new PBEKeySpec(passphrase, salt, pbkdf2_iterations, derived_key_bits); var encoded = factory.generateSecret(spec).getEncoded(); Files.writeString(key, Base64.getEncoder().encodeToString(encoded) + "\n", StandardCharsets.UTF_8); chmod(key, "rw-------"); log("Cached dotfiles AES key in {0}", emphasize_local(key_file)); } finally { Arrays.fill(passphrase, '\0'); Files.createDirectories(key.getParent()); var temporary = Files.createTempFile(key.getParent(), key_file + ".", ".tmp"); char[] passphrase = null; try { passphrase = passphrase(); var factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256"); var spec = new PBEKeySpec(passphrase, read_salt(root), pbkdf2_iterations, derived_key_bits); var encoded = factory.generateSecret(spec).getEncoded(); Files.writeString(temporary, Base64.getEncoder().encodeToString(encoded) + "\n", StandardCharsets.UTF_8); ensure_permissions(temporary, "rw-------"); if (!authenticate_key(root, secrets, temporary)) self_test_aes(root, temporary); try { Files.move(temporary, key, StandardCopyOption.ATOMIC_MOVE); } catch (AtomicMoveNotSupportedException ignored) { Files.move(temporary, key); } log("Cached dotfiles AES key in {0}", emphasize_local(key.toString())); } finally { if (passphrase != null) Arrays.fill(passphrase, '\0'); Files.deleteIfExists(temporary); } } static void validate_key(Path key) throws IOException { if (!Files.isRegularFile(key, LinkOption.NOFOLLOW_LINKS) || !Files.isReadable(key)) throw new IllegalStateException("Dotfiles AES key must be a readable regular file: " + key); try { if (Base64.getDecoder().decode(Files.readString(key).trim()).length != derived_key_bits / 8) throw new IllegalStateException("Dotfiles AES key has the wrong length: " + key); } catch (IllegalArgumentException problem) { throw new IllegalStateException("Dotfiles AES key is not valid Base64: " + key); } } static boolean authenticate_key(Path root, List<String> secrets, Path key) throws Throwable { String encrypted_secret = null; for (var secret : secrets) { var committed = run(root, List.of("git", "cat-file", "blob", "HEAD:" + secret), null, false, false); if (committed.exit != 0 || !starts_with(committed.stdout, aes_magic)) continue; encrypted_secret = secret; var decrypted = run(root, List.of("java", aes_tool_argument(root), "decrypt", "--key-file", key.toString()), committed.stdout, false, false); if (decrypted.exit == 0) return true; } if (encrypted_secret != null) throw new IllegalStateException("Passphrase does not decrypt committed secrets, including: " + encrypted_secret); return false; static void self_test_aes(Path root) throws Throwable { static void self_test_aes(Path root, Path key) throws Throwable { var encrypted = run(root, List.of("java", "tools/aes.java", "encrypt", "--key-file", key_file), plain, false).stdout; if (!starts_with(encrypted, aes_magic)) throw fail("AES self-test did not produce expected magic header."); var decrypted = run(root, List.of("java", "tools/aes.java", "decrypt", "--key-file", key_file), encrypted, false).stdout; if (!Arrays.equals(plain, decrypted)) throw fail("AES self-test failed to round-trip."); var aes = aes_tool_argument(root); var encrypted = run(root, List.of("java", aes, "encrypt", "--key-file", key.toString()), plain, false, false); if (encrypted.exit != 0 || !starts_with(encrypted.stdout, aes_magic)) throw new IllegalStateException("AES self-test encryption failed: " + encrypted.error().strip()); var decrypted = run(root, List.of("java", aes, "decrypt", "--key-file", key.toString()), encrypted.stdout, false, false); if (decrypted.exit != 0 || !Arrays.equals(plain, decrypted.stdout)) throw new IllegalStateException("AES self-test decryption failed: " + decrypted.error().strip()); var tracked = new ArrayList<String>(); for (var secret : secrets) { var result = run(root, List.of("git", "cat-file", "-e", "HEAD:" + secret), null, false, false); if (result.exit == 0) { tracked.add(secret); var path = root.resolve(secret); if (Files.exists(path) && starts_with(Files.readAllBytes(path), aes_magic)) Files.delete(path); } } var tree_command = new ArrayList<>(List.of("git", "--literal-pathspecs", "ls-tree", "--name-only", "-z", "HEAD", "--")); tree_command.addAll(secrets); var tracked_output = run(root, tree_command, null, false, false); if (tracked_output.exit != 0) return; var tracked = new LinkedHashSet<String>(); for (var path : new String(tracked_output.stdout, StandardCharsets.UTF_8).split("\u0000")) if (!path.isEmpty()) tracked.add(path); var command = new ArrayList<String>(); command.addAll(List.of("git", "restore", "--source=HEAD", "--worktree", "--")); command.addAll(tracked); run(root, command, null, false); var staged_command = new ArrayList<>(List.of("git", "--literal-pathspecs", "diff", "--cached", "--quiet", "HEAD", "--")); staged_command.addAll(tracked); if (run(root, staged_command, null, false, false).exit != 0) { for (var secret : tracked) if (run(root, List.of("git", "--literal-pathspecs", "diff", "--cached", "--quiet", "HEAD", "--", secret), null, false, false).exit != 0) throw fail("Refusing to restore locally changed secret: {0}", secret); } var current = new LinkedHashMap<String, byte[]>(); var needs_restoration = false; for (var secret : tracked) { var path = root.resolve(secret); if (!Files.isRegularFile(path, LinkOption.NOFOLLOW_LINKS)) throw fail("Refusing to restore locally changed secret: {0}", secret); var bytes = Files.readAllBytes(path); current.put(secret, bytes); needs_restoration |= starts_with(bytes, aes_magic); } if (!needs_restoration) return; var pending = new LinkedHashMap<Path, byte[]>(); for (var secret : tracked) { var committed = run(root, List.of("git", "cat-file", "blob", "HEAD:" + secret), null, false); var plain = run(root, List.of("java", aes_tool_argument(root), "decrypt", "--key-file", key_argument(root)), committed.stdout, false).stdout; var bytes = current.get(secret); if (Arrays.equals(bytes, committed.stdout)) pending.put(root.resolve(secret), plain); else if (!Arrays.equals(bytes, plain)) throw fail("Refusing to restore locally changed secret: {0}", secret); } for (var entry : pending.entrySet()) Files.write(entry.getKey(), entry.getValue()); static void install_hooks(Path root) throws IOException { var hooks = root.resolve(".git/hooks"); static void install_hooks(Path root) throws Throwable { var hooks = git_hooks_path(root); var pre_commit = hooks.resolve("pre-commit"); var pre_push = hooks.resolve("pre-push"); var legacy_pre_commit = "#!/bin/sh\ncd \"$(git rev-parse --show-toplevel)\" || exit 1\nexec java bootstripper.java pre-commit\n"; var pre_commit_content = hook_content("pre-commit"); var pre_push_content = hook_content("pre-push"); check_hook_destination(pre_commit, pre_commit_content, legacy_pre_commit); check_hook_destination(pre_push, pre_push_content, null); install_hook(hooks, pre_commit, pre_commit_content); install_hook(hooks, pre_push, pre_push_content); } static Path git_hooks_path(Path root) throws Throwable { var configured = run(root, List.of("git", "config", "--show-scope", "--get", "core.hooksPath"), null, false, false); if (configured.exit == 0 && !configured.text().matches("(?s)^(local|worktree)\\s+.*")) throw fail("Refusing to modify inherited core.hooksPath. Configure a repository-local hooks path or unset it."); var result = run(root, List.of("git", "rev-parse", "--path-format=absolute", "--git-path", "hooks"), null, false).text().strip(); var hooks = Path.of(result).toAbsolutePath().normalize(); if (hooks.equals(Path.of("/dev/null")) || Files.exists(hooks, LinkOption.NOFOLLOW_LINKS) && !Files.isDirectory(hooks, LinkOption.NOFOLLOW_LINKS)) throw fail("Invalid Git hooks directory: {0}", hooks); return hooks; } static String hook_content(String command) { return "#!/bin/sh\n" + hook_marker + "\ncd \"$(git rev-parse --show-toplevel)\" || exit 1\nexec java bootstripper.java " + command + "\n"; } static void check_hook_destination(Path hook, String expected, String legacy) throws Throwable { if (!Files.exists(hook, LinkOption.NOFOLLOW_LINKS)) return; if (Files.isSymbolicLink(hook) || !Files.isRegularFile(hook, LinkOption.NOFOLLOW_LINKS)) throw fail("Refusing to replace non-file Git hook: {0}", hook); var content = Files.readString(hook); if (content.equals(expected) || content.equals(legacy) || content.contains("\n" + hook_marker + "\n")) return; throw fail("Refusing to replace unmanaged Git hook: {0}", hook); } static void install_hook(Path hooks, Path hook, String content) throws Throwable { var content_matches = Files.isRegularFile(hook, LinkOption.NOFOLLOW_LINKS) && Files.readString(hook).equals(content); var permissions_match = hook_permissions_match(hook); if (content_matches && permissions_match) return; var hook = hooks.resolve("pre-commit"); Files.writeString(hook, "#!/bin/sh\ncd \"$(git rev-parse --show-toplevel)\" || exit 1\nexec java bootstripper.java pre-commit\n", StandardCharsets.UTF_8); chmod(hook, "rwxr-xr-x"); log("Installed Git hook: {0}", emphasize_local(".git/hooks/pre-commit")); if (!content_matches) { var temporary = Files.createTempFile(hooks, "." + hook.getFileName() + ".", ".tmp"); try { Files.writeString(temporary, content, StandardCharsets.UTF_8); chmod(temporary, "rwxr-xr-x"); try { Files.move(temporary, hook, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING); } catch (AtomicMoveNotSupportedException ignored) { Files.move(temporary, hook, StandardCopyOption.REPLACE_EXISTING); } } finally { Files.deleteIfExists(temporary); } } else { chmod(hook, "rwxr-xr-x"); } log("Installed Git hook: {0}", emphasize_local(hook.toString())); } static boolean hook_permissions_match(Path hook) throws IOException { if (win32) return true; try { return Files.exists(hook) && Files.getPosixFilePermissions(hook).equals(PosixFilePermissions.fromString("rwxr-xr-x")); } catch (UnsupportedOperationException ignored) { return Files.isExecutable(hook); } static void pre_push(Path root) throws Throwable { for (var line : new String(System.in.readAllBytes(), StandardCharsets.UTF_8).lines().toList()) { if (line.isBlank()) continue; var fields = line.strip().split("\\s+"); if (fields.length != 4) throw fail("Invalid pre-push input: expected four fields."); var local_oid = fields[1]; var remote_oid = fields[3]; if (is_zero_oid(local_oid)) continue; if (!is_oid(local_oid) || !is_oid(remote_oid)) throw fail("Invalid object ID in pre-push input."); var local_commit = resolve_commit(root, local_oid, "local"); var remote_commit = run(root, List.of("git", "rev-parse", "--verify", remote_oid + "^{commit}"), null, false, false); var revisions = is_zero_oid(remote_oid) || remote_commit.exit != 0 ? local_commit : remote_commit.text().strip() + ".." + local_commit; var log_options = "--full-history --diff-merges=first-parent --no-ext-diff --no-textconv " + revisions; run_gitleaks(root, List.of("--platform=none", "--log-opts=" + log_options)); } } static boolean is_oid(String value) { return value.matches("[0-9a-fA-F]{40}|[0-9a-fA-F]{64}"); } static boolean is_zero_oid(String value) { return is_oid(value) && value.chars().allMatch(character -> character == '0'); } static String resolve_commit(Path root, String oid, String label) throws Throwable { var result = run(root, List.of("git", "rev-parse", "--verify", oid + "^{commit}"), null, false, false); if (result.exit != 0) throw fail("Pre-push {0} object is not a commit: {1}", label, oid); return result.text().strip(); } static void run_gitleaks(Path root, List<String> scan_arguments) throws Throwable { var command = new ArrayList<>(List.of("gitleaks", "git")); command.addAll(scan_arguments); command.addAll(List.of("--redact=100", "--no-banner")); Result result; try { result = run(root, command, null, true, false); } catch (IOException error) { throw fail("Gitleaks is required for Git hooks. Install Gitleaks, ensure it is on Git''s PATH, then retry."); } if (result.exit != 0) throw fail("Gitleaks blocked the operation (exit {0}). Review its redacted output.", result.exit); } static void check_staged_matches_worktree(Path root, String path) throws Throwable { var tracked = run(root, List.of("git", "ls-files", "--error-unmatch", "--", path), null, false, false); var changed = run(root, List.of("git", "-c", "diff.autoRefreshIndex=false", "diff", "--no-ext-diff", "--no-textconv", "--quiet", "--", path), null, false, false); if (tracked.exit != 0 || changed.exit != 0) throw fail("{0} must match the staged version.", path); } if (secrets.isEmpty()) return; check_filter(root); check_attributes(root, secrets); check_key_not_tracked(root); check_staged_secrets(root, secrets); if (!secrets.isEmpty()) { if (!Files.isReadable(key_path(root))) throw fail("Dotfiles AES key is unavailable. Run `mise run setup-crypto`, then retry."); check_filter(root); check_attributes(root, secrets); check_secrets_not_ignored(root, secrets); check_worktree_secrets_decrypted(root, secrets); check_key_not_tracked(root); check_staged_secrets(root, secrets); } check_repo_settings(root); var clean = run(root, List.of("git", "config", "--local", "--get", "filter." + filter_name + ".clean"), null, false).text().strip(); var smudge = run(root, List.of("git", "config", "--local", "--get", "filter." + filter_name + ".smudge"), null, false).text().strip(); var required = run(root, List.of("git", "config", "--local", "--get", "filter." + filter_name + ".required"), null, false).text().strip(); if (!clean.equals("java tools/aes.java encrypt --key-file " + key_file)) if (!smudge.equals("java tools/aes.java decrypt --key-file " + key_file)) if (!smudge.equals(smudge_filter_command(root))) var output = run(root, List.of("git", "check-attr", "text", "filter", "diff", "--", secret), null, false).text(); var output = run(root, List.of("git", "--literal-pathspecs", "check-attr", "text", "filter", "diff", "merge", "--", secret), null, false).text(); if (!output.contains(secret + ": merge: " + filter_name)) throw fail("Missing merge attribute for {0}: {1}", secret, output.strip()); } } static void check_secrets_not_ignored(Path root, List<String> secrets) throws Throwable { var command = new ArrayList<String>(List.of("git", "check-ignore", "--no-index", "--verbose", "--")); command.addAll(secrets); var result = run(root, command, null, false, false); if (result.exit == 0) throw fail("Secret paths are matched by ignore rules, so they can never be encrypted or staged: {0}", result.text().strip()); if (result.exit != 1) throw fail("Unable to check ignore rules for secrets: {0}", result.text().strip()); } static void check_worktree_secrets_decrypted(Path root, List<String> secrets) throws Throwable { for (var secret : secrets) { var path = root.resolve(secret); if (Files.exists(path) && starts_with(Files.readAllBytes(path), aes_magic)) throw fail("Worktree secret is encrypted; smudge failed: {0}", secret); var bad = run(root, List.of("git", "ls-files", "--", key_file), null, false).text().strip(); var bad = run(root, List.of("git", "ls-files", "--", ".git/" + key_file, key_file), null, false).text().strip(); var staged = run(root, List.of("git", "diff", "--cached", "--name-only", "--", key_file), null, false).text().strip(); var staged = run(root, List.of("git", "diff", "--cached", "--name-only", "--", ".git/" + key_file, key_file), null, false).text().strip(); var status = run(root, List.of("git", "diff", "--cached", "--name-status", "--", secret), null, false).text().strip(); var status = run(root, List.of("git", "--literal-pathspecs", "diff", "--cached", "--name-status", "--", secret), null, false).text().strip(); run(root, List.of("java", "tools/aes.java", "decrypt", "--key-file", key_file), blob, false); run(root, List.of("java", aes_tool_argument(root), "decrypt", "--key-file", key_argument(root)), blob, false); var files = stream.filter(path -> path.getFileName().toString().endsWith(".symlinks")).collect(Collectors.toList()); var targets = new HashSet<Path>(); var source_line = 0; source_line = line_number; throw fail("Missing symlink source: {0}:{1}: {2}", file.getFileName(), line_number - 1, source); static void check_no_tresor_refs(Path root) throws IOException { try (var stream = Files.list(root)) { var files = stream.filter(path -> path.getFileName().toString().endsWith(".symlinks")).collect(Collectors.toList()); for (var file : files) { var line_number = 0; for (var line : Files.readAllLines(file)) { line_number++; if (line.strip().startsWith("tresor/")) throw new IllegalStateException("tresor reference remains: " + file.getFileName() + ":" + line_number); } } } } static void check_staged_plaintext_patterns(Path root) throws Throwable { var diff = run(root, List.of("git", "diff", "--cached", "-U0"), null, false).text(); var patterns = List.of( Pattern.compile("gh[pousr]_[A-Za-z0-9_]{20,}"), Pattern.compile("github_personal_access_token\\s*\\\":\\s*\\\"[^<G][^\\\"]+\\\""), Pattern.compile("oauth_(access|refresh)_token\\s*=\\s*\\S+"), Pattern.compile("Authorization\\s*[:=]\\s*Bearer\\s+[A-Za-z0-9._-]{20,}", Pattern.CASE_INSENSITIVE)); for (var pattern : patterns) { var matcher = pattern.matcher(diff); if (matcher.find()) throw fail("Potential plaintext secret in staged diff."); } } static boolean is_wsl() { var distro = System.getenv("WSL_DISTRO_NAME"); if (distro != null && !distro.isBlank()) return true; try { var release = Files.readString(Path.of("/proc/sys/kernel/osrelease"), StandardCharsets.UTF_8).toLowerCase(); return release.contains("microsoft") || release.contains("wsl"); } catch (IOException ignored) { return false; } } log("Creating symlinks as defined in {0} file.", emphasize_local(symlinks_file.getFileName().toString())); var source_path = root.resolve(source).toAbsolutePath(); var source_path = root.resolve(source).toAbsolutePath().normalize(); log("\n{0} does not exist anymore in my dorkfiles. Have I yeeted it?", emphasize_global(source_path.toString())); var actual = target_path.toRealPath(); var expected = source_path.toRealPath(); if (actual.equals(expected)) { log("\nOK {0} -> {1}.", emphasize_global(target_path.toString()), emphasize_local(source_path.toString())); return; var raw_actual = symlink_target_path(target_path); if (!inside_home(raw_actual)) throw fail("Target symlink points outside HOME: {0} -> {1}. Move it manually.", target_path, raw_actual); if (!Files.exists(target_path)) { log("\nRELINK {0}: broken symlink.", emphasize_global(target_path.toString())); remove_owned_symlink(target_path); } else { var actual = target_path.toRealPath(); if (actual.equals(expected)) { log("\nOK {0} -> {1}.", emphasize_global(target_path.toString()), emphasize_local(source_path.toString())); return; } if (!inside_home(actual)) throw fail("Target symlink points outside HOME: {0} -> {1}. Move it manually.", target_path, actual); else { if (!actual.startsWith(root.toRealPath())) throw fail("Target symlink points outside dorkfiles: {0} -> {1}. Move it manually.", target_path, actual); log("\nRELINK {0}: {1} -> {2}.", emphasize_global(target_path.toString()), emphasize_local(actual.toString()), emphasize_local(expected.toString())); remove_owned_symlink(target_path); } var expected = source_path.toRealPath(); log("\nOK {0} resolves to {1}.", emphasize_global(target_path.toString()), emphasize_local(source_path.toString())); throw fail("Target exists but is not a symlink: {0}. Move it away or run clean first.", target_path); log("\nNOPE {0} exists, but it points into nirvana. Removing broken link!", target_path.toString()); static Path expand_target(String target) { var home = System.getProperty("user.home"); if ("~".equals(target)) return Path.of(home).toAbsolutePath(); if (target.startsWith("~/")) return Path.of(home).resolve(target.substring(2)).toAbsolutePath(); return Path.of(target).toAbsolutePath(); static void remove_owned_symlink(Path target_path) throws Throwable { if (!win32) { Files.delete(target_path); return; } var retired = sibling_path(target_path, "replaced"); Files.move(target_path, retired); try { Files.delete(retired); } catch (IOException error) { log("WIN32 kept retired link for later cleanup: {0}", retired); } } static Path symlink_target_path(Path target_path) throws IOException { var link = Files.readSymbolicLink(target_path); var resolved = link.isAbsolute() ? link : target_path.getParent().resolve(link); return resolved.toAbsolutePath().normalize(); } static Path sibling_backup_path(Path target_path) throws Throwable { return sibling_path(target_path, "backup"); } static Path sibling_path(Path target_path, String kind) throws Throwable { var stamp = DateTimeFormatter.ofPattern("yyyyMMdd-HHmmss").format(LocalDateTime.now()); var base = target_path.resolveSibling(target_path.getFileName() + ".dorkfiles-" + kind + "-" + stamp); var candidate = base; var suffix = 1; while (Files.exists(candidate, LinkOption.NOFOLLOW_LINKS)) { candidate = Path.of(base + "." + suffix); suffix++; } return candidate; } static Path expand_target(String target) throws Throwable { var path = switch (target) { case "~" -> target_home_path(); default -> target.startsWith("~/") ? target_home_path().resolve(target.substring(2)) : Path.of(target).toAbsolutePath(); }; path = path.normalize(); require_inside_home(path, "Symlink target"); return path; } static Path target_home_path() { return Path.of(System.getProperty("user.home")).toAbsolutePath().normalize(); } static Path home_path() { var home = System.getenv("HOME"); if (home == null || home.isBlank()) home = System.getProperty("user.home"); return Path.of(home).toAbsolutePath().normalize(); } static boolean inside_home(Path path) { return path.toAbsolutePath().normalize().startsWith(home_path()); } static void require_inside_home(Path path, String label) throws Throwable { if (!inside_home(path)) throw fail("{0} outside HOME: {1}", label, path.toAbsolutePath().normalize()); static void ensure_permissions(Path path, String permissions) throws IOException { if (win32) return; try { var desired = PosixFilePermissions.fromString(permissions); if (!Files.getPosixFilePermissions(path).equals(desired)) Files.setPosixFilePermissions(path, desired); } catch (UnsupportedOperationException ignored) {} } log("{0}: java bootstripper.java [init-crypto|check|pre-commit|install-hooks|clean] [dotfiles root path]", emphasize_global("Usage")); 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")); static void warn(String message) { warnings.add(message); } static void error(String message) { errors.add(message); } static void print_attention(boolean fatal) { if (warnings.isEmpty() && errors.isEmpty()) return; var color = fatal || !errors.isEmpty() ? "\033[31m" : "\033[33m"; System.out.println(); System.out.println(color + "ATTENTION"); for (var warning : warnings) System.out.println("- " + warning); for (var error : errors) System.out.println("- " + error); System.out.println("\033[0m"); } print_attention(true);bottom/bottom.toml
Modified+141 / −141 text lines
# This is a default config file for bottom. All of the settings are commented
# out by default; if you wish to change them uncomment and modify as you see
# fit.
# This group of options represents a command-line flag/option. Flags explicitly
# added when running (ie: btm -a) will override this config file if an option
# is also set here.
[flags]
# Whether to hide the average cpu entry.
#hide_avg_cpu = false
# Whether to use dot markers rather than braille.
dot_marker = true
# The update rate of the application.
rate = 350
# Whether to put the CPU legend to the left.
left_legend = true
# Whether to set CPU% on a process to be based on the total CPU or just current usage.
#current_usage = false
# Whether to group processes with the same name together by default.
group_processes = true
# Whether to make process searching case sensitive by default.
#case_sensitive = false
# Whether to make process searching look for matching the entire word by default.
#whole_word = false
# Whether to make process searching use regex by default.
#regex = false
# Defaults to Celsius. Temperature is one of:
#temperature_type = "k"
#temperature_type = "f"
#temperature_type = "c"
#temperature_type = "kelvin"
#temperature_type = "fahrenheit"
temperature_type = "celsius"
# The default time interval (in milliseconds).
#default_time_value = 60000
# The time delta on each zoom in/out action (in milliseconds).
#time_delta = 15000
# Override layout default widget
#default_widget_type = "proc"
#default_widget_count = 1
# Use basic mode
#basic = false
# Use the old network legend style
#use_old_network_legend = false
# Remove space in tables
#hide_table_gap = false
##########################################################
# These are all the components that support custom theming. Note that colour support
# will, at the end of the day, depend on terminal support - for example, the
# macOS default Terminal does NOT like custom colours and it will glitch out.
[colors]
# Represents the colour of table headers (processes, CPU, disks, temperature).
#table_header_color="LightBlue"
# Represents the colour of the label each widget has.
widget_title_color = "Blue"
# Represents the average CPU color.
#avg_cpu_color="Red"
# Represents the colour the core will use in the CPU legend and graph.
#cpu_core_colors=["LightMagenta", "LightYellow", "LightCyan", "LightGreen", "LightBlue", "LightRed", "Cyan", "Green", "Blue", "Red"]
# Represents the colour RAM will use in the memory legend and graph.
ram_color = "LightGreen"
# Represents the colour SWAP will use in the memory legend and graph.
#swap_color="LightYellow"
# Represents the colour rx will use in the network legend and graph.
#rx_color="LightCyan"
# Represents the colour tx will use in the network legend and graph.
#tx_color="LightGreen"
# Represents the colour of the border of unselected widgets.
border_color = "Blue"
# Represents the colour of the border of selected widgets.
#highlighted_border_color="LightBlue"
# Represents the colour of most text.
text_color = "Blue"
# Represents the colour of text that is selected.
#selected_text_color="Black"
# Represents the background colour of text that is selected.
#selected_bg_color="LightBlue"
# Represents the colour of the lines and text of the graph.
graph_color = "Blue"
# Represents the colours of the battery based on charge
#battery_colors = ["red", "yellow", "yellow", "green", "green", "green"]
##########################################################
# Layout - layouts follow a pattern like this:
# [[row]] represents a row in the application.
# [[row.child]] represents either a widget or a column.
# [[row.child.child]] represents a widget.
#
# All widgets must have the type value set to one of ["cpu", "mem", "proc", "net", "temp", "disk", "empty"].
# All layout components have a ratio value - if this is not set, then it defaults to 1.
# The default widget layout:
[[row]]
ratio = 60
[[row.child]]
type = "proc"
default = true
[[row]]
ratio = 20
[[row.child]]
type = "cpu"
[[row]]
ratio = 10
[[row.child]]
type = "mem"
# This is a default config file for bottom. All of the settings are commented# out by default; if you wish to change them uncomment and modify as you see# fit.# This group of options represents a command-line flag/option. Flags explicitly# added when running (ie: btm -a) will override this config file if an option# is also set here.[flags]# Whether to hide the average cpu entry.#hide_avg_cpu = false# Whether to use dot markers rather than braille.dot_marker = true# The update rate of the application.rate = 350# Whether to put the CPU legend to the left.left_legend = true# Whether to set CPU% on a process to be based on the total CPU or just current usage.#current_usage = false# Whether to group processes with the same name together by default.group_processes = true# Whether to make process searching case sensitive by default.#case_sensitive = false# Whether to make process searching look for matching the entire word by default.#whole_word = false# Whether to make process searching use regex by default.#regex = false# Defaults to Celsius. Temperature is one of:#temperature_type = "k"#temperature_type = "f"#temperature_type = "c"#temperature_type = "kelvin"#temperature_type = "fahrenheit"temperature_type = "celsius"# The default time interval (in milliseconds).#default_time_value = 60000# The time delta on each zoom in/out action (in milliseconds).#time_delta = 15000# Override layout default widget#default_widget_type = "proc"#default_widget_count = 1# Use basic mode#basic = false# Use the old network legend style#use_old_network_legend = false# Remove space in tables#hide_table_gap = false########################################################### These are all the components that support custom theming. Note that colour support# will, at the end of the day, depend on terminal support - for example, the# macOS default Terminal does NOT like custom colours and it will glitch out.[colors]# Represents the colour of table headers (processes, CPU, disks, temperature).#table_header_color="LightBlue"# Represents the colour of the label each widget has.widget_title_color = "Blue"# Represents the average CPU color.#avg_cpu_color="Red"# Represents the colour the core will use in the CPU legend and graph.#cpu_core_colors=["LightMagenta", "LightYellow", "LightCyan", "LightGreen", "LightBlue", "LightRed", "Cyan", "Green", "Blue", "Red"]# Represents the colour RAM will use in the memory legend and graph.ram_color = "LightGreen"# Represents the colour SWAP will use in the memory legend and graph.#swap_color="LightYellow"# Represents the colour rx will use in the network legend and graph.#rx_color="LightCyan"# Represents the colour tx will use in the network legend and graph.#tx_color="LightGreen"# Represents the colour of the border of unselected widgets.border_color = "Blue"# Represents the colour of the border of selected widgets.#highlighted_border_color="LightBlue"# Represents the colour of most text.text_color = "Blue"# Represents the colour of text that is selected.#selected_text_color="Black"# Represents the background colour of text that is selected.#selected_bg_color="LightBlue"# Represents the colour of the lines and text of the graph.graph_color = "Blue"# Represents the colours of the battery based on charge#battery_colors = ["red", "yellow", "yellow", "green", "green", "green"]########################################################### Layout - layouts follow a pattern like this:# [[row]] represents a row in the application.# [[row.child]] represents either a widget or a column.# [[row.child.child]] represents a widget.## All widgets must have the type value set to one of ["cpu", "mem", "proc", "net", "temp", "disk", "empty"].# All layout components have a ratio value - if this is not set, then it defaults to 1.# The default widget layout:[[row]]ratio = 60[[row.child]]type = "proc"default = true[[row]]ratio = 20[[row.child]]type = "cpu"[[row]]ratio = 10[[row.child]]type = "mem"claude/RTK.md
Modified+29 / −29 text lines
# RTK - Rust Token Killer
**Usage**: Token-optimized CLI proxy (60-90% savings on dev operations)
## Meta Commands (always use rtk directly)
```bash
rtk gain # Show token savings analytics
rtk gain --history # Show command usage history with savings
rtk discover # Analyze Claude Code history for missed opportunities
rtk proxy <cmd> # Execute raw command without filtering (for debugging)
```
## Installation Verification
```bash
rtk --version # Should show: rtk X.Y.Z
rtk gain # Should work (not "command not found")
which rtk # Verify correct binary
```
⚠️ **Name collision**: If `rtk gain` fails, you may have reachingforthejack/rtk (Rust Type Kit) installed instead.
## Hook-Based Usage
All other commands are automatically rewritten by the Claude Code hook.
Example: `git status` → `rtk git status` (transparent, 0 tokens overhead)
Refer to CLAUDE.md for full command reference.
# RTK - Rust Token Killer**Usage**: Token-optimized CLI proxy (60-90% savings on dev operations)## Meta Commands (always use rtk directly)```bashrtk gain # Show token savings analyticsrtk gain --history # Show command usage history with savingsrtk discover # Analyze Claude Code history for missed opportunitiesrtk proxy <cmd> # Execute raw command without filtering (for debugging)```## Installation Verification```bashrtk --version # Should show: rtk X.Y.Zrtk gain # Should work (not "command not found")which rtk # Verify correct binary```⚠️ **Name collision**: If `rtk gain` fails, you may have reachingforthejack/rtk (Rust Type Kit) installed instead.## Hook-Based UsageAll other commands are automatically rewritten by the Claude Code hook.Example: `git status` → `rtk git status` (transparent, 0 tokens overhead)Refer to CLAUDE.md for full command reference.claude/STATUSLINE.md
Addednew file mode 100644+141 / −0 text lines
# Claude Code StatuslineEine einzeilige, Statusline für Claude Code.Reines Node (stdlib), ein Renderer + ein Hook. Cross-Plattform (win/mac/linux).Beispielausgabe:``` RD-1950 · Opus 4.8 · xhigh · RD-1950 · 5h ██▋░░░░░ 33%·2h44m · 7d █▏░░░░░░ 14% · 🔥$26.68/hr · $0.499 $136.54Σ $486.13☾ · caveman:full```Segmente (v.l.n.r.): Verzeichnis · Modell · Effort · Git/JJ-Branch · 5h-Limit ·7d-Limit · Burn-Rate ($/h) · Kosten (Turn / Session Σ / Monat ☾) · Caveman-Badge.---## Voraussetzungen| Dep | Pflicht | Zweck ||-----|---------|-------|| **Node ≥ 18** | ✅ | Laufzeit. Nur stdlib (`fs/os/path/crypto/child_process`), keine npm-Pakete. || **Claude Code** | ✅ | Liefert den JSON-Payload (inkl. Kosten) via stdin. || **git** oder **jj** | ➖ | Branch-Segment. Muss im `PATH` sein. Ohne → Segment entfällt. || **Nerd Font** | ➖ (empfohlen) | Glyphen ``, Balken `█▏░`, Icons. Ohne → Tofu (`□`). || **caveman-Plugin** | ➖ | Caveman-Badge. Ohne → Badge entfällt. |---## Dateien| Datei | Rolle ||-------|-------|| [`statusline.js`](./statusline.js) | Renderer. Liest stdin-JSON, gibt eine Zeile aus. || [`cc-statusline-hook.js`](./cc-statusline-hook.js) | Hook. Setzt Turn-Marker + Workflow-Badge. |Beide nach `~/.claude/` kopieren oder symlinken:```bashln -s "$PWD/statusline.js" ~/.claude/statusline.jsln -s "$PWD/cc-statusline-hook.js" ~/.claude/cc-statusline-hook.js```---## Installation1. Node ≥ 18 installieren, im `PATH`.2. Beide Dateien nach `~/.claude/` (s.o.).3. `~/.claude/settings.json` ergänzen (Auszug unten).4. Nerd Font im Terminal aktivieren (sonst Tofu statt Glyphen).5. Claude Code neu starten.### settings.json (Auszug)```jsonc{ "statusLine": { "type": "command", "command": "node ~/.claude/statusline.js" }, "hooks": { // Turn-Marker: Basis für die "Turn"-Kosten (Δ seit letztem Prompt) "UserPromptSubmit": [ { "hooks": [ { "type": "command", "command": "node ~/.claude/cc-statusline-hook.js" } ] } ], // Workflow-Badge: NUR beim Workflow-Tool feuern (matcher scoped!) "PreToolUse": [ { "matcher": "Workflow", "hooks": [ { "type": "command", "command": "node ~/.claude/cc-statusline-hook.js" } ] } ] }}```Der Hook ist **ein** Skript für beide Events; es verzweigt über `hook_event_name`.---## Funktionsweise- Claude Code spawnt `statusline.js` **pro Render** (frischer Prozess, Payload via stdin, 300 ms Debounce, event-getriggert: neue Assistant-Nachricht, `/compact`, Permission-/Vim-Mode-Wechsel). Per-Render-Spawn ist von der API erzwungen.- Renderer baut Segmente, jeweils eigener `try/catch` (ein Crash darf die Zeile nicht leeren), und schreibt **ohne** Trailing-Newline.- **Turn-Kosten**: Der Hook legt bei `UserPromptSubmit` eine Marker-Datei `~/.claude/.cc-turn-<session>` an. Der nächste Render liest sie, rebaselined den Turn-Start und löscht den Marker.- **Workflow-Badge**: Bei `PreToolUse(Workflow)` schreibt der Hook eine selbst- ablaufende Zeile nach `~/.claude/.cc-statusline-extra` (TTL 120 s), die der Renderer rendert.- **Kosten-Ledger** `~/.claude/.cc-cost-ledger.json`: Turn / Session / Monat (monats- übergreifend kumuliert). Idle-Renders (keine Kostenänderung) schreiben nicht. Selbst-GC räumt alte `.cc-*.tmp` / `.cc-turn-*` (> 1 Tag) auf.---## AnpassungTunables stehen oben in `statusline.js` im `CONFIG`-Block:| Schlüssel | Default | Bedeutung ||-----------|---------|-----------|| `sep` | `" · "` | Trenner zwischen Segmenten. || `barWidth` | `8` | Zellen pro Usage-Balken. || `costStyle` | `"icon"` | `"icon"` = helle `$Zahl` + gedämpftes Glyph; `"slash"` = `$x/turn`. || `gitCacheTtlMs` | `8000` | Cache für `git status` (Spawn ist ~400 ms kalt auf win32). || `contextWarnPct`/`CritPct` | `70`/`90` | Schwellen Kontext-Balken (gelb/rot). || `usageWarnPct`/`CritPct` | `50`/`80` | Schwellen Rate-Limit-Balken. || `burnWindowMs` | `10 min` | Fenster für die Burn-Rate ($/h). |---## Performance (win32)- Harte Untergrenze ist **nicht** das Skript, sondern der Node-Kaltstart: `node -e 0` ≈ **120 ms** (Prozess-Spawn + V8-Init). Nicht durch Flags reduzierbar.- **< 100 ms ist mit Node unmöglich.** Nur ein kompiliertes Binary (Go/Rust ~10–20 ms) unterbietet das — kostet aber Cross-Plattform (per-OS-Builds) + zweite Codebase. Bun (win32) und Deno sind langsamer als Node; LLRT kann kein stdin lesen. → Node.- Die Bar ist asynchron und blockiert keine Eingabe; ~120–140 ms sind unsichtbar.---## Troubleshooting| Symptom | Ursache / Fix ||---------|---------------|| `□`/Tofu statt Glyphen | Nerd Font nicht aktiv im Terminal. || Keine Kosten | Alte Claude-Code-Version ohne `cost` im Payload. || Kein Branch-Segment | `git`/`jj` nicht im `PATH`, oder nicht in einem Repo. || Keine Turn-Kosten | Hook nicht in `UserPromptSubmit` registriert. || Statusline leer | `statusline.js` wirft beim Start — manuell testen: `echo '{}' \| node ~/.claude/statusline.js`. |claude/settings.json
Modified+13 / −41 text lines
"enabledPlugins": { "context7@claude-plugins-official": true, "code-review@claude-plugins-official": true, "code-simplifier@claude-plugins-official": true, "github@claude-plugins-official": false, "skill-creator@claude-plugins-official": true, "feature-dev@claude-plugins-official": true, "commit-commands@claude-plugins-official": true, "atlassian@claude-plugins-official": true, "jdtls-lsp@claude-plugins-official": true, "remember@claude-plugins-official": false, "caveman@caveman": true, "superpowers@claude-plugins-official": true, "frontend-design@claude-plugins-official": true, "learning-output-style@claude-plugins-official": true, "coderabbit@claude-plugins-official": true, "desktop-commander@claude-plugins-official": true, "code-modernization@claude-plugins-official": true }, "extraKnownMarketplaces": { "claude-code-plugins": { "source": { "source": "github", "repo": "anthropics/claude-code" } }, "caveman": { "source": { "source": "github", "repo": "JuliusBrussee/caveman" } } }, "effortLevel": "xhigh", "advisorModel": "opus", "awaySummaryEnabled": false,claude/statusline.js
Modified+192 / −84 text lines
// <dir> · <model> · <effort> · <git|jj> · <5h bar> · <7d bar> · <cost> · <cm> · <extra>// <dir> · <model> · <effort> · <git|jj> · <ctx bar> · <5h bar> · <7d bar> · <burn> · <cost> · <caveman> · <extra> sep: " · ", // segment padding sep: " · ", // segment padding (single-space around the dot — tight) // burn-rate color: truecolor gradient stops ($/hr). grounded in this ledger // (median ~$9.5, p90 ~$19, peak intervals ~$50) + Opus 4.8 pricing ($5/$25/MTok): // ~$8 calm single-stream · ~$18 heavy/active · ~$36+ parallel-agent burn. // smooth lerp between stops — these are gradient anchors, not hard tiers. burnCool: 8, // ≤ this → pure green (calm) burnWarn: 18, // amber midpoint (≈ p90 — notably elevated) burnHot: 36, // ≥ this → pure red (HOT — deep tail) burnBold: 28, // ≥ this → bold weight (visual alarm) orange: (s) => `${E}[38;5;172m${s}${R}`, accent: (s) => `${E}[93m${s}${R}`, // bright yellow — warm badge accent (no orange in the 16-index palette)const pctColor = (p, warn, crit) => (p >= crit ? c.red : p >= warn ? c.yellow : c.green);const PARTIALS = ["", "▏", "▎", "▍", "▌", "▋", "▊", "▉"];function bar(pct, width, color) { let p = Math.max(0, Math.min(100, pct)); let filled = (p / 100) * width; let full = Math.floor(filled); let pIdx = Math.round((filled - full) * 8); if (pIdx === 8) { full += 1; pIdx = 0; } if (full > width) full = width; const partial = pIdx > 0 && full < width ? PARTIALS[pIdx] : ""; const used = full + (partial ? 1 : 0); const empty = Math.max(0, width - used); return color("█".repeat(full) + partial) + c.dim("░".repeat(empty));const lerp = (a, b, t) => Math.round(a + (b - a) * t); // single channelconst mix = (from, to, t) => from.map((v, i) => lerp(v, to[i], t)); // 3-channel lerp// Shared color basis. Base colors are ANSI 16-index (38;5;N, N<16) so the terminal THEME// remaps them on dark↔light. A gradient between two indices can't itself be an index, so// it's lerp'd in truecolor from each index's reference RGB — only the transient middle of// a ramp is non-adaptive; every anchor follows the theme.const IDX = { calm: 12, warn: 13, crit: 9 }; // bars: blue → magenta → red (all theme-adaptive)const BURN = { cool: 2, warm: 3, hot: 1 }; // 🔥 burn: green → yellow → red (kept distinct from bars)const 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 onlyconst sgr = (code, s) => `${E}[${code}m${s}${R}`;const idxColor = (n, bold) => (s) => sgr(`${bold ? "1;" : ""}38;5;${n}`, s); // adaptive anchorconst rgbColor = (rgb, bold) => (s) => sgr(`${bold ? "1;" : ""}38;2;${rgb[0]};${rgb[1]};${rgb[2]}`, s); // blend// 🔥 burn-rate color: green (calm) → yellow → red (HOT, bold past burnBold). anchors are// indices; the warming middle is a truecolor blend. render gates on burnRate>0 (no NaN).function burnColor(rate, label) { const { burnCool, burnWarn, burnHot, burnBold } = CONFIG; const bold = rate >= burnBold; if (rate <= burnCool) return idxColor(BURN.cool, bold)(label); if (rate >= burnHot) return idxColor(BURN.hot, bold)(label); const rgb = rate <= burnWarn ? mix(IDX_RGB[BURN.cool], IDX_RGB[BURN.warm], (rate - burnCool) / (burnWarn - burnCool)) : mix(IDX_RGB[BURN.warm], IDX_RGB[BURN.hot], (rate - burnWarn) / (burnHot - burnWarn)); return rgbColor(rgb, bold)(label);}const trough = idxColor(IDX.calm, false); // empty cells — same adaptive index as calm, ░ glyph separates// severity → colorizer. all three anchors are ANSI indices (theme-adaptive); only the// strictly-between warn→crit blend is truecolor (lerp of the two anchors' reference RGB).function meterColor(pct, warn, crit) { if (pct < warn) return idxColor(IDX.calm, false); // calm — blue if (pct >= crit) return idxColor(IDX.crit, true); // crit — red + bold const t = (pct - warn) / (crit - warn); if (t === 0) return idxColor(IDX.warn, false); // exactly at warn — yellow return rgbColor(mix(IDX_RGB[IDX.warn], IDX_RGB[IDX.crit], t), false); // smooth blend}// fill bar with shade-density leading edge (░▒▓); color from meterColor (index-based).function bar(pct, width, warn, crit) { const p = Math.max(0, Math.min(100, pct)); const filled = (p / 100) * width; const full = Math.min(width, Math.floor(filled)); const frac = filled - full; const tip = frac > 0 && full < width ? (frac < 1 / 3 ? "░" : frac < 2 / 3 ? "▒" : "▓") : ""; const empty = Math.max(0, width - full - (tip ? 1 : 0)); return meterColor(p, warn, crit)("█".repeat(full) + tip) + trough("░".repeat(empty));// label + 8-cell bar + pct% — shared by ctx and usage. severity drives color (subtle→loud).const meter = (label, pct, warn, crit) => `${c.dim(label)} ${bar(pct, CONFIG.barWidth, warn, crit)} ${meterColor(pct, warn, crit)(pct + "%")}`;// drop control chars (ANSI-injection / newline guard) before printing untrusted file text.const stripCtl = (s) => s.replace(/[\x00-\x1F]/g, "");// ─── crash-safe IO helpers (all swallow — a failed read/write must never blank the bar) ──// atomic write: tmp + rename so a concurrent reader never sees a half-written file.function atomicWrite(file, data) { try { const tmp = `${file}.${process.pid}.tmp`; fs.writeFileSync(tmp, data); fs.renameSync(tmp, file); } catch {}}// read a small plain file as text, or null. rejects symlinks (don't follow a planted// link out of the config dir) and oversized files; lstat keeps the symlink unfollowed.function readSmallFile(file, maxSize) { try { const st = fs.lstatSync(file); if (st.isSymbolicLink() || st.size > maxSize) return null; return fs.readFileSync(file, "utf8"); } catch { return null; }}// parse a JSON file, or null on missing/corrupt.function readJson(file) { try { return JSON.parse(fs.readFileSync(file, "utf8")); } catch { return null; }}const cwd = d?.workspace?.current_dir || d?.cwd; const cwd = d?.workspace?.current_dir || d?.cwd; if (d?.model?.display_name) push(c.magenta(d.model.display_name)); push(on ? col(`⚡${lvl}`) : c.dim(`⚡${lvl}`)); push(on ? col(lvl) : c.dim(lvl)); // no ⚡ glyph — level word alone const exceeds = d?.exceeds_200k_tokens === true; if (exceeds || (pct != null && pct >= CONFIG.contextWarnPct)) { const shown = pct != null ? Math.round(pct) : 100; const col = exceeds || shown >= CONFIG.contextCritPct ? c.red : c.yellow; push(`${c.dim("ctx")} ${bar(shown, CONFIG.barWidth, col)} ${col(shown + "%")}`); if (pct != null) { let seg = meter("ctx", Math.round(pct), CONFIG.contextWarnPct, CONFIG.contextCritPct); // absolute size helps on 1M windows, where 10% is already 100k tokens const tok = cw.total_input_tokens ?? (cw.context_window_size ? (pct / 100) * cw.context_window_size : null); if (tok != null) seg += c.dim("·" + fmtTokens(tok)); push(seg); const col = pctColor(p, CONFIG.usageWarnPct, CONFIG.usageCritPct); let seg = `${c.dim(label)} ${bar(p, CONFIG.barWidth, col)} ${col(p + "%")}`; let seg = meter(label, p, CONFIG.usageWarnPct, CONFIG.usageCritPct); if (burnRate > 0) push(c.orange(`🔥$${burnRate.toFixed(2)}/hr`)); // icon: semantic glyph (⟳ turn / Σ session / ☾ month). slash: <num>/<type>. const fmt = (n, type, icon, color) => CONFIG.costStyle === "icon" ? color(`${icon}$${money(n)}`) : color(`$${money(n)}/${type}`); if (burnRate > 0) push(burnColor(burnRate, ` $${burnRate.toFixed(2)}/hr`)); // icon style: bright $number (emphasis) + dim trailing glyph (muted icon). // turn has no glyph (bare $num); session Σ / month ☾. slash: $num/type. const fmt = (n, type, icon) => CONFIG.costStyle === "icon" ? c.white(`$${money(n)}`) + (icon ? c.dim(icon) : "") : c.white(`$${money(n)}/${type}`); for (const line of fs.readFileSync(f, "utf8").split(/\r?\n/)) { for (const line of content.split(/\r?\n/)) { let dirty = false; // persist (disk write) only when something material changed dirty = true; dirty = true; // Session cost went backwards (counter restarted, e.g. on resume): rebaseline, // otherwise new spend is silently dropped until it exceeds the old high-water mark. if (total < (s.total ?? 0)) { s.total = 0; s.turnStart = Math.min(s.turnStart ?? total, total); s.samples = []; dirty = true; } if (delta > 0) L.monthTotal = (L.monthTotal || 0) + delta; s.samples.push([now, total]); if (delta > 0) { s.total = total; s.ts = now; s.samples.push([now, total]); if (s.samples.length > CONFIG.burnMaxSamples) s.samples = s.samples.slice(-CONFIG.burnMaxSamples); } // Prune the window in-memory every render (cheap, no disk) so even an idle // render shows a current-window rate rather than a stale one. if (s.samples.length > CONFIG.burnMaxSamples) s.samples = s.samples.slice(-CONFIG.burnMaxSamples); try { const tmp = `${file}.${process.pid}.tmp`; fs.writeFileSync(tmp, JSON.stringify(L)); fs.renameSync(tmp, file); } catch {} // Persist only when something changed — skips stringify+write+rename (the bulk // of this function's cost) on the common idle re-render path. if (dirty) { atomicWrite(file, JSON.stringify(L)); // Opportunistic GC (write-path only, so throttled to active turns): cancelled // renders leave `.cc-*.tmp` atomic-write orphans; ended sessions leave // `.cc-turn-*` markers. Sweep our own debris older than a day. try { const stale = now - 864e5; for (const f of fs.readdirSync(claudeDir)) { if (!((f.startsWith(".cc-") && f.endsWith(".tmp")) || f.startsWith(".cc-turn-"))) continue; const fp = path.join(claudeDir, f); try { if (fs.statSync(fp).mtimeMs < stale) fs.unlinkSync(fp); } catch {} } } catch {} } const key = crypto.createHash("sha1").update(repo.kind + ":" + repo.root).digest("hex").slice(0, 12); try { const tmp = `${cacheFile}.${process.pid}.tmp`; fs.writeFileSync(tmp, JSON.stringify({ ts: Date.now(), text })); fs.renameSync(tmp, cacheFile); } catch {} atomicWrite(cacheFile, JSON.stringify({ ts: Date.now(), text })); let s = col(`⎇${branch}`); let s = col(` ${branch}`); // U+E0A0 powerline branch glyph (Nerd Font)// caveman badge — terse: full→"cm", else "cm:<first-letter>"// caveman badge — "caveman:<mode>" (+ optional savings suffix) let out = c.orange(mode || "full"); let out = c.dim("caveman:") + c.accent(mode); // muted label, bright valueclipse/config.json
Deleteddeleted file mode 100644+0 / −35 text lines
{ "allowDuplicates": false, "historyFile": "clipboard_history.json", "maxHistory": 100, "logFile": "clipse.log", "themeFile": "nugu.json", "tempDir": "tmp_files", "keyBindings": { "choose": "enter", "clearSelected": "S", "down": "down", "end": "end", "filter": "/", "home": "home", "more": "?", "nextPage": "right", "prevPage": "left", "preview": " ", "quit": "q", "remove": "x", "selectDown": "ctrl+down", "selectSingle": "s", "selectUp": "ctrl+up", "togglePin": "p", "togglePinned": "tab", "up": "up", "yankFilter": "ctrl+s" }, "imageDisplay": { "type": "kitty", "scaleX": 9, "scaleY": 9, "heightCut": 2 }}clipse/nugu.json
Deleteddeleted file mode 100644+0 / −28 text lines
{ "useCustomTheme": true, "TitleFore": "#ffffff", "TitleBack": "#6F4CBC", "TitleInfo": "#3498db", "NormalTitle": "#ffffff", "DimmedTitle": "#808080", "SelectedTitle": "#FF69B4", "NormalDesc": "#808080", "DimmedDesc": "#808080", "SelectedDesc": "#FF69B4", "StatusMsg": "#2ecc71", "PinIndicatorColor": "#FFD700", "SelectedBorder": "#3498db", "SelectedDescBorder": "#3498db", "FilteredMatch": "#ffffff", "FilterPrompt": "#2ecc71", "FilterInfo": "#3498db", "FilterText": "#ffffff", "FilterCursor": "#FFD700", "HelpKey": "#999999", "HelpDesc": "#808080", "PageActiveDot": "#3498db", "PageInactiveDot": "#808080", "DividerDot": "#3498db", "PreviewedText": "#ffffff", "PreviewBorder": "#3498db"}codex/config.toml
Modified+34 / −2 text lines
[windows]sandbox = "elevated"[notice]hide_rate_limit_model_nudge = truehide_full_access_warning = true[tui]theme = "ansi"status_line = [ "model-with-reasoning", "current-dir", "project-name", "git-branch", "pull-request-number", "branch-changes", "context-used", "five-hour-limit", "weekly-limit", "context-window-size", "fast-mode", "thread-title", "task-progress",]status_line_use_colors = truesession_picker_view = "comfortable"screen_reader_detection_done = true[shell_environment_policy]inherit = "core"containers/systemd/einordner-stalwart-e2e.container
Deleteddeleted file mode 100644+0 / −30 text lines
# Podman Quadlet template for einordner Stalwart E2E.# Install with: just e2e-install# Generated unit: einordner-stalwart-e2e.service (systemd --user)[Unit]Description=einordner Stalwart E2E mail serverDocumentation=https://github.com/stalwartlabs/mail-serverAfter=network-online.targetWants=network-online.target[Container]Image=docker.io/stalwartlabs/stalwart:latestContainerName=einordner-stalwart-e2eEnvironment=STALWART_RECOVERY_ADMIN=admin:changemePublishPort=127.0.0.1:8080:8080PublishPort=127.0.0.1:1025:1025PublishPort=127.0.0.1:1143:1143PublishPort=127.0.0.1:4190:4190Volume=/home/me/.local/state/einordner/e2e/stalwart/config/config.json:/etc/stalwart/config.json:ro,ZVolume=einordner-stalwart-e2e-data:/dataWorkingDir=/dataExec=-c /etc/stalwart/config.json[Service]Restart=on-failureRestartSec=2TimeoutStartSec=120[Install]WantedBy=default.targetdesktop.symlinks
Modified+91 / −31 text lines
dprint/dprint.jsonc~/.config/dprint/dprint.jsoncclaude/settings.json~/.claude/settings.jsonclaude/statusline.js~/.claude/statusline.jsclaude/cc-statusline-hook.js~/.claude/cc-statusline-hook.jsclaude/CLAUDE.md~/.claude/CLAUDE.mdclaude/RTK.md~/.claude/RTK.mdparu/paru.conf~/.config/paru/paru.confzed~/.config/zedjj~/.config/jjglow~/.config/glowmise~/.config/misequickshell/nuguland~/.config/quickshell/nugulandsystemd/user/quickshell.service~/.config/systemd/user/quickshell.servicesystemd/user/quickshell.service~/.config/systemd/user/graphical-session.target.wants/quickshell.servicesystemd/user/session-graphical.slice.d/10-desktop-resources.conf~/.config/systemd/user/session-graphical.slice.d/10-desktop-resources.confsystemd/user/app-graphical.slice.d/10-desktop-resources.conf~/.config/systemd/user/app-graphical.slice.d/10-desktop-resources.confsystemd/user/background-graphical.slice.d/10-desktop-resources.conf~/.config/systemd/user/background-graphical.slice.d/10-desktop-resources.confsystemd/user/psd.service~/.config/systemd/user/psd.servicesystemd/user/psd.service~/.config/systemd/user/default.target.wants/psd.servicesystemd/user/work.slice~/.config/systemd/user/work.slicexdg/mimeapps.list~/.config/mimeapps.listxdg/applications/mpv-tui.desktop~/.local/share/applications/mpv-tui.desktopxdg/bin~/.local/override/binenvironment.d/60-xdg-open-gio.conf~/.config/environment.d/60-xdg-open-gio.confdocs/superpowers/plans/2026-05-30-yazi-nugu-dotfiles.md
Deleteddeleted file mode 100644+0 / −941 text lines
# Yazi Nugu Dotfiles Implementation Plan> **For agentic workers:** REQUIRED SUB-SKILL: Use /skill:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.**Goal:** Build a dotfiles-managed Yazi config that uses generated Nugu flavors, tasteful Yazi-native key overrides, and a small managed plugin set.**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.**Tech Stack:** Yazi 26.5.6, `ya pkg`, Nushell, Just, TOML, Lua, dotfiles symlink manifests.**Roadmap:** None**Phase:** Single-plan implementation---## File structureCreate or modify these files:- Create `nugu/yazi.nu`: generator from Nugu semantic palette to Yazi flavor TOML.- Modify `nugu/justfile`: add `yazi` recipe and include it in `install`.- Create `yazi/theme.toml`: selects generated Nugu flavors.- Create `yazi/yazi.toml`: minimal manager/open/preview/plugin rules.- Create `yazi/keymap.toml`: prepend-only key overrides.- Create `yazi/init.lua`: plugin setup.- Create `yazi/package.toml`: generated by `ya pkg add`; plugin lock source of truth.- Create `yazi/flavors/nugu-dark.yazi/flavor.toml`: generated artifact.- Create `yazi/flavors/nugu-light.yazi/flavor.toml`: generated artifact.- Modify `.gitignore`: ignore installed `yazi/plugins/` artifacts.- Modify `desktop.symlinks`, `fedora.symlinks`, `x230.symlinks`: map `yazi` to `~/.config/yazi`.Do not touch or add `yazi/plugins/`. Existing untracked `pi/research/**` noise must not be staged.---### Task 1: Add dotfiles ownership, ignore rules, and live symlink**Files:**- Modify: `/home/me/Workspace/dotfiles/.gitignore`- Modify: `/home/me/Workspace/dotfiles/desktop.symlinks`- Modify: `/home/me/Workspace/dotfiles/fedora.symlinks`- Modify: `/home/me/Workspace/dotfiles/x230.symlinks`- Create: `/home/me/Workspace/dotfiles/yazi/.gitkeep` temporarily if needed before config files exist- Live target: `/home/me/.config/yazi`- [ ] **Step 1: Add Yazi installed plugin ignore rule**Append this block to `/home/me/Workspace/dotfiles/.gitignore` near the other local runtime/package caches:```gitignore# Yazi package manager installs plugin repos here; package.toml is source of truth.yazi/plugins/```- [ ] **Step 2: Add Yazi to `desktop.symlinks`**In `/home/me/Workspace/dotfiles/desktop.symlinks`, insert this pair after the existing `pi` mapping:```textyazi~/.config/yazi```The beginning of the file should become:```textforgejo-cli~/.config/forgejo-clipi~/.piyazi~/.config/yaziNotes~/Notes```- [ ] **Step 3: Add Yazi to `fedora.symlinks`**In `/home/me/Workspace/dotfiles/fedora.symlinks`, insert this pair after the `Notes` mapping:```textyazi~/.config/yazi```The beginning of the file should become:```textNotes~/Notesyazi~/.config/yazigit/gitconfig~/.config/git/config```- [ ] **Step 4: Add Yazi to `x230.symlinks`**In `/home/me/Workspace/dotfiles/x230.symlinks`, insert this pair after the `Notes` mapping:```textyazi~/.config/yazi```The beginning of the file should become:```textNotes~/Notesyazi~/.config/yazigit/gitconfig~/.config/git/config```- [ ] **Step 5: Create Yazi directory skeleton**Run:```bashcd /home/me/Workspace/dotfilesmkdir -p yazi/flavors/nugu-dark.yazi yazi/flavors/nugu-light.yazitouch yazi/.gitkeep```Expected: directories exist. Verify:```bashtest -d yazi/flavors/nugu-dark.yazi && test -d yazi/flavors/nugu-light.yazi && test -f yazi/.gitkeep && echo ok```Expected output:```textok```- [ ] **Step 6: Back up existing live Yazi config now**Run:```bashif [ -e /home/me/.config/yazi ] && [ ! -L /home/me/.config/yazi ]; then mv /home/me/.config/yazi /home/me/.config/yazi.noctalia-backup-$(date +%Y%m%d%H%M%S)fi```Expected: existing non-symlink config is moved aside; no output on success.- [ ] **Step 7: Bootstrap live symlink now**Run:```bashcd /home/me/Workspace/dotfilesjava bootstripper.java bootstrap```Expected: bootstrap exits 0 and creates `/home/me/.config/yazi` symlink.- [ ] **Step 8: Verify live symlink target**Run:```bashrealpath /home/me/.config/yazi```Expected output:```text/home/me/Workspace/dotfiles/yazi```- [ ] **Step 9: Run dotfiles manifest check**Run:```bashcd /home/me/Workspace/dotfilesjava bootstripper.java check```Expected: `OK bootstripper check passed.`- [ ] **Step 10: Commit ownership changes**Run:```bashcd /home/me/Workspace/dotfilesgit add .gitignore desktop.symlinks fedora.symlinks x230.symlinks yazi/.gitkeepgit commit -m "chore: manage yazi dotfiles"```Expected: commit succeeds. `yazi/.gitkeep` is removed in Task 3 after real config files exist.---### Task 2: Add Nugu-to-Yazi flavor generator**Files:**- Create: `/home/me/Workspace/dotfiles/nugu/yazi.nu`- Modify: `/home/me/Workspace/dotfiles/nugu/justfile`- [ ] **Step 1: Create `nugu/yazi.nu`**Write this file to `/home/me/Workspace/dotfiles/nugu/yazi.nu`:```nuuse palette.nu# Generate a Yazi flavor.toml from the Nugu semantic palette.export def flavor [mode: string] { let nugu = (palette nugu $mode) let p = $nugu.palette let theme = { mgr: { cwd: { fg: $p.content.normal } find_keyword: { fg: $p.content.accent, bold: true, italic: true, underline: true } find_position: { fg: $p.content.accent, bold: true } symlink_target: { fg: $p.content.minor } marker_copied: { fg: $p.content.focus, bg: $p.content.focus } marker_cut: { fg: $p.warning, bg: $p.warning } marker_marked: { fg: $p.content.accent, bg: $p.content.accent } marker_selected: { fg: $p.ui.important_local, bg: $p.ui.important_local } count_copied: { fg: $p.content.backdrop, bg: $p.content.focus, bold: true } count_cut: { fg: $p.content.backdrop, bg: $p.warning, bold: true } count_selected: { fg: $p.ui.backdrop, bg: $p.ui.important_local, bold: true } border_symbol: "│" border_style: { fg: $p.ui.unfocus } } status: { overall: { fg: $p.ui.normal, bg: $p.ui.backdrop } sep_left: { open: "", close: "" } sep_right: { open: "", close: "" } perm_type: { fg: $p.content.important_global } perm_read: { fg: $p.content.focus } perm_write: { fg: $p.warning } perm_exec: { fg: $p.error } perm_sep: { fg: $p.content.minor } progress_label: { fg: $p.content.normal, bold: true } progress_normal: { fg: $p.ui.accent, bg: $p.ui.backdrop } progress_error: { fg: $p.error, bg: $p.ui.backdrop } } mode: { normal_main: { fg: $p.ui.backdrop, bg: $p.ui.accent, bold: true } normal_alt: { fg: $p.ui.normal, bg: $p.ui.backdrop } select_main: { fg: $p.ui.backdrop, bg: $p.ui.important_local, bold: true } select_alt: { fg: $p.ui.normal, bg: $p.ui.backdrop } unset_main: { fg: $p.content.backdrop, bg: $p.warning, bold: true } unset_alt: { fg: $p.ui.normal, bg: $p.ui.backdrop } } tabs: { active: { fg: $p.ui.backdrop, bg: $p.ui.accent, bold: true } inactive: { fg: $p.ui.minor, bg: $p.ui.backdrop } sep_inner: { open: "", close: "" } sep_outer: { open: "", close: "" } } which: { cols: 3 mask: { bg: $p.ui.backdrop } cand: { fg: $p.ui.accent, bold: true } rest: { fg: $p.ui.minor } desc: { fg: $p.ui.normal } separator: " → " separator_style: { fg: $p.ui.minor } } input: { border: { fg: $p.ui.unfocus } title: { fg: $p.ui.accent, bold: true } value: { fg: $p.content.normal } selected: { fg: $p.content.backdrop, bg: $p.content.focus } } confirm: { border: { fg: $p.warning } title: { fg: $p.warning, bold: true } body: { fg: $p.content.normal } list: { fg: $p.content.normal } btn_yes: { fg: $p.content.backdrop, bg: $p.error, bold: true } btn_no: { fg: $p.ui.backdrop, bg: $p.ui.focus, bold: true } btn_labels: ["yes", "no"] } spot: { border: { fg: $p.ui.unfocus } title: { fg: $p.ui.accent, bold: true } tbl_col: { fg: $p.content.normal } tbl_cell: { fg: $p.content.backdrop, bg: $p.content.focus } } pick: { border: { fg: $p.ui.unfocus } active: { fg: $p.ui.backdrop, bg: $p.ui.focus, bold: true } inactive: { fg: $p.ui.normal } } cmp: { border: { fg: $p.ui.unfocus } active: { fg: $p.ui.backdrop, bg: $p.ui.focus, bold: true } inactive: { fg: $p.ui.normal } } tasks: { border: { fg: $p.ui.unfocus } title: { fg: $p.ui.accent, bold: true } hovered: { fg: $p.content.focus, bold: true } } help: { on: { fg: $p.ui.accent, bold: true } run: { fg: $p.content.important_local } desc: { fg: $p.content.normal } hovered: { fg: $p.ui.backdrop, bg: $p.ui.focus, bold: true } footer: { fg: $p.ui.backdrop, bg: $p.ui.accent, bold: true } } notify: { title_info: { fg: $p.info, bold: true } title_warn: { fg: $p.warning, bold: true } title_error: { fg: $p.error, bold: true } } filetype: { rules: [ { mime: "image/*", fg: $p.content.focus } { mime: "{audio,video}/*", fg: $p.content.important_local } { mime: "application/{zip,rar,7z*,tar,gzip,xz,zstd,bzip*,lzma,compress,archive,cpio,arj,xar,ms-cab*}", fg: $p.content.accent } { mime: "application/{pdf,doc,rtf}", fg: $p.content.important_global } { mime: "*", is: "orphan", fg: $p.content.backdrop, bg: $p.error, bold: true } { mime: "application/*exec*", fg: $p.error } { url: "*/", fg: $p.ui.accent, bold: true } { url: "*", fg: $p.content.normal } ] } git: { unknown: { fg: $p.content.minor } modified: { fg: $p.warning, bold: true } added: { fg: $p.content.focus, bold: true } untracked: { fg: $p.content.accent, bold: true } ignored: { fg: $p.content.minor } deleted: { fg: $p.error, bold: true } updated: { fg: $p.warning, bold: true } clean: { fg: $p.content.minor } unknown_sign: "" modified_sign: "M " added_sign: "A " untracked_sign: "? " ignored_sign: "I " deleted_sign: "D " updated_sign: "U " clean_sign: "" } } $theme | to toml}```- [ ] **Step 2: Check the new Nushell module parses**Run:```bashcd /home/me/Workspace/dotfiles/nuguopen yazi.nu | nu-check --as-module --debug yazi.nu```Expected: `nu-check` exits 0.- [ ] **Step 3: Add `yazi` recipe to `nugu/justfile`**Add this recipe after the `ghostty` recipe:```justyazi: build rm --force --recursive {{output}}/yazi mkdir {{output}}/yazi mkdir {{output}}/yazi/nugu-dark.yazi mkdir {{output}}/yazi/nugu-light.yazi use yazi.nu; yazi flavor dark | save --raw {{output}}/yazi/nugu-dark.yazi/flavor.toml use yazi.nu; yazi flavor light | save --raw {{output}}/yazi/nugu-light.yazi/flavor.toml mkdir ../yazi/flavors mkdir ../yazi/flavors/nugu-dark.yazi mkdir ../yazi/flavors/nugu-light.yazi cp {{output}}/yazi/nugu-dark.yazi/flavor.toml ../yazi/flavors/nugu-dark.yazi/flavor.toml cp {{output}}/yazi/nugu-light.yazi/flavor.toml ../yazi/flavors/nugu-light.yazi/flavor.toml```- [ ] **Step 4: Include Yazi in Nugu install recipe**Change the final recipe in `/home/me/Workspace/dotfiles/nugu/justfile` from:```justinstall: helix wezterm ghostty```to:```justinstall: helix wezterm ghostty yazi```- [ ] **Step 5: Generate Yazi flavors**Run:```bashcd /home/me/Workspace/dotfiles/nugujust yazi```Expected files:```text/home/me/Workspace/dotfiles/yazi/flavors/nugu-dark.yazi/flavor.toml/home/me/Workspace/dotfiles/yazi/flavors/nugu-light.yazi/flavor.toml```Verify:```bashtest -s /home/me/Workspace/dotfiles/yazi/flavors/nugu-dark.yazi/flavor.toml && \test -s /home/me/Workspace/dotfiles/yazi/flavors/nugu-light.yazi/flavor.toml && \echo ok```Expected output:```textok```- [ ] **Step 6: Commit Nugu generator**Run:```bashcd /home/me/Workspace/dotfilesgit add nugu/yazi.nu nugu/justfile yazi/flavors/nugu-dark.yazi/flavor.toml yazi/flavors/nugu-light.yazi/flavor.tomlgit commit -m "feat: generate yazi nugu flavors"```Expected: commit succeeds.---### Task 3: Add base Yazi config files**Files:**- Create: `/home/me/Workspace/dotfiles/yazi/theme.toml`- Create: `/home/me/Workspace/dotfiles/yazi/yazi.toml`- Create: `/home/me/Workspace/dotfiles/yazi/keymap.toml`- Create: `/home/me/Workspace/dotfiles/yazi/init.lua`- [ ] **Step 1: Create `yazi/theme.toml`**Write this file:```toml[flavor]dark = "nugu-dark"light = "nugu-light"```- [ ] **Step 2: Create `yazi/yazi.toml`**Write this file:```toml# A TOML linter such as Tombi can use this schema to validate your config.#:schema https://yazi-rs.github.io/schemas/yazi.json[mgr]show_hidden = truesort_by = "natural"sort_dir_first = truelinemode = "none"[opener]edit = [ { run = 'nvim %s', desc = "nvim", block = true, for = "unix" },]play = [ { run = 'mpv %s', desc = "mpv", orphan = true, for = "unix" },]open = [ { run = 'xdg-open %s1', desc = "Open", for = "linux" },]extract = [ { run = 'ouch d -y %s', desc = "Extract here with ouch", for = "unix" },][open]prepend_rules = [ { mime = "text/*", use = [ "edit", "reveal" ] }, { mime = "application/{json,ndjson,javascript,wine-extension-ini}", use = [ "edit", "reveal" ] },][plugin]prepend_fetchers = [ { url = "*", run = "git", group = "git" }, { url = "*/", run = "git", group = "git" },]prepend_previewers = [ { url = "*.md", mime = "text/markdown", run = 'piper -- CLICOLOR_FORCE=1 glow -w=$w -s=dark "$1"' }, { mime = "application/{*zip,tar,bzip2,7z*,rar,xz,zstd,java-archive}", run = "ouch" },]append_previewers = [ { url = "*", run = 'piper -- hexyl --border=none --terminal-width=$w "$1"' },]```- [ ] **Step 3: Create `yazi/keymap.toml`**Write this file:```toml# A TOML linter such as Tombi can use this schema to validate your config.#:schema https://yazi-rs.github.io/schemas/keymap.json[[mgr.prepend_keymap]]on = "l"run = "plugin smart-enter"desc = "Enter directory or open file"[[mgr.prepend_keymap]]on = "<Enter>"run = "plugin smart-enter"desc = "Enter directory or open file"[[mgr.prepend_keymap]]on = "p"run = "plugin smart-paste"desc = "Paste into hovered directory or CWD"[[mgr.prepend_keymap]]on = "f"run = "plugin smart-filter"desc = "Smart filter"[[mgr.prepend_keymap]]on = "T"run = "plugin toggle-pane min-preview"desc = "Show or hide preview pane"[[mgr.prepend_keymap]]on = "F"run = "plugin toggle-pane max-preview"desc = "Maximize or restore preview pane"[[mgr.prepend_keymap]]on = [ "c", "m" ]run = "plugin chmod"desc = "Chmod selected files"[[mgr.prepend_keymap]]on = [ "c", "D" ]run = "plugin diff"desc = "Diff selected file with hovered file"[[mgr.prepend_keymap]]on = "!"for = "unix"run = 'shell "$SHELL" --block'desc = "Open shell here"[[mgr.prepend_keymap]]on = [ "g", "w" ]run = "cd ~/Workspace"desc = "Go ~/Workspace"[[mgr.prepend_keymap]]on = [ "g", "k" ]run = "cd ~/Workspace/dotfiles"desc = "Go dotfiles"[[mgr.prepend_keymap]]on = [ "g", "n" ]run = "cd ~/Notes"desc = "Go notes"[[mgr.prepend_keymap]]on = [ "g", "y" ]run = "cd ~/.config/yazi"desc = "Go Yazi config"[[mgr.prepend_keymap]]on = [ "g", "r" ]run = 'shell -- ya emit cd "$(git rev-parse --show-toplevel 2>/dev/null || jj root 2>/dev/null || pwd)"'desc = "Go repository root"[[input.prepend_keymap]]on = "<Esc>"run = "close"desc = "Cancel input"```- [ ] **Step 4: Create `yazi/init.lua`**Write this file:```luarequire("full-border"):setup { type = ui.Border.PLAIN }require("git"):setup { order = 1500 }require("yaziline"):setup { separator_style = "liney" }```- [ ] **Step 5: Remove temporary `yazi/.gitkeep` if it exists**Run:```bashcd /home/me/Workspace/dotfilesrm -f yazi/.gitkeep```Expected: command exits 0.- [ ] **Step 6: Commit base Yazi config**Run:```bashcd /home/me/Workspace/dotfilesgit add yazi/theme.toml yazi/yazi.toml yazi/keymap.toml yazi/init.luagit commit -m "feat: add yazi config"```Expected: commit succeeds.---### Task 4: Install and lock Yazi plugins**Files:**- Create: `/home/me/Workspace/dotfiles/yazi/package.toml`- Generated but ignored: `/home/me/Workspace/dotfiles/yazi/plugins/`- [ ] **Step 1: Install selected plugins with `ya pkg`**Run:```bashcd /home/me/.config/yaziya pkg add \ yazi-rs/plugins:full-border \ yazi-rs/plugins:toggle-pane \ yazi-rs/plugins:smart-enter \ yazi-rs/plugins:smart-filter \ yazi-rs/plugins:smart-paste \ yazi-rs/plugins:git \ yazi-rs/plugins:chmod \ yazi-rs/plugins:diff \ yazi-rs/plugins:piper \ ndtoan96/ouch \ llanosrocas/yaziline```Expected:- `/home/me/Workspace/dotfiles/yazi/package.toml` exists through the live symlink.- `/home/me/Workspace/dotfiles/yazi/plugins/` exists and is ignored.- The command exits 0.- [ ] **Step 2: Verify installed plugin dirs are ignored**Run:```bashcd /home/me/Workspace/dotfilesgit status --short yazi/package.toml yazi/plugins```Expected output includes `?? yazi/package.toml` and does not list individual files under `yazi/plugins/`.- [ ] **Step 3: Verify package lock lists all plugin deps**Run:```bashcd /home/me/Workspace/dotfilesfor dep in \ 'yazi-rs/plugins:full-border' \ 'yazi-rs/plugins:toggle-pane' \ 'yazi-rs/plugins:smart-enter' \ 'yazi-rs/plugins:smart-filter' \ 'yazi-rs/plugins:smart-paste' \ 'yazi-rs/plugins:git' \ 'yazi-rs/plugins:chmod' \ 'yazi-rs/plugins:diff' \ 'yazi-rs/plugins:piper' \ 'ndtoan96/ouch' \ 'llanosrocas/yaziline'; do grep -F "use = \"$dep\"" yazi/package.toml >/dev/null || { echo "missing $dep"; exit 1; }doneecho ok```Expected output:```textok```- [ ] **Step 4: Commit package lock**Run:```bashcd /home/me/Workspace/dotfilesgit add yazi/package.tomlgit commit -m "feat: lock yazi plugins"```Expected: commit succeeds and `yazi/plugins/` remains untracked/ignored.---### Task 5: Validate generated Nugu and Yazi config**Files:**- Verify: `/home/me/Workspace/dotfiles/nugu/yazi.nu`- Verify: `/home/me/Workspace/dotfiles/yazi/*.toml`- Verify: `/home/me/Workspace/dotfiles/yazi/init.lua`- [ ] **Step 1: Run Nugu checks**Run:```bashcd /home/me/Workspace/dotfiles/nugujust check```Expected: `just check` exits 0 and reports Nugu color contrast results.- [ ] **Step 2: Regenerate Yazi flavors and check drift**Run:```bashcd /home/me/Workspace/dotfiles/nugujust yazicd /home/me/Workspace/dotfilesgit diff -- yazi/flavors/nugu-dark.yazi/flavor.toml yazi/flavors/nugu-light.yazi/flavor.toml```Expected: no diff.- [ ] **Step 3: Validate Yazi can print debug config**Run:```bashyazi --debug >/tmp/yazi-debug.txthead -40 /tmp/yazi-debug.txt```Expected:- Command exits 0.- Output contains Yazi debug information.- No TOML parse error appears.- [ ] **Step 4: Verify plugin restore from lock works**Run:```bashcd /home/me/.config/yaziya pkg install```Expected: command exits 0.- [ ] **Step 5: Run dotfiles pre-commit check**Run:```bashcd /home/me/Workspace/dotfilesjust pre-commit```Expected: command exits 0 with no leaked secrets or manifest failures.- [ ] **Step 6: Commit validation fixups if any**If any validation step required fixes, run:```bashcd /home/me/Workspace/dotfilesgit 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.tomlgit commit -m "fix: validate yazi nugu config"```Expected: commit succeeds only if there were fixups. If there were no changes, skip this step.---### Task 6: Smoke-test live config interactively**Files:**- Live target: `/home/me/.config/yazi`- Source: `/home/me/Workspace/dotfiles/yazi`- [ ] **Step 1: Verify live config is already symlinked**Run:```bashrealpath /home/me/.config/yazi```Expected output:```text/home/me/Workspace/dotfiles/yazi```- [ ] **Step 2: Install locked plugins in live config**Run:```bashcd /home/me/.config/yaziya pkg install```Expected: command exits 0.- [ ] **Step 3: Launch Yazi smoke session**Run:```bashYAZI_LOG=debug yazi /home/me/Workspace/dotfiles```In Yazi, verify manually:- Hidden files are visible immediately.- `~` or `<F1>` opens help and custom bindings appear.- `l` and `<Enter>` enter dirs/open files through smart-enter.- `p` runs smart-paste behavior.- `f` opens smart-filter.- `T` hides/shows preview.- `F` maximizes/restores preview.- `c m` opens chmod plugin.- `c D` opens diff plugin when a file is selected and another is hovered.- `!` opens `$SHELL` and returns to Yazi when the shell exits.- `g w`, `g k`, `g n`, `g y`, `g r` navigate to the expected directories.- Markdown files preview through glow.- Archives preview through ouch.- Git signs appear in the file list inside the dotfiles repo.- Yaziline statusline uses liney separators.- Plain full border is visible.Quit with `q`.- [ ] **Step 4: Inspect Yazi log if smoke test fails**Run:```bashtail -200 /home/me/.local/state/yazi/yazi.log```Expected: no Lua stack traces for configured plugins after any needed fixes.- [ ] **Step 5: Commit smoke-test fixes if any**If the smoke test required config changes, run:```bashcd /home/me/Workspace/dotfilesgit 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/justfilegit commit -m "fix: smoke test yazi config"```Expected: commit succeeds only if there were fixes. If there were no changes, skip this step.---### Task 7: Final repository verification**Files:**- Verify all changed files from previous tasks.- [ ] **Step 1: Check concise Git status**Run:```bashcd /home/me/Workspace/dotfilesgit 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```Expected: no unstaged changes for these paths. `yazi/plugins/` must not appear.- [ ] **Step 2: Run full dotfiles check**Run:```bashcd /home/me/Workspace/dotfilesjust check```Expected: command exits 0.- [ ] **Step 3: Record final notes**If all validation passes, add a short note to the final response:```textImplemented 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.```No file change is required for this step.docs/superpowers/specs/2026-05-30-yazi-nugu-dotfiles-design.md
Deleteddeleted file mode 100644+0 / −261 text lines
# Yazi Nugu dotfiles designDate: 2026-05-30## GoalMake 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.## Non-goals- Do not vendor third-party plugin repositories into dotfiles.- Do not add bookmarks or session/autosession plugins.- Do not replace Yazi defaults wholesale.- Do not add a Space leader layer; keep Space for selection.- Do not implement Jujutsu (`jj`) Yazi plugin support in v1.- Do not add heavyweight statusline alternatives beyond the chosen minimal statusline plugin.## Current context- Live Yazi config currently lives in `~/.config/yazi` and contains only: - `theme.toml`, selecting the `noctalia` flavor. - `flavors/noctalia.yazi/flavor.toml`.- Dotfiles do not currently manage `~/.config/yazi`.- Nugu already provides generated themes for Ghostty, Helix, and WezTerm.- Existing dotfiles favor declarative config, Nushell automation, generated theme artifacts, and symlink manifests.- 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`.## Architecture### Dotfiles ownershipCreate a new `yazi/` directory in the dotfiles repository. It will be symlinked to `~/.config/yazi` through the host symlink manifests, consistent with other applications.Planned files:```textyazi/├── theme.toml├── yazi.toml├── keymap.toml├── init.lua├── package.toml└── flavors/ ├── nugu-dark.yazi/ │ └── flavor.toml └── nugu-light.yazi/ └── flavor.toml```The symlink manifest should map:```textyazi~/.config/yazi```Linux 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.### Plugin package hygieneYazi plugins will be managed with `ya pkg`. The committed source of truth is `yazi/package.toml`, not the installed plugin directories.- Commit `package.toml`.- Ignore `yazi/plugins/`.- Do not vendor plugin repositories.- Restore plugins on a new machine with `ya pkg install`.The generated Nugu flavors are not third-party plugin clutter. They are first-party generated artifacts and should be committed.### Nugu integrationAdd a `nugu/yazi.nu` generator that maps Nugu palette roles to Yazi's flavor schema.Extend `nugu/justfile` with a `yazi` recipe that:1. Builds or reads the Nugu palette.2. Generates dark and light flavor files under `output/yazi/` or directly writes `../yazi/flavors/nugu-{dark,light}.yazi/flavor.toml`.3. Keeps generated Yazi flavor output reproducible.Extend `nugu/justfile install` to include the Yazi generation step.`yazi/theme.toml` will select Nugu:```toml[flavor]dark = "nugu-dark"light = "nugu-light"```Yazi will use separate generated Nugu dark and light flavors so terminal light/dark switching has matching colors.## Theme mappingThe Yazi flavor should use Nugu semantic palette roles rather than raw arbitrary colors.Suggested role mapping:- App/status backgrounds: `ui.backdrop`.- Main text: `content.normal`.- File manager borders: `ui.unfocus` or `ui.minor`.- Active UI elements: `ui.accent` and `ui.important_local`.- Selected counts/markers: `content.focus` and `ui.important_local`.- Warnings/errors: `warning` and `error`.- Git signs: - modified: `warning` - added: `content.focus` - untracked: `content.accent` - deleted: `error` - ignored: `content.minor`The 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.## Yazi behavior config`yazi/yazi.toml` should be minimal and override defaults only where the dotfiles imply a preference.Planned manager settings:```toml[mgr]show_hidden = truesort_by = "natural"sort_dir_first = truelinemode = "none"```Use default pane ratio `[1, 4, 3]` unless testing shows preview feels cramped.Preview/opening behavior:- Keep built-in JSON, PDF, image, video, and archive previews where they work well.- Use `piper` selectively for tools already present: - Markdown preview via `glow`. - Fallback binary preview via `hexyl`.- Use `ouch` for archive preview/extract behavior where it improves over defaults.- Use `nvim` as blocking editor.- Use `mpv` for media.- Use `xdg-open` for general open behavior.Git integration:- Configure `git.yazi` fetchers for files and directories.- Do not configure `vcs-files` in v1.- Do not attempt inline `jj` status in v1.## Lua initialization`yazi/init.lua` should only initialize selected plugins and avoid custom UI rewrites.Planned setup:```luarequire("full-border"):setup { type = ui.Border.PLAIN }require("git"):setup { order = 1500 }require("yaziline"):setup { separator_style = "liney" }```Additional plugin setup can be added only if required by the chosen plugin's documented API. Avoid overriding core Yazi UI build functions.## Keymap designUse `[[mgr.prepend_keymap]]` only. Preserve Yazi defaults and add targeted improvements.Principles:- Space remains selection.- `g`, `t`, `c`, and existing Yazi prefix groups remain native Yazi-style groups.- No full keymap replacement.- Avoid terminal-fragile Alt bindings when a normal sequence is available.Planned bindings:| Key | Action || --- | --- || `l` | `plugin smart-enter` || `<Enter>` | `plugin smart-enter` || `p` | `plugin smart-paste` || `f` | `plugin smart-filter` || `T` | `plugin toggle-pane min-preview` || `F` | `plugin toggle-pane max-preview` || `c m` | `plugin chmod` || `c D` | `plugin diff` || `!` | blocking `$SHELL` in current directory || `g w` | `cd ~/Workspace` || `g k` | `cd ~/Workspace/dotfiles` || `g n` | `cd ~/Notes` || `g y` | `cd ~/.config/yazi` || `g r` | change to repo root using `git rev-parse --show-toplevel` or `jj root` |Input behavior:- Override input `<Esc>` to close the input immediately, avoiding Yazi input's vi-normal mode when the intent is simple cancellation.## Plugin setInstall and lock these plugins in `yazi/package.toml`:- `yazi-rs/plugins:full-border`- `yazi-rs/plugins:toggle-pane`- `yazi-rs/plugins:smart-enter`- `yazi-rs/plugins:smart-filter`- `yazi-rs/plugins:smart-paste`- `yazi-rs/plugins:git`- `yazi-rs/plugins:chmod`- `yazi-rs/plugins:diff`- `yazi-rs/plugins:piper`- `ndtoan96/ouch`- `llanosrocas/yaziline`Deferred plugins and integrations:- Custom `jj` plugin.- `vcs-files` and `git-files`.- Bookmark plugins.- Session/autosession plugins.- `lazygit` plugin until the `lazygit` binary is installed.- `starship`, `yatline`, `simple-status`, and other statusline alternatives.- `mount`, `sudo`, and clipboard plugins.## Validation strategyFunctional validation:1. Generate Nugu Yazi flavor.2. Run `ya pkg install` from the Yazi config directory.3. Run `yazi --debug` to inspect merged config and schema issues.4. Launch Yazi with `YAZI_LOG=debug` if plugin errors occur.5. Check keybindings in Yazi help.6. Smoke-test: - hidden files visible by default - `l`/Enter smart-enter behavior - `p` smart-paste behavior - `f` smart-filter behavior - `T` and `F` pane behavior - `c m` chmod prompt - `c D` diff behavior - Markdown preview via glow - archive handling via ouch - git signs in a Git repoRepo validation:1. Ensure `yazi/plugins/` is ignored.2. Ensure `yazi/flavors/nugu-dark.yazi/flavor.toml` and `yazi/flavors/nugu-light.yazi/flavor.toml` are tracked.3. Ensure symlink manifest tests still pass.4. Ensure regenerating Nugu Yazi flavor produces no unexpected diff.## Implementation phases1. Add Yazi dotfiles skeleton and symlink manifest entries.2. Add Nugu Yazi generator and generated flavor.3. Add Yazi config files (`theme.toml`, `yazi.toml`, `keymap.toml`, `init.lua`).4. Install and lock selected plugins via `ya pkg`.5. Add ignore rules for installed plugin artifacts.6. Validate with Yazi, Nugu generation, and dotfiles checks.## Open follow-ups after v1- Add a local custom Yazi plugin for `jj` changed files or inline status signs.- Consider adding a `just yazi` or root-level dotfiles recipe for Yazi validation.- Consider adding `lazygit` integration if the binary is installed later.dprint/dprint.jsonc
Addednew file mode 100644+63 / −0 text lines
{ "typescript": { }, "json": { }, "markdown": { }, "toml": { }, "dockerfile": { }, "ruff": { }, "gofumpt": { }, "malva": { }, "markup": { }, "yaml": { }, "sql": { }, "exec": { "cwd": "${configDir}", "commands": [ { "command": "rustfmt", "exts": ["rs"] }, { "command": "clang-format", "exts": ["c", "cc", "cpp", "cxx", "h", "hpp", "hxx", "m", "mm"] }, { "command": "shfmt", "exts": ["sh", "bash"] }, { "command": "zig fmt --stdin", "exts": ["zig"] } ] }, "excludes": [ "**/node_modules", "**/*-lock.json" ], "plugins": [ "npm:@dprint/typescript@0.96.1", "npm:@dprint/json@0.24.0", "npm:@dprint/markdown@0.24.0", "npm:@dprint/toml@0.8.0", "npm:@dprint/dockerfile@0.6.0", "npm:@dprint/ruff@0.8.8", "npm:@jakebailey/dprint-plugin-gofumpt@0.0.18", "npm:dprint-plugin-malva@0.16.0", "npm:dprint-plugin-markup@0.27.3", "npm:dprint-plugin-yaml@0.6.0", "npm:lax-sql@0.3.0", "npm:@dprint/exec@0.7.3/plugin.json@704701df449dd7e942a71144773778ac529d68c2e4657bfc236d393b898b9a67" ]}enable_user_services.nu
Deleteddeleted file mode 100644+0 / −33 text lines
if ($nu.os-info.name != linux) { return}const services = [ [profile-sync-daemon psd psd.service] [pueued pueued pueued.service] [hypridle hypridle hypridle.service] [hyprsunset hyprsunset hyprsunset.service] [hyprpolkitagent /usr/lib/hyprpolkitagent/hyprpolkitagent hyprpolkitagent.service] [mako mako mako.service] [cliphist cliphist cliphist.service] [wl-clip-persist wl-clip-persist wl-clip-persist.service] [wezterm-mux-server wezterm-mux-server wezterm-mux-server.service] [nugu-theme nu nugu-theme.service] [ironbar ironbar ironbar.service] [ironbar-workspaces python ironbar-workspaces.service]]$services | each { | service | let name = $service.0 let binary = $service.1 let service_name = $service.2 let found = if ($binary | str starts-with "/") { $binary | path exists } else { which $binary | is-not-empty } if $found { print $"Found program ($name). Enabling service now." systemctl --user enable --now $service_name null }}nullenvironment.d/60-xdg-open-gio.conf
Addednew file mode 100644+3 / −0 text lines
fuzzel/fuzzel.ini
Deleteddeleted file mode 100644+0 / −25 text lines
# Fuzzel Configuration# See: https://codeberg.org/dnkl/fuzzel#configuration# ~/.config/fuzzel/fuzzel.ini[main]width=69prompt=" "layer=overlayanchor=centerlines=8terminal=weztermfont=Monaspace Krypton Var:style=Regular:size=24use-bold=truedpi-aware=auto# TODO: nugu[colors]background=2e3440fftext=eceff4ffselection=4c566affselection-text=d8dee9ffborder=88c0d0ff[border]width=4gh/hosts.yml
ModifiedBinary size (old → new): 118 → 121 bytes.
ghostty/TODO.md
Deleteddeleted file mode 100644+0 / −59 text lines
# Ghostty Migration TODOFeatures from wezterm config not yet ported. Check off as ghostty adds support.## Blocked: Needs Ghostty Scripting API (#2353)- [ ] **AI shell integration** — requires scrollback access from external script. Wezterm: `pane:get_lines_as_text()` → curl to z.ai API → `pane:send_text()`. Ghostty has no equivalent on Linux. macOS has AppleScript (preview).- [ ] **Zoxide workspace switcher** — requires PromptInputLine equivalent + mux API. Wezterm: `PromptInputLine` → fuzzy picker combining zoxide + workspaces → `SwitchToWorkspace`. Workaround: use a nushell keybinding that calls zoxide directly via fzf/builtin picker.- [ ] **Dynamic status bar** — requires per-window state + formatting API. Wezterm: `update-status` event → time, battery, AI status, leader indicator, workspace name. Ghostty: title only. No custom formatted status bar.- [ ] **Rotating panes** — no `rotate_panes` equivalent. Wezterm: `RotatePanes 'CounterClockwise'` / `RotatePanes 'Clockwise'`. Ghostty has `equalize_splits` but no rotation.## Blocked: Needs Ghostty Config API- [ ] **Presentation mode** — requires saving/restoring per-surface font size. Wezterm: toggles fullscreen + doubles font + sets DemiBold weight, then restores. Ghostty has `chain=` + `set_font_size` + `toggle_fullscreen` but no state restore. Possible workaround: write a script that swaps config files and reloads.- [ ] **Per-host config** — currently using `config-file = ?host-desktop`. Wezterm: `wez.hostname()` → dynamic require. Ghostty: static `config-file` directive. Needs manual per-host file or symlinks.## Blocked: Ghostty Philosophy- [ ] **Process icons in tab titles** — ghostty doesn't map process→nerdfont icons. Wezterm: `icons.lua` maps 100+ process names to nerdfont glyphs. Ghostty sets tab title from terminal title only.- [ ] **Mouse 4-click semantic zone selection** — no ghostty equivalent. Wezterm: `SelectTextAtMouseCursor 'SemanticZone'` on 4 clicks.## Not Ported: Low Priority- [ ] **Battery display in status** — ghostty has no battery API. Use external widget.- [ ] **Quick select** — ghostty has `quick_select` action but no customization of alphabets/matches yet.- [ ] **Char select** — ghostty has no `CharSelect` equivalent. Use `toggle_command_palette` instead.- [ ] **Debug overlay** — ghostty has `inspector:toggle` (close equivalent).- [ ] **Workspace "dotfiles" auto-open** — wezterm `gui-startup` spawns dotfiles workspace on launch. Ghostty has `window-save-state = always` which partially replaces this.## New Capabilities (not in wezterm)- [x] `global:` quick terminal — system-wide terminal toggle- [x] Custom GLSL shaders — visual effects (bloom, cursor smear, etc.)- [x] `performable:` keybinds — context-aware bindings that don't shadow nvim- [x] `chain=` actions — multiple actions per keypress- [x] Key table stacking — nested modal modes- [x] Click-to-move cursor in nushell prompts (native, no config needed)ghostty/config
Modified+8 / −52 text lines
font-size = 13# ── Font ──────────────────────────────────────────────────────────────────────font-family = "IBM Plex Mono"font-size = 16# Bold italic: Monaspace Xenon Var (for comments in editors)font-family-bold-italic = "Monaspace Xenon Var"font-style-bold-italic = "Bold Italic"# Italic: VictorMono (for string values, gives a special touch)font-family-italic = "VictorMono"font-style-italic = "Italic"# ── Window ────────────────────────────────────────────────────────────────────window-padding-x = 0window-padding-y = 0window-inherit-font-size = false# ── Tab bar ───────────────────────────────────────────────────────────────────window-show-tab-bar = alwaysgtk-tabs-location = bottomwindow-save-state = always# ── Scrollback ────────────────────────────────────────────────────────────────scrollback-limit = 16777216# ── Bell ──────────────────────────────────────────────────────────────────────bell-features = no-system,no-audio,no-attention,no-title,no-border# ── Clipboard ─────────────────────────────────────────────────────────────────clipboard-paste-protection = false# ── Close behavior ────────────────────────────────────────────────────────────confirm-close-surface = false# ── Split behavior ────────────────────────────────────────────────────────────split-preserve-zoom = navigation# ── Mouse ─────────────────────────────────────────────────────────────────────mouse-hide-while-typing = true# ── Shell integration ─────────────────────────────────────────────────────────shell-integration = detectshell-integration-features = cursor,sudo# ── Modular configs ───────────────────────────────────────────────────────────config-file = keybindsconfig-file = launch-menuconfig-file = ?host-desktopghostty/host-desktop
Deleteddeleted file mode 100644+0 / −5 text lines
ghostty/keybinds
Deleteddeleted file mode 100644+0 / −72 text lines
# ── Keybinds for ghostty ──────────────────────────────────────────────────────# Ports wezterm bugabinga/key_binds.lua using ghostty 1.3 key tables.## Leader: ctrl+a (VoidSymbol in wezterm, ctrl+a here)# All modes use catch_all=ignore to prevent key leaks.# Wipe all defaults (equivalent to wezterm's disable_default_key_bindings)keybind = clear# ── Clipboard ─────────────────────────────────────────────────────────────────keybind = ctrl+shift+c=copy_to_clipboardkeybind = ctrl+shift+v=paste_from_clipboard# ── Font mode ─────────────────────────────────────────────────────────────────# Port of wezterm font_mode: -=scale down, ==scale up, 0=resetkeybind = ctrl+a>0=activate_key_table:fontkeybind = font/-=decrease_font_size:1keybind = font/==increase_font_size:1keybind = font/0=reset_font_sizekeybind = font/escape=deactivate_key_tablekeybind = font/catch_all=ignore# ── Pane mode ─────────────────────────────────────────────────────────────────# Port of wezterm pane_mode: hjkl navigate, vs split, a select, q closekeybind = ctrl+a>w=activate_key_table:panekeybind = pane/h=goto_split:leftkeybind = pane/j=goto_split:downkeybind = pane/k=goto_split:upkeybind = pane/l=goto_split:rightkeybind = pane/v=new_split:rightkeybind = pane/s=new_split:downkeybind = pane/==activate_key_table:resizekeybind = pane/q=close_surfacekeybind = pane/escape=deactivate_key_tablekeybind = pane/catch_all=ignore# ── Resize sub-mode ──────────────────────────────────────────────────────────# Port of wezterm resize_pane_mode: hjkl resize by 10pxkeybind = resize/h=resize_split:left,10keybind = resize/j=resize_split:down,10keybind = resize/k=resize_split:up,10keybind = resize/l=resize_split:right,10keybind = resize/escape=deactivate_key_tablekeybind = resize/catch_all=ignore# ── Direct leader sequences ───────────────────────────────────────────────────# Single-shot actions that don't need a modekeybind = ctrl+a>f=toggle_split_zoomkeybind = ctrl+a>F5=reload_configkeybind = ctrl+a>F11=toggle_fullscreenkeybind = ctrl+a>t=new_tabkeybind = ctrl+a>/=start_searchkeybind = ctrl+a>q=close_surface# ── Tab navigation (leader + number) ─────────────────────────────────────────keybind = ctrl+a>1=goto_tab:1keybind = ctrl+a>2=goto_tab:2keybind = ctrl+a>3=goto_tab:3keybind = ctrl+a>4=goto_tab:4keybind = ctrl+a>5=goto_tab:5keybind = ctrl+a>6=goto_tab:6keybind = ctrl+a>7=goto_tab:7keybind = ctrl+a>8=goto_tab:8# ── Scrolling ─────────────────────────────────────────────────────────────────keybind = page_up=scroll_page_upkeybind = page_down=scroll_page_downkeybind = shift+page_up=scroll_page_fractional:-0.42keybind = shift+page_down=scroll_page_fractional:0.42# ── Command palette (replaces wezterm launcher) ───────────────────────────────keybind = ctrl+a>p=toggle_command_paletteghostty/launch-menu
Deleteddeleted file mode 100644+0 / −20 text lines
# ── Launch Menu ───────────────────────────────────────────────────────────────# Replaces wezterm bugabinga/launch.lua via command-palette-entry.# Open with ctrl+a>p then search/filter → enter to execute.## Each entry uses text: action to type the command + newline into the terminal.command-palette-entry = title:Anime (new),action:text:ani-cli\ncommand-palette-entry = title:Anime (continue),action:text:ani-cli --continue\ncommand-palette-entry = title:Upgrade,action:text:topgrade --keep\ncommand-palette-entry = title:IRC Chat,action:text:weechat\ncommand-palette-entry = title:Browser,action:text:cha -V\ncommand-palette-entry = title:E-Mail,action:text:aerc\ncommand-palette-entry = title:Music,action:text:cmus\ncommand-palette-entry = title:System Monitor,action:text:btm\ncommand-palette-entry = title:Clock,action:text:tclock\ncommand-palette-entry = title:Calculator,action:text:eva\ncommand-palette-entry = title:Weather,action:text:nu -c "loop {clear; wthrr --forecast today; sleep 15sec}"\ncommand-palette-entry = title:Host Info,action:text:nu -c "loop {clear; macchina --current-shell --interface wlp3s0; sleep 5sec}"\ncommand-palette-entry = title:Units,action:text:fend\ncommand-palette-entry = title:Files,action:text:yazi\nghostty/themes/nugu-dark
Modified+9 / −6 text lines
ghostty/themes/nugu-light
Modified+9 / −6 text lines
git/allowed_signers
Addednew file mode 100644+4 / −0 text lines
# Trust store for SSH commit signatures. Public keys only; no secret material.# Principal is matched against the committer email.oliver@bugabinga.net ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAICyZgTxIo9LIsvZLl/iKxlh6vf2WSiz6tyHEQI9lYnC6 oli@velmao.krylow@isp-insoft.de ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIIvGTFdXbhJF4VCi1l5Rm3/ypY0rN16XEJOcIzyLq8AA code.isp-insoft.degit/gitattributes
Modified+66 / −46 text lines
*.java merge=mergiraf*.properties merge=mergiraf*.kt merge=mergiraf*.rs merge=mergiraf*.go merge=mergiraf*.js merge=mergiraf*.jsx merge=mergiraf*.mjs merge=mergiraf*.json merge=mergiraf*.yml merge=mergiraf*.yaml merge=mergiraf*.toml merge=mergiraf*.html merge=mergiraf*.htm merge=mergiraf*.xhtml merge=mergiraf*.xml merge=mergiraf*.c merge=mergiraf*.h merge=mergiraf*.cc merge=mergiraf*.hh merge=mergiraf*.cpp merge=mergiraf*.hpp merge=mergiraf*.cxx merge=mergiraf*.hxx merge=mergiraf*.c++ merge=mergiraf*.h++ merge=mergiraf*.mpp merge=mergiraf*.cppm merge=mergiraf*.ixx merge=mergiraf*.tcc merge=mergiraf*.cs merge=mergiraf*.dart merge=mergiraf*.dts merge=mergiraf*.scala merge=mergiraf*.sbt merge=mergiraf*.ts merge=mergiraf*.tsx merge=mergiraf*.py merge=mergiraf*.php merge=mergiraf*.phtml merge=mergiraf*.sol merge=mergiraf*.lua merge=mergiraf*.rb merge=mergiraf*.nix merge=mergiraf*.sv merge=mergiraf*.svh merge=mergiraf* merge=mergiraf# Diff drivers select hunk headers, word-diff boundaries, and `grep -W` context.# Every driver below ships with git except `zig`, which is defined in gitconfig.# One pattern per line: gitattributes reads the first field as the pattern.*.adb diff=ada*.ads diff=ada*.bash diff=bash*.bib diff=bibtex*.c diff=cpp*.cc diff=cpp*.cpp diff=cpp*.cxx diff=cpp*.h diff=cpp*.hh diff=cpp*.hpp diff=cpp*.hxx diff=cpp*.cs diff=csharp*.css diff=css*.dts diff=dts*.dtsi diff=dts*.ex diff=elixir*.exs diff=elixir*.f diff=fortran*.f90 diff=fortran*.f95 diff=fortran*.go diff=golang*.htm diff=html*.html diff=html*.xhtml diff=html*.java diff=java*.kt diff=kotlin*.kts diff=kotlin*.lua diff=lua*.markdown diff=markdown*.md diff=markdown*.mm diff=objc*.pas diff=pascal*.pp diff=pascal*.php diff=php*.phtml diff=php*.pl diff=perl*.pm diff=perl*.py diff=python*.R diff=r*.rb diff=ruby*.rs diff=rust*.scm diff=scheme*.ss diff=scheme*.cls diff=tex*.sty diff=tex*.tex diff=tex*.zig diff=zig*.zon diff=zig# textconv: make opaque formats reviewable.*.class diff=javap*.jar diff=zip*.war diff=zip*.apk diff=zip*.docx diff=pandoc*.odt diff=pandoc# Config languages git ships no driver for.*.toml diff=toml*.yaml diff=yaml*.yml diff=yamlgit/gitconfig
Modified+99 / −54 text lines
l = log --all --graph --pretty=format:'%C(magenta)%h %C(white) %an %ar%C(auto) %D%n%s%n' rb = rebase @{upstream} preloadindex = true safecrlf = false submoduleSummary = true[difftool "zed"] # Binary is named 'zeditor' on some distros, 'zed' elsewhere. cmd = "\"$(command -v zeditor || command -v zed)\" --wait --diff \"$LOCAL\" \"$REMOTE\""[diff "javap"] textconv = javap -p -c cachetextconv = true[diff "zip"] textconv = unzip -l cachetextconv = true[diff "pandoc"] textconv = pandoc --to=markdown --wrap=none cachetextconv = true[diff "toml"] xfuncname = "^\\[.*\\]$"[diff "yaml"] xfuncname = "^[^ \t#-].*:.*$"[diff "zig"] # Hunk headers name the enclosing declaration in Zig and ZON sources. # Capture groups would truncate the header, so the alternation is group-free. xfuncname = "^pub .*$|^fn .*$|^const .*$|^var .*$|^test .*$|^export .*$|^inline .*$|^comptime .*$"[diff] algorithm = histogram colorMoved = zebra colorMovedWS = allow-indentation-change interHunkContext = 10 mnemonicPrefix = true submodule = log driver = mergiraf merge --git %O %A %B -s %S -x %X -y %Y -p %P -l %L[mergetool "vim"] cmd = "nvim -d \"$LOCAL\" \"$MERGED\" \"$REMOTE\" " # A driver that exits non-zero means "conflict", so a missing mergiraf would # leave the file untouched with no markers. Fall back to git's own merge. 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" pruneTags = true recurseSubmodules = false recurseSubmodules = check default = current recurseSubmodules = false gpgSign = true[pager] # Use a pager if the difftool output is larger than one screenful, # consistent with the behaviour of `git diff`. difftool = true[diff] # Set difftastic as the default difftool, so we don't need to specify # `-t difftastic` every time. tool = difftastic algorithm = histogram colorMoved = plain mnemonicPrefix = true renames = true useRelativePaths = truegit/gitconfig.bugabinga
Modified+1 / −0 text lines
git/gitconfig.isp
Modified+15 / −38 text lines
[user]
name = Oliver Krylow
email = o.krylow@isp-insoft.de
[gui]
fontui = -family \"PT Mono\" -size 12 -weight normal -slant roman -underline 0 -overstrike 0
fontdiff = -family Cousine -size 12 -weight normal -slant roman -underline 0 -overstrike 0
[sendemail]
smtpserver = sslout.df.eu
smtpuser = o.krylow@isp-insoft.de
smtpencryption = ssl
smtpserverport = 465
annotate = yes
[core]
# Windows Linebreaks behalten, wir nutzen gitattributes für explizite Kontrolle
autocrlf = false
[branch]
# Immer den neusten Branch auf anhieb finden, da diese wahrscheinlich relevanter sind
sort = committerdate
[pull]
# führt git pull mit --rebase aus, um unnötige Merge-Commits zu vermeiden
rebase = true
[rebase]
# Stashed und Entstashed lokale Änderungen um Konflikte beim Rebase zu vermeiden
autostash = true
# Falls gestackte PRs verwendet werden (absichtlich oder ausversehen), wird hier der Workflow vereinfacht
updateRefs = true
[merge]
# Stashed und Entstashed lokale Änderungen um Konflikte beim Merge zu vermeiden
autostash = true
[push]
# Spart einem bei neuen Branches immer wieder den Remote-Server und Branch spezifizieren zu müssern
autoSetupRemote = true
[submodule]
# Erspart einem ein manuelles git submodule update bei jedem git checkout (branch switch)
recurse = true
[user] name = Oliver Krylow email = o.krylow@isp-insoft.de signingKey = ~/.ssh/code.isp-insoft.de[gui] fontui = -family \"PT Mono\" -size 12 -weight normal -slant roman -underline 0 -overstrike 0 fontdiff = -family Cousine -size 12 -weight normal -slant roman -underline 0 -overstrike 0[sendemail] smtpserver = sslout.df.eu smtpuser = o.krylow@isp-insoft.de smtpencryption = ssl smtpserverport = 465 annotate = yesgit/ignore
Modified+2 / −0 text lines
helix/config.toml
Deleteddeleted file mode 100644+0 / −103 text lines
theme = "nugu-dark"[editor]shell = ["nu", "--commands"]true-color = truemouse = trueline-number = "relative"rulers = [81, 121, 141]auto-completion = truecompletion-trigger-len = 3auto-info = trueauto-pairs = falseauto-format = trueauto-save = trueidle-timeout = 200scrolloff = 5scroll-lines = 1color-modes = truebufferline = "multiple"[editor.statusline]left = [ "mode", "spacer", "selections", "position", "separator", "position-percentage",]center = [ "version-control", "separator", "file-name", "spacer", "file-modification-indicator", "separator", "file-encoding", "file-line-ending", "file-type",]right = ["diagnostics", "spacer", "spinner"]separator = "·"mode.normal = ""mode.insert = ""mode.select = ""[editor.lsp]display-messages = truedisplay-inlay-hints = true[editor.cursor-shape]normal = "block"insert = "bar"select = "underline"[editor.file-picker]hidden = false[editor.whitespace.render]space = "all"tab = "all"newline = "none"[editor.whitespace.characters]space = "·"nbsp = "⍽"newline = "⏎"[editor.indent-guides]render = falsecharacter = "▏"skip-levels = 2[editor.soft-wrap]enable = true[keys.normal]# move current line upA-k = [ "extend_to_line_bounds", "delete_selection", "move_line_up", "paste_before",]# move current line downA-j = ["extend_to_line_bounds", "delete_selection", "paste_after"]"A-=" = ":format"[keys.insert]up = "no_op"down = "no_op"left = "no_op"right = "no_op"pageup = "no_op"pagedown = "no_op"home = "no_op"end = "no_op"helix/languages.toml
Deleteddeleted file mode 100644+0 / −20 text lines
[[language]]name = "nasm"auto-format = truelanguage-servers = [{ name = "asm-lsp" }][[language]]name = "xml"auto-format = falselanguage-servers = [{ name = "lemminx" }][[language]]name = "java"auto-format = falselanguage-servers = [{ name = "jdtls" }][language-server.asm-lsp]command = "asm-lsp"[language-server.lemminx]command = "lemminx"helix/themes/nugu-dark.toml
Deleteddeleted file mode 100644+0 / −142 text lines
# SYNTAX THEME# modifiers:# # - bold# - dim# - italic# - slow_blink# - rapid_blink# - reversed# - hidden# - crossed_out# underline:# - style# - line# - curl# - dashed# - dotted# - double_line# - color"comment" = { fg = "important_global", modifiers = ["bold"] }"string" = { fg = "important_local", modifiers = ["italic"] }"comment.block.documentation" = { fg = "minor", modifiers = ["dim"] }"punctuation" = { fg = "minor" }"keyword" = { fg = "minor" }"tag" = { fg = "minor" }"keyword.control.return" = { modifiers = ["bold"], underline.style = "line" }"keyword.control.exception" = { modifiers = ["bold"], underline.style = "line" }"operator" = { fg = "minor" }"variable.parameter" = { fg = "focus", modifiers = ["bold"] }"markup.heading" = { fg = "important_global", modifiers = [ "bold",], underline.style = "double_line" }"markup.heading.marker" = { fg = "minor" }"markup.list" = "minor""markup.bold" = { modifiers = ["bold"] }"markup.italic" = { modifiers = ["italic"] }"markup.strikethrough" = { modifiers = ["crossed_out"] }"markup.link.url" = "accent""markup.link.text" = "important_local""markup.link.label" = "important_global""markup.quote" = { fg = "important_local", modifiers = ["italic"] }"markup.raw.inline" = { fg = "important_local" }"markup.raw.block" = { fg = "important_global" }"diff.plus" = { fg = "important_local", modifiers = ["bold"] }"diff.delta" = { fg = "unfocus" }"diff.minus" = { fg = "focus", modifiers = ["crossed_out"] }"ui.background" = { fg = "normal", bg = "backdrop" }"ui.background.separator" = { fg = "ui_minor" }"ui.cursor" = { fg = "normal", bg = "accent" }"ui.cursor.primary" = { fg = "normal", bg = "accent" }"ui.cursor.match" = { fg = "normal", bg = "unfocus", modifiers = [ "slow_blink",] }"ui.cursorline.primary" = { bg = "debug" }"ui.selection" = { fg = "normal", bg = "ui_important_local" }"ui.selection.primary" = { fg = "normal", bg = "ui_important_global" }"ui.linenr" = { fg = "ui_unfocus" }"ui.linenr.selected" = { fg = "ui_accent" }"ui.statusline" = { fg = "ui_minor", bg = "ui_backdrop" }"ui.statusline.separator" = { fg = "ui_unfocus", bg = "ui_backdrop" }"ui.statusline.insert" = { fg = "ui_important_global", modifiers = ["bold"] }"ui.statusline.select" = { fg = "ui_focus", modifiers = ["bold"] }"ui.statusline.inactive" = { fg = "ui_unfocus", bg = "ui_backdrop" }"ui.bufferline" = { fg = "ui_minor", bg = "ui_backdrop" }"ui.bufferline.active" = { fg = "ui_important_global", bg = "ui_unfocus", modifiers = [ "bold",], underline = { style = "double_line", color = "ui_backdrop" } }"ui.gutter" = { bg = "ui_backdrop" }"ui.debug.breakpoint" = { fg = "ui_important_global" }"ui.debug.active" = { fg = "ui_important_global" }"ui.window" = { fg = "ui_unfocus", bg = "ui_backdrop" }"ui.help" = { fg = "ui_important_global", bg = "ui_backdrop" }"ui.text" = { fg = "normal", bg = "backdrop" }"ui.text.focus" = { fg = "ui_focus" }"ui.text.info" = { fg = "ui_normal", bg = "ui_backdrop" }"ui.text.inactive" = { fg = "ui_minor" }"ui.menu" = { fg = "ui_normal", bg = "ui_backdrop" }"ui.menu.selected" = { fg = "ui_focus", bg = "ui_backdrop", modifiers = [ "bold",] }"ui.menu.scroll" = { fg = "ui_accent", bg = "ui_backdrop" }"ui.popup" = { fg = "normal", bg = "backdrop" }"ui.popup.info" = { fg = "ui_minor", bg = "ui_backdrop" }"ui.highlight" = { bg = "ui_focus" }"ui.highlight.frameline" = { bg = "ui_important_global" }"ui.virtual.ruler" = { bg = "ui_unfocus" }"ui.virtual.whitespace" = { fg = "ui_unfocus" }"ui.virtual.inlay-hint" = { fg = "ui_minor" }"error" = { bg = "error" }"warning" = { bg = "warning" }"info" = { bg = "info" }"hint" = { fg = "info", modifiers = ["dim"] }"diagnostic.error" = { underline = { style = "double_line", color = "error" } }"diagnostic.warning" = { underline = { style = "double_line", color = "warning" } }"diagnostic.info" = { underline = { style = "double_line", color = "info" } }"diagnostic.hint" = { underline = { style = "double_line", color = "info" }, modifiers = [ "dim",] }"special" = { fg = "debug" }[palette]normal = "#ededed"backdrop = "#121212"accent = "#d151d1"important_local = "#b59ae4"important_global = "#dfd3f3"minor = "#8b8b8b"focus = "#7ba1aa"unfocus = "#5d5d5d"ui_normal = "#dbdbdb"ui_backdrop = "#242424"ui_accent = "#d86dd8"ui_important_global = "#f3effb"ui_important_local = "#c9b6eb"ui_minor = "#9d9d9d"ui_focus = "#9aabae"ui_unfocus = "#6f6f6f"error = "#ec6376"warning = "#f0ee69"info = "#3ec5e3"debug = "#ed5eed"helix/themes/nugu-light.toml
Deleteddeleted file mode 100644+0 / −142 text lines
# SYNTAX THEME# modifiers:# # - bold# - dim# - italic# - slow_blink# - rapid_blink# - reversed# - hidden# - crossed_out# underline:# - style# - line# - curl# - dashed# - dotted# - double_line# - color"comment" = { fg = "important_global", modifiers = ["bold"] }"string" = { fg = "important_local", modifiers = ["italic"] }"comment.block.documentation" = { fg = "minor", modifiers = ["dim"] }"punctuation" = { fg = "minor" }"keyword" = { fg = "minor" }"tag" = { fg = "minor" }"keyword.control.return" = { modifiers = ["bold"], underline.style = "line" }"keyword.control.exception" = { modifiers = ["bold"], underline.style = "line" }"operator" = { fg = "minor" }"variable.parameter" = { fg = "focus", modifiers = ["bold"] }"markup.heading" = { fg = "important_global", modifiers = [ "bold",], underline.style = "double_line" }"markup.heading.marker" = { fg = "minor" }"markup.list" = "minor""markup.bold" = { modifiers = ["bold"] }"markup.italic" = { modifiers = ["italic"] }"markup.strikethrough" = { modifiers = ["crossed_out"] }"markup.link.url" = "accent""markup.link.text" = "important_local""markup.link.label" = "important_global""markup.quote" = { fg = "important_local", modifiers = ["italic"] }"markup.raw.inline" = { fg = "important_local" }"markup.raw.block" = { fg = "important_global" }"diff.plus" = { fg = "important_local", modifiers = ["bold"] }"diff.delta" = { fg = "unfocus" }"diff.minus" = { fg = "focus", modifiers = ["crossed_out"] }"ui.background" = { fg = "normal", bg = "backdrop" }"ui.background.separator" = { fg = "ui_minor" }"ui.cursor" = { fg = "normal", bg = "accent" }"ui.cursor.primary" = { fg = "normal", bg = "accent" }"ui.cursor.match" = { fg = "normal", bg = "unfocus", modifiers = [ "slow_blink",] }"ui.cursorline.primary" = { bg = "debug" }"ui.selection" = { fg = "normal", bg = "ui_important_local" }"ui.selection.primary" = { fg = "normal", bg = "ui_important_global" }"ui.linenr" = { fg = "ui_unfocus" }"ui.linenr.selected" = { fg = "ui_accent" }"ui.statusline" = { fg = "ui_minor", bg = "ui_backdrop" }"ui.statusline.separator" = { fg = "ui_unfocus", bg = "ui_backdrop" }"ui.statusline.insert" = { fg = "ui_important_global", modifiers = ["bold"] }"ui.statusline.select" = { fg = "ui_focus", modifiers = ["bold"] }"ui.statusline.inactive" = { fg = "ui_unfocus", bg = "ui_backdrop" }"ui.bufferline" = { fg = "ui_minor", bg = "ui_backdrop" }"ui.bufferline.active" = { fg = "ui_important_global", bg = "ui_unfocus", modifiers = [ "bold",], underline = { style = "double_line", color = "ui_backdrop" } }"ui.gutter" = { bg = "ui_backdrop" }"ui.debug.breakpoint" = { fg = "ui_important_global" }"ui.debug.active" = { fg = "ui_important_global" }"ui.window" = { fg = "ui_unfocus", bg = "ui_backdrop" }"ui.help" = { fg = "ui_important_global", bg = "ui_backdrop" }"ui.text" = { fg = "normal", bg = "backdrop" }"ui.text.focus" = { fg = "ui_focus" }"ui.text.info" = { fg = "ui_normal", bg = "ui_backdrop" }"ui.text.inactive" = { fg = "ui_minor" }"ui.menu" = { fg = "ui_normal", bg = "ui_backdrop" }"ui.menu.selected" = { fg = "ui_focus", bg = "ui_backdrop", modifiers = [ "bold",] }"ui.menu.scroll" = { fg = "ui_accent", bg = "ui_backdrop" }"ui.popup" = { fg = "normal", bg = "backdrop" }"ui.popup.info" = { fg = "ui_minor", bg = "ui_backdrop" }"ui.highlight" = { bg = "ui_focus" }"ui.highlight.frameline" = { bg = "ui_important_global" }"ui.virtual.ruler" = { bg = "ui_unfocus" }"ui.virtual.whitespace" = { fg = "ui_unfocus" }"ui.virtual.inlay-hint" = { fg = "ui_minor" }"error" = { bg = "error" }"warning" = { bg = "warning" }"info" = { bg = "info" }"hint" = { fg = "info", modifiers = ["dim"] }"diagnostic.error" = { underline = { style = "double_line", color = "error" } }"diagnostic.warning" = { underline = { style = "double_line", color = "warning" } }"diagnostic.info" = { underline = { style = "double_line", color = "info" } }"diagnostic.hint" = { underline = { style = "double_line", color = "info" }, modifiers = [ "dim",] }"special" = { fg = "debug" }[palette]normal = "#121212"backdrop = "#ededed"accent = "#ae2eae"important_local = "#715696"important_global = "#4f3c69"minor = "#3b3b3b"focus = "#184e5b"unfocus = "#6f6f6f"ui_normal = "#242424"ui_backdrop = "#dbdbdb"ui_accent = "#922792"ui_important_global = "#3e2f53"ui_important_local = "#604980"ui_minor = "#292929"ui_focus = "#15333b"ui_unfocus = "#5d5d5d"error = "#bd172e"warning = "#6e6c10"info = "#116477"debug = "#a112a1"hypr/AGENTS.md
Deleteddeleted file mode 100644+0 / −42 text lines
# AGENTS — Nugu themingScope: `hypr/` desktop theming.Rules:- Nugu generators output palette/color fragments only when app supports import/include.- Keep app behavior/layout/fonts/spacing in app config dir.- Do not duplicate whole app configs in `nugu/`.- Use generated fragments: - Ironbar: `ironbar/nugu.css` via `@import url("nugu.css")` - Mako: `mako/nugu.conf` via `include=~/.config/mako/nugu.conf` - Hypr Lua: `hypr/generated/nugu.lua` - Runtime JSON: `hypr/generated/nugu.json`- Runtime switcher `hypr/scripts/theme.nu` writes active color fragments under `$XDG_CONFIG_HOME`.Hyprtoolkit:- Never rewrite `hyprtoolkit.conf` while Hyprtoolkit apps run.- Bug: https://github.com/hyprwm/hyprtoolkit/issues/92- Static session config only until fixed.Nugu semantics:- `content.*` = app/content/terminal text surfaces.- `ui.*` = chrome/widgets/borders/status bars.- `error|warning|info|debug` = semantic signal colors.- Active UI: bg `ui.focus`, fg `content.backdrop`.- Hover/accent UI: bg `ui.accent`, fg `content.backdrop`.- Muted UI text: `ui.minor` over `ui.backdrop`.- Borders/accent lines: `ui.accent`.Accessibility:- Check critical fg/bg pairs with `pastel format luminance` or `pastel textcolor`.- Target ≥4.5 contrast; prefer ≥7 for small bar text.- Verify screenshots; CSS cascade/child labels may override intended colors.Fonts:- Use IBM Plex family exclusively in Hypr desktop configs.- UI sans: `IBM Plex Sans`; mono/status: `IBM Plex Mono`.Testing:- After theme edits: `NUGU_NO_NOTIFY=1 hypr/scripts/theme.nu dark|light`.- Check `systemctl --user is-active mako.service ironbar.service hyprpaper.service`.- Screenshot dark/light with `grim`; inspect actual rendered colors, not just CSS.hypr/generated/nugu.json
Deleteddeleted file mode 100644+0 / −54 text lines
{ "dark": { "debug": "#ed5eed", "error": "#ec6376", "warning": "#f0ee69", "info": "#3ec5e3", "content": { "normal": "#ededed", "backdrop": "#121212", "accent": "#d151d1", "minor": "#8b8b8b", "focus": "#7ba1aa", "unfocus": "#5d5d5d", "important_local": "#b59ae4", "important_global": "#dfd3f3" }, "ui": { "normal": "#dbdbdb", "backdrop": "#242424", "accent": "#d86dd8", "minor": "#9d9d9d", "focus": "#9aabae", "unfocus": "#6f6f6f", "important_local": "#c9b6eb", "important_global": "#f3effb" } }, "light": { "debug": "#a112a1", "error": "#bd172e", "warning": "#6e6c10", "info": "#116477", "content": { "normal": "#121212", "backdrop": "#ededed", "accent": "#ae2eae", "minor": "#3b3b3b", "focus": "#184e5b", "unfocus": "#6f6f6f", "important_local": "#715696", "important_global": "#4f3c69" }, "ui": { "normal": "#242424", "backdrop": "#dbdbdb", "accent": "#922792", "minor": "#292929", "focus": "#15333b", "unfocus": "#5d5d5d", "important_local": "#604980", "important_global": "#3e2f53" } }}No final newlinehypr/generated/nugu.lua
Deleteddeleted file mode 100644+0 / −88 text lines
local palette = { dark = { debug = "#ed5eed", error = "#ec6376", warning = "#f0ee69", info = "#3ec5e3", content = { normal = "#ededed", backdrop = "#121212", accent = "#d151d1", minor = "#8b8b8b", focus = "#7ba1aa", unfocus = "#5d5d5d", important_local = "#b59ae4", important_global = "#dfd3f3", }, ui = { normal = "#dbdbdb", backdrop = "#242424", accent = "#d86dd8", minor = "#9d9d9d", focus = "#9aabae", unfocus = "#6f6f6f", important_local = "#c9b6eb", important_global = "#f3effb", }, }, light = { debug = "#a112a1", error = "#bd172e", warning = "#6e6c10", info = "#116477", content = { normal = "#121212", backdrop = "#ededed", accent = "#ae2eae", minor = "#3b3b3b", focus = "#184e5b", unfocus = "#6f6f6f", important_local = "#715696", important_global = "#4f3c69", }, ui = { normal = "#242424", backdrop = "#dbdbdb", accent = "#922792", minor = "#292929", focus = "#15333b", unfocus = "#5d5d5d", important_local = "#604980", important_global = "#3e2f53", }, },}local M = {}function M.mode() local path = os.getenv("HOME") .. "/.cache/nugu/mode" local file = io.open(path, "r") if not file then return "dark" end local mode = file:read("*l") or "dark" file:close() if mode == "light" then return "light" end return "dark"endfunction M.current() return palette[M.mode()]endfunction M.get(mode) return palette[mode]endfunction M.hex(color) return color:gsub("#", "")endfunction M.rgba(color, alpha) return "rgba(" .. M.hex(color) .. (alpha or "ff") .. ")"endfunction M.rgb(color) return "rgb(" .. M.hex(color) .. ")"endreturn Mhypr/hypridle.conf
Deleteddeleted file mode 100644+0 / −21 text lines
general { lock_cmd = pidof hyprlock || hyprlock before_sleep_cmd = loginctl lock-session after_sleep_cmd = hyprctl dispatch dpms on}listener { timeout = 600 on-timeout = loginctl lock-session}listener { timeout = 690 on-timeout = hyprctl dispatch dpms off on-resume = hyprctl dispatch dpms on}listener { timeout = 4200 on-timeout = systemctl suspend}hypr/hyprland.lua
Deleteddeleted file mode 100644+0 / −12 text lines
-- bugabinga x230 Hyprland-- Lua-only compositor config. Generated app configs live beside this tree.require("modules.env")require("modules.permissions")require("modules.monitors")require("modules.input")require("modules.appearance")require("modules.animations")require("modules.workspaces")require("modules.rules")require("modules.binds")hypr/hyprlock.conf
Deleteddeleted file mode 100644+0 / −36 text lines
general { hide_cursor = true ignore_empty_input = true fail_timeout = 1500}background { monitor = path = screenshot color = rgba(121212ff) blur_passes = 3 blur_size = 4}input-field { monitor = size = 520, 72 position = 0, -24 halign = center valign = center outer_color = rgba(d151d1ee) inner_color = rgba(242424ee) font_color = rgba(edededff) check_color = rgba(7ba1aaff) fail_color = rgba(e46479ff) outline_thickness = 2 font_family = IBM Plex Mono placeholder_text = unlock fail_text = nope rounding = 7 shadow_passes = 0 fade_on_empty = false}hypr/hyprpaper.conf
Deleteddeleted file mode 100644+0 / −7 text lines
hypr/hyprsunset.conf
Deleteddeleted file mode 100644+0 / −12 text lines
hypr/hyprtoolkit.conf
Deleteddeleted file mode 100644+0 / −25 text lines
# Nugu Hyprtoolkit palette.# Static for now: live rewrites busy-loop Hyprtoolkit apps.# https://github.com/hyprwm/hyprtoolkit/issues/92background = 0xFF121212base = 0xFF242424alternate_base = 0xFF2E2E2Etext = 0xFFEDEDEDbright_text = 0xFFF3EFFBlink_text = 0xFF3EC5DDaccent = 0xFFD86DD8accent_secondary = 0xFFB59AE4rounding_large = 12rounding_small = 7h1_size = 21h2_size = 16h3_size = 13font_size = 11small_font_size = 10font_family = IBM Plex Sansfont_family_monospace = IBM Plex Monoicon_theme = Adwaitahypr/lib/apps.lua
Deleteddeleted file mode 100644+0 / −23 text lines
local tui = require("scripts.tui_tab")return { terminal = "wezterm connect unix", terminal_class = "wezterm start --always-new-process --class", browser = "firefox", editor = "nvim", launcher = "hyprlauncher", file_manager = function() tui.spawn("yazi") end, bluetooth = function() tui.spawn("bluetui") end, wifi = function() tui.spawn("impala") end, lock = "hyprlock", logout = "hyprshutdown --dry-run", theme_toggle = "nu ~/.config/hypr/scripts/theme.nu toggle", theme_auto = "nu ~/.config/hypr/scripts/theme.nu auto", clipboard = "bash -lc 'cliphist list | hyprlauncher --dmenu | cliphist decode | wl-copy'", screenshot_region = "hyprshot -m region -z", screenshot_window = "hyprshot -m window -z", screenshot_output = "hyprshot -m output -z", screenshot_annotate = "hyprshot -m region -z -- satty --filename", binds_help = "nu ~/.config/hypr/scripts/show_binds.nu", clients_help = "nu ~/.config/hypr/scripts/show_clients.nu",}hypr/modules/animations.lua
Deleteddeleted file mode 100644+0 / −14 text lines
hl.config({ animations = { enabled = true } })hl.curve("nuguEase", { type = "bezier", points = { {0.16, 1.0}, {0.3, 1.0} } })hl.curve("nuguSnap", { type = "bezier", points = { {0.2, 0.0}, {0.0, 1.0} } })hl.curve("nuguSpring", { type = "spring", mass = 1, stiffness = 80, dampening = 16 })hl.animation({ leaf = "global", enabled = true, speed = 1, bezier = "default" })hl.animation({ leaf = "border", enabled = true, speed = 4.0, bezier = "nuguEase" })hl.animation({ leaf = "windows", enabled = true, speed = 3.6, spring = "nuguSpring" })hl.animation({ leaf = "windowsIn", enabled = true, speed = 3.2, spring = "nuguSpring", style = "popin 88%" })hl.animation({ leaf = "windowsOut", enabled = true, speed = 2.0, bezier = "nuguSnap", style = "popin 92%" })hl.animation({ leaf = "fade", enabled = true, speed = 2.4, bezier = "nuguEase" })hl.animation({ leaf = "layers", enabled = true, speed = 3.0, bezier = "nuguEase" })hl.animation({ leaf = "workspaces", enabled = true, speed = 2.2, bezier = "nuguEase", style = "slidefade 20%" })hypr/modules/appearance.lua
Deleteddeleted file mode 100644+0 / −70 text lines
local nugu = require("generated.nugu")local t = nugu.current()local rgba = nugu.rgbahl.config({ general = { gaps_in = 4, gaps_out = 8, border_size = 2, col = { active_border = { colors = { rgba(t.content.accent, "ee"), rgba(t.content.important_local, "ee") }, angle = 42 }, inactive_border = rgba(t.ui.unfocus, "88"), }, resize_on_border = true, allow_tearing = false, layout = "dwindle", }, decoration = { rounding = 7, rounding_power = 2, active_opacity = 1.0, inactive_opacity = 0.96, shadow = { enabled = true, range = 8, render_power = 2, color = rgba(t.content.backdrop, "cc"), }, blur = { enabled = true, size = 4, passes = 2, vibrancy = 0.12, noise = 0.02, }, }, dwindle = { preserve_split = true, smart_split = true, }, master = { new_status = "master", }, group = { col = { border_active = rgba(t.content.accent, "ee"), border_inactive = rgba(t.ui.unfocus, "88"), }, }, misc = { force_default_wallpaper = 0, disable_hyprland_logo = true, disable_splash_rendering = true, vrr = 0, }, ecosystem = { no_update_news = true, no_donation_nag = true, }, xwayland = { enabled = false, },})hypr/modules/binds.lua
Deleteddeleted file mode 100644+0 / −78 text lines
local apps = require("lib.apps")local workspaces = require("modules.workspaces")local mod = "SUPER"local function bind(key, cmd, description) local dispatcher = type(cmd) == "function" and cmd or hl.dsp.exec_cmd(cmd) hl.bind(key, dispatcher, { description = description })endbind(mod .. " + Return", apps.terminal, "terminal: wezterm")bind(mod .. " + Space", apps.launcher, "launcher: hyprlauncher")bind(mod .. " + B", apps.browser, "browser: firefox")-- TUI app binds open in an existing WezTerm default mux workspace window as new tabs.bind(mod .. " + E", apps.file_manager, "files: yazi")bind(mod .. " + N", apps.wifi, "wifi: impala")bind(mod .. " + U", apps.bluetooth, "bluetooth: bluetui")hl.bind(mod .. " + Q", hl.dsp.window.close(), { description = "close window" })hl.bind(mod .. " + C", hl.dsp.window.close(), { description = "close window" })bind(mod .. " + V", apps.clipboard, "clipboard history")bind(mod .. " + ALT + L", apps.lock, "lock")bind(mod .. " + ALT + S", "loginctl lock-session && systemctl suspend", "lock + suspend")bind(mod .. " + SHIFT + R", "hyprctl reload", "reload hypr")bind(mod .. " + SHIFT + T", apps.theme_toggle, "toggle nugu light/dark")bind(mod .. " + CTRL + T", apps.theme_auto, "nugu auto mode now")bind(mod .. " + Slash", apps.binds_help, "show binds")bind(mod .. " + Tab", apps.clients_help, "show clients")bind(mod .. " + Escape", "makoctl dismiss --all", "dismiss notifications")bind("CTRL + ALT + Delete", apps.logout, "graceful hyprland logout")hl.bind(mod .. " + H", hl.dsp.focus({ direction = "left" }), { description = "focus left" })hl.bind(mod .. " + L", hl.dsp.focus({ direction = "right" }), { description = "focus right" })hl.bind(mod .. " + K", hl.dsp.focus({ direction = "up" }), { description = "focus up" })hl.bind(mod .. " + J", hl.dsp.focus({ direction = "down" }), { description = "focus down" })hl.bind(mod .. " + SHIFT + H", hl.dsp.window.move({ direction = "left" }), { description = "move left" })hl.bind(mod .. " + SHIFT + L", hl.dsp.window.move({ direction = "right" }), { description = "move right" })hl.bind(mod .. " + SHIFT + K", hl.dsp.window.move({ direction = "up" }), { description = "move up" })hl.bind(mod .. " + SHIFT + J", hl.dsp.window.move({ direction = "down" }), { description = "move down" })hl.bind(mod .. " + CTRL + H", hl.dsp.window.resize({ x = -24, y = 0, relative = true }), { description = "resize left" })hl.bind(mod .. " + CTRL + L", hl.dsp.window.resize({ x = 24, y = 0, relative = true }), { description = "resize right" })hl.bind(mod .. " + CTRL + K", hl.dsp.window.resize({ x = 0, y = -24, relative = true }), { description = "resize up" })hl.bind(mod .. " + CTRL + J", hl.dsp.window.resize({ x = 0, y = 24, relative = true }), { description = "resize down" })hl.bind(mod .. " + F", hl.dsp.window.fullscreen({ mode = "fullscreen", action = "toggle" }), { description = "fullscreen" })hl.bind(mod .. " + T", hl.dsp.window.float({ action = "toggle" }), { description = "toggle floating" })hl.bind(mod .. " + P", hl.dsp.window.pseudo({ action = "toggle" }), { description = "pseudo tile" })hl.bind(mod .. " + G", hl.dsp.group.toggle(), { description = "toggle group" })hl.bind(mod .. " + SHIFT + G", hl.dsp.group.next(), { description = "next group tab" })for _, ws in ipairs(workspaces.list) do hl.bind(mod .. " + " .. ws.key, hl.dsp.focus({ workspace = ws.id }), { description = "workspace " .. ws.name }) hl.bind(mod .. " + SHIFT + " .. ws.key, hl.dsp.window.move({ workspace = ws.id }), { description = "move to " .. ws.name })endhl.bind(mod .. " + S", hl.dsp.workspace.toggle_special("scratch"), { description = "toggle scratch" })hl.bind(mod .. " + SHIFT + V", hl.dsp.window.move({ workspace = "special:scratch" }), { description = "send to scratch" })hl.bind(mod .. " + mouse_down", hl.dsp.focus({ workspace = "e+1" }))hl.bind(mod .. " + mouse_up", hl.dsp.focus({ workspace = "e-1" }))hl.bind(mod .. " + mouse:272", hl.dsp.window.drag(), { mouse = true, description = "drag window" })hl.bind(mod .. " + mouse:273", hl.dsp.window.resize(), { mouse = true, description = "resize window" })hl.bind("XF86AudioRaiseVolume", hl.dsp.exec_cmd("wpctl set-volume -l 1 @DEFAULT_AUDIO_SINK@ 2%+"), { locked = true, repeating = true })hl.bind("XF86AudioLowerVolume", hl.dsp.exec_cmd("wpctl set-volume @DEFAULT_AUDIO_SINK@ 2%-"), { locked = true, repeating = true })hl.bind("XF86AudioMute", hl.dsp.exec_cmd("wpctl set-mute @DEFAULT_AUDIO_SINK@ toggle"), { locked = true })hl.bind("XF86AudioMicMute", hl.dsp.exec_cmd("wpctl set-mute @DEFAULT_AUDIO_SOURCE@ toggle"), { locked = true })hl.bind("XF86MonBrightnessUp", hl.dsp.exec_cmd("brightnessctl -e4 -n2 set 5%+"), { locked = true, repeating = true })hl.bind("XF86MonBrightnessDown", hl.dsp.exec_cmd("brightnessctl -e4 -n2 set 5%-"), { locked = true, repeating = true })hl.bind("XF86AudioNext", hl.dsp.exec_cmd("playerctl next"), { locked = true })hl.bind("XF86AudioPause", hl.dsp.exec_cmd("playerctl play-pause"), { locked = true })hl.bind("XF86AudioPlay", hl.dsp.exec_cmd("playerctl play-pause"), { locked = true })hl.bind("XF86AudioPrev", hl.dsp.exec_cmd("playerctl previous"), { locked = true })bind("Print", apps.screenshot_region, "screenshot region")bind("SHIFT + Print", apps.screenshot_window, "screenshot window")bind("CTRL + Print", apps.screenshot_output, "screenshot output")bind(mod .. " + Print", apps.screenshot_annotate, "screenshot annotate")bind(mod .. " + SHIFT + Print", "hyprpicker -a", "pick color")hypr/modules/env.lua
Deleteddeleted file mode 100644+0 / −15 text lines
hl.env("XDG_CURRENT_DESKTOP", "Hyprland")hl.env("XDG_SESSION_DESKTOP", "Hyprland")hl.env("XDG_SESSION_TYPE", "wayland")hl.env("GDK_BACKEND", "wayland,x11")hl.env("QT_QPA_PLATFORM", "wayland;xcb")hl.env("QT_QPA_PLATFORMTHEME", "xdgdesktopportal")hl.env("QT_WAYLAND_DISABLE_WINDOWDECORATION", "1")hl.env("SDL_VIDEODRIVER", "wayland")hl.env("CLUTTER_BACKEND", "wayland")hl.env("MOZ_ENABLE_WAYLAND", "1")hl.env("ELECTRON_OZONE_PLATFORM_HINT", "wayland")hl.env("OZONE_PLATFORM", "wayland")hl.env("_JAVA_AWT_WM_NONREPARENTING", "1")hl.env("XCURSOR_SIZE", "24")hl.env("HYPRCURSOR_SIZE", "24")hypr/modules/input.lua
Deleteddeleted file mode 100644+0 / −21 text lines
hl.config({ input = { kb_layout = "us", kb_variant = "altgr-intl", kb_model = "", kb_options = "caps:none", kb_rules = "", repeat_rate = 40, repeat_delay = 600, follow_mouse = 1, sensitivity = 0, accel_profile = "adaptive", natural_scroll = true, touchpad = { natural_scroll = true, disable_while_typing = true, }, },})hl.gesture({ fingers = 3, direction = "horizontal", action = "workspace" })hypr/modules/monitors.lua
Deleteddeleted file mode 100644+0 / −10 text lines
-- ThinkPad X230 internal display. Fallback keeps docks/external outputs sane.-- ICC path stays under ~/.config so other WMs can reuse the same profile.hl.monitor({ output = "LVDS-1", mode = "1366x768@60.01900", position = "0x0", scale = 1, icc = "/home/oli/.config/icc/thinkpad_x230.icc",})hl.monitor({ output = "", mode = "preferred", position = "auto", scale = 1 })hypr/modules/permissions.lua
Deleteddeleted file mode 100644+0 / −5 text lines
-- Explicitly allow the small trusted local tools this rice binds.-- Permission changes may require a fresh Hyprland session.hl.permission("/usr/(bin|local/bin)/grim", "screencopy", "allow")hl.permission("/usr/(bin|local/bin)/hyprshot", "screencopy", "allow")hl.permission("/usr/(lib|libexec|lib64)/xdg-desktop-portal-hyprland", "screencopy", "allow")hypr/modules/rules.lua
Deleteddeleted file mode 100644+0 / −26 text lines
local nugu = require("generated.nugu")local t = nugu.current()hl.window_rule({ name = "suppress-maximize-events", match = { class = ".*" }, suppress_event = "maximize",})hl.window_rule({ match = { class = "^(firefox|org.mozilla.firefox)$" }, workspace = "1" })hl.window_rule({ match = { class = "^(firefox|org.mozilla.firefox)$" }, opacity = "0.98 0.96" })hl.window_rule({ match = { class = "^(wezterm|org.wezfurlong.wezterm)$" }, workspace = "3" })hl.window_rule({ match = { class = "^yazi$" }, workspace = "3" })hl.window_rule({ match = { class = "^(mpv|com.github.celluloid_player.Celluloid)$" }, workspace = "5" })hl.window_rule({ match = { class = "^(mpv|com.github.celluloid_player.Celluloid)$" }, immediate = true })hl.window_rule({ match = { class = "^(pavucontrol|blueman-manager|nm-connection-editor)$" }, float = true, center = true })hl.window_rule({ match = { class = "^(org.gnome.Nautilus|thunar)$", title = "^(Open|Save).*" }, float = true, center = true })hl.window_rule({ match = { class = "(pinentry-)(.*)" }, stay_focused = true })hl.window_rule({ match = { float = true }, border_color = nugu.rgba(t.ui.accent, "dd") })hl.window_rule({ match = { fullscreen = true }, border_size = 0, rounding = 0 })hl.window_rule({ match = { float = false, workspace = "w[tv1]s[false]" }, border_size = 0, rounding = 0 })hl.window_rule({ match = { float = false, workspace = "f[1]s[false]" }, border_size = 0, rounding = 0 })hypr/modules/workspaces.lua
Deleteddeleted file mode 100644+0 / −21 text lines
local M = {}M.list = { { key = "1", id = "1", name = "web" }, { key = "2", id = "2", name = "code" }, { key = "3", id = "3", name = "term" }, { key = "4", id = "4", name = "chat" }, { key = "5", id = "5", name = "media" }, { key = "9", id = "9", name = "misc" },}for _, ws in ipairs(M.list) do hl.workspace_rule({ workspace = ws.id, monitor = "LVDS-1" })endhl.workspace_rule({ workspace = "1", default = true })hl.workspace_rule({ workspace = "special:scratch", on_created_empty = "wezterm start --always-new-process" })hl.workspace_rule({ workspace = "w[tv1]s[false]", gaps_out = 0, gaps_in = 0 })hl.workspace_rule({ workspace = "f[1]s[false]", gaps_out = 0, gaps_in = 0 })return Mhypr/scripts/show_binds.nu
Deleteddeleted file mode 100644+0 / −54 text lines
# Function to parse modmask into readable modifier namesdef parse_modmask [modmask: int] { let modifiers = [ { mask: 64, name: "SUPER" }, { mask: 1, name: "SHIFT" }, { mask: 4, name: "CTRL" }, { mask: 8, name: "ALT" } ] let active_mods = $modifiers | where { |mod| ($modmask | bits and $mod.mask) != 0 } | get name if ($active_mods | is-empty) { "None" } else { $active_mods | str join "+" }}# Function to format key for displaydef format_key [key: string, mouse: bool] { if $mouse { $key | str replace "mouse:" "MOUSE_" } else { $key | str upcase }}# Main function to process binds and show fuzzel menudef main [] { # Get binds from hyprctl let binds = (hyprctl binds -j | from json) # Parse binds into a formatted list for fuzzel let formatted_binds = $binds | each { |bind| let mods = (parse_modmask $bind.modmask) let key = (format_key $bind.key $bind.mouse) let display = $"($mods) + ($key) -> ($bind.dispatcher): ($bind.arg)" { display: $display, arg: $bind.arg, dispatcher: $bind.dispatcher } } # Create a temporary file for fuzzel let temp_file = (mktemp -t hypr_binds.XXXXXX | str trim) $formatted_binds | each { |b| $b.display } | str join "\n" | save -f $temp_file # Show fuzzel menu and get selection let selection = (cat $temp_file | fuzzel --dmenu --prompt "Keybindings: " | str trim) rm $temp_file # Find the selected binding and execute its arg if ($selection | is-not-empty) { let selected_bind = ($formatted_binds | where display == $selection | first) if ($selected_bind | is-not-empty) { if $selected_bind.dispatcher == "exec" { run-external ($selected_bind.arg | split row ' ') } else { hyprctl dispatch $selected_bind.dispatcher $selected_bind.arg } } }}hypr/scripts/show_clients.nu
Deleteddeleted file mode 100644+0 / −25 text lines
# Fetch and parse hyprctl clients JSONlet clients = (hyprctl clients -j | from json)# Format clients for fuzzel: "class: title (workspace)"let formatted = ($clients | each { |client| $"($client.class): ($client.title) \(($client.workspace.name)\)"} | str join "\n")# Pipe formatted list to fuzzel and get selected itemlet selected = ($formatted | fuzzel --dmenu --prompt "Select window: " | str trim)# Exit if no selectionif ($selected | is-empty) { exit 0}# Find the index of the selected itemlet selected_index = ($formatted | split row "\n" | enumerate | where item == $selected | get 0.index)# Get the address of the selected clientlet address = ($clients | get $selected_index | get address)# Focus the selected windowhyprctl -q dispatch focuswindow address:($address)hyprctl -q dispatch alterzorder tophypr/scripts/theme.nu
Deleteddeleted file mode 100755+0 / −182 text lines
#!/usr/bin/env nu# Nugu desktop theme switcher. Writes active runtime configs, then reloads clients.const modes = [dark light]def config-home [] { $env.XDG_CONFIG_HOME? | default ($env.HOME | path join ".config") }def cache-dir [] { $env.HOME | path join ".cache" "nugu" }def mode-file [] { cache-dir | path join "mode" }def auto-file [] { cache-dir | path join "auto" }def palette-file [] { config-home | path join "hypr" "generated" "nugu.json" }def active-mode [] { let path = (mode-file) if ($path | path exists) { let mode = (open --raw $path | str trim) if $mode in $modes { return $mode } } "dark"}def auto-mode [] { let hour = (date now | format date "%H" | into int) if $hour >= 7 and $hour < 19 { "light" } else { "dark" }}def hex-no-hash [color: string] { $color | str replace --all "#" "" }def argb [color: string] { $"0xFF(hex-no-hash $color)" }def palette [mode: string] { open (palette-file) | get $mode}def auto-enabled [] { let path = (auto-file) if not ($path | path exists) { return true } (open --raw $path | str trim) != "0"}def set-auto [enabled: bool] { (if $enabled { "1" } else { "0" }) | save --raw --force (auto-file)}def write-desktop-color-scheme [mode: string] { let scheme = if $mode == "dark" { "prefer-dark" } else { "prefer-light" } try { gsettings set org.gnome.desktop.interface color-scheme $scheme | ignore }}def write-hyprtoolkit [mode: string, p: record] { let out = (config-home | path join "hypr" "hyprtoolkit.conf") $"background = (argb $p.content.backdrop)base = (argb $p.ui.backdrop)alternate_base = (argb $p.ui.unfocus)text = (argb $p.content.normal)bright_text = (argb $p.ui.important_global)accent = (argb $p.ui.accent)accent_secondary = (argb $p.content.important_local)h1_size = 20h2_size = 16h3_size = 13font_size = 11small_font_size = 10font_family = IBM Plex Sansfont_family_monospace = IBM Plex Monoicon_theme = Adwaita" | save --raw --force $out}def write-mako [mode: string, p: record] { mkdir (config-home | path join "mako") let out = (config-home | path join "mako" "nugu.conf") $"# Generated by hypr/scripts/theme.nu from Nugu palette.background-color=($p.ui.backdrop)eetext-color=($p.ui.normal)ffborder-color=($p.ui.accent)ffprogress-color=over ($p.ui.focus)ff[urgency=low]background-color=($p.content.backdrop)e6text-color=($p.content.minor)ffborder-color=($p.ui.unfocus)ffprogress-color=over ($p.content.minor)ff[urgency=normal]border-color=($p.ui.accent)ffprogress-color=over ($p.ui.focus)ff[urgency=critical]background-color=($p.ui.backdrop)fftext-color=($p.ui.important_global)ffborder-color=($p.error)ffprogress-color=over ($p.error)ff[summary~=\"[Ee]rror|[Ff]ailed|[Ff]ailure|[Cc]rash\"]border-color=($p.error)ffprogress-color=over ($p.error)ff[summary~=\"[Ww]arn|[Ww]arning\"]border-color=($p.warning)ffprogress-color=over ($p.warning)ff[summary~=\"[Ii]nfo|[Nn]otice\"]border-color=($p.info)ffprogress-color=over ($p.info)ff" | save --raw --force $out}def write-ironbar [mode: string, p: record] { mkdir (config-home | path join "ironbar") let out = (config-home | path join "ironbar" "nugu.css") let surface = $p.ui.minor let on_focus = $p.content.backdrop $"/* Generated by hypr/scripts/theme.nu from Nugu palette. */:root { --bg: ($p.ui.backdrop); --bg-transparent: ($p.ui.backdrop)ee; --surface: ($surface); --fg: ($p.ui.normal); --accent: ($p.ui.accent); --focus: ($p.ui.focus); --on-focus: ($on_focus); --muted: ($p.ui.minor); --unfocus: ($p.ui.unfocus); --error: ($p.error); --warning: ($p.warning); --info: ($p.info); --debug: ($p.debug); --border: ($p.ui.accent);}" | save --raw --force $out}def apply-mode [mode: string] { mkdir (cache-dir) let p = (palette $mode) $mode | save --raw --force (mode-file) write-desktop-color-scheme $mode # Disabled until Hyprtoolkit handles live config rewrites without busy-looping: # https://github.com/hyprwm/hyprtoolkit/issues/92 # write-hyprtoolkit $mode $p write-mako $mode $p write-ironbar $mode $p try { hyprctl hyprpaper wallpaper $",~/.config/hypr/wallpapers/nugu-($mode).png" | ignore } try { hyprctl reload | ignore } if (($env.NUGU_NO_RESTART_MAKO? | default "") != "1") { try { systemctl --user restart mako.service | ignore } } try { systemctl --user restart ironbar.service | ignore } if (($env.NUGU_NO_NOTIFY? | default "") != "1") { try { notify-send --expire-time 1500 "nugu" $"($mode) mode" | ignore } }}def next-mode [] { if (active-mode) == "dark" { "light" } else { "dark" } }def main [mode: string = "toggle"] { let manual = $mode in [dark light toggle] if $manual { set-auto false } if $mode == "auto" { set-auto true } let target = match $mode { "dark" => "dark", "light" => "light", "toggle" => (next-mode), "auto" => (auto-mode), "current" => (active-mode), "watch" => { watch; return }, _ => { error make { msg: "mode must be dark|light|toggle|auto|current|watch" } }, } apply-mode $target}def watch [] { loop { if (auto-enabled) { let target = (auto-mode) if $target != (active-mode) { apply-mode $target } } sleep 5min }}hypr/scripts/tui_tab.lua
Deleteddeleted file mode 100644+0 / −36 text lines
local M = {}local function shell_quote(value) value = tostring(value) return "'" .. value:gsub("'", "'\\''") .. "'"endlocal function trim(value) return (value or ""):gsub("^%s+", ""):gsub("%s+$", "")endlocal function run(command) local pipe = io.popen(command .. " 2>/dev/null") if not pipe then return nil end local output = pipe:read("*a") pipe:close() return trim(output)endfunction M.spawn(...) local args = { ... } if #args == 0 then return end for i, arg in ipairs(args) do args[i] = shell_quote(arg) end local pane_id = run("wezterm cli --prefer-mux spawn -- " .. table.concat(args, " ")) if pane_id and pane_id:match("^%d+$") then hl.exec_cmd("wezterm cli --prefer-mux activate-pane --pane-id " .. shell_quote(pane_id)) endendreturn Mhypr/systemd/cliphist.service
Deleteddeleted file mode 100644+0 / −12 text lines
hypr/systemd/ironbar-workspaces.service
Deleteddeleted file mode 100644+0 / −13 text lines
[Unit]Description=Instant Ironbar workspace stateAfter=graphical-session.target ironbar.servicePartOf=graphical-session.target ironbar.service[Service]ExecStart=%h/.config/ironbar/scripts/workspaces-watch.pyRestart=on-failureRestartSec=1Slice=session.slice[Install]WantedBy=graphical-session.targethypr/systemd/ironbar.service
Deleteddeleted file mode 100644+0 / −14 text lines
[Unit]Description=Ironbar Wayland status barPartOf=graphical-session.targetAfter=graphical-session.target nugu-theme.serviceWants=nugu-theme.service[Service]Environment=GSK_RENDERER=cairoExecStart=/usr/bin/ironbarRestart=on-failureRestartSec=2[Install]WantedBy=graphical-session.targethypr/systemd/mako.service
Deleteddeleted file mode 100644+0 / −15 text lines
[Unit]Description=Mako notification daemonPartOf=graphical-session.targetAfter=graphical-session.target[Service]Environment=NUGU_NO_RESTART_MAKO=1Environment=NUGU_NO_NOTIFY=1ExecStartPre=/usr/bin/nu %h/.config/hypr/scripts/theme.nu currentExecStart=/usr/bin/mako --config %h/.config/mako/configRestart=on-failureRestartSec=2[Install]WantedBy=graphical-session.targethypr/systemd/nugu-theme.service
Deleteddeleted file mode 100644+0 / −13 text lines
[Unit]Description=Nugu automatic light/dark desktop modePartOf=graphical-session.targetAfter=graphical-session.target hyprpaper.serviceWants=hyprpaper.service[Service]ExecStart=/usr/bin/nu %h/.config/hypr/scripts/theme.nu watchRestart=on-failureRestartSec=10[Install]WantedBy=graphical-session.targethypr/systemd/wl-clip-persist.service
Deleteddeleted file mode 100644+0 / −12 text lines
hypr/wallpapers/nugu-dark.png
Deleteddeleted file mode 100644Binary size (old → new): 9858 → 0 bytes.
hypr/wallpapers/nugu-light.png
Deleteddeleted file mode 100644Binary size (old → new): 131656 → 0 bytes.
ironbar/PLAN.md
Deleteddeleted file mode 100644+0 / −715 text lines
# Ironbar rework planGoal: rebuild the bar incrementally, one widget/behavior at a time, with Nugu colors, consistent clicks, and verification after each step.Workflow rule:1. Propose exact minimal change.2. Experiment safely when behavior is unknown.3. Apply focused changes.4. Verify live with config validation, service state, logs, screenshots, and interaction tests.5. Remove superfluous widgets/CSS/scripts.Originally: stop after each step for discussion.Current standing goal: continue autonomously to completion while preserving brutal verification.Order rule: start with Bluetooth as requested, then proceed roughly easiest → hardest.## Current statusDone/live:- Bluetooth stack installed/running: `bluez`, `bluez-utils`, `bluetooth.service` active.- `bluetui` installed and preferred as Bluetooth manager.- Ironbar Bluetooth widget is status-only; builtin popup disabled because GTK switch popup looked bad.- Bluetooth left/middle click opens `bluetui` through shared Hypr Lua TUI launcher.- Ironbar icon theme switched to installed `Adwaita`.- Ironbar `popup_autohide = true` globally.- WezTerm mux service added under `wezterm/systemd/wezterm-mux-server.service`, enabled and active.- WezTerm config attaches GUI to Unix mux (`connect unix`) and status shows `MUX` for mux domain.- Hypr `SUPER+Enter` opens `wezterm connect unix`.- Hypr TUI app binds: - `SUPER+E` → `yazi` - `SUPER+N` → `impala` - `SUPER+U` → `bluetui`- TUI launcher activates the newly spawned WezTerm pane/tab.- XWayland disabled; obsolete XWayland drag workaround removed.- Mouse accel switched to adaptive; natural scroll enabled.Known unresolved:- No hard blocker.- Physical wheel/trackpad scroll over the volume module remains unverified because `wdotool scroll` does not trigger Ironbar layer-shell scroll events here.- Existing visible WezTerm local-domain sessions may need manual migration/closure; no seamless transfer to mux known.## Current live audit- Repo clean, ahead of origin; Ironbar commits are local.- Running services verified active: `ironbar.service`, `ironbar-workspaces.service`, `mako.service`, `hyprpaper.service`, `pipewire-pulse.socket`, system `upower.service`, system `bluetooth.service`.- Resource usage after settling: `ironbar` about 1.3% CPU / 77M RSS; `workspaces-watch.py` 0.0% CPU / 15M RSS.- Regions use Ironbar `start` / `center` / `end` boxes: - start: custom workspace switcher, clipboard, bindmode - center: music, clock - end: Mako status, WiFi, Bluetooth, tray, CPU, volume, brightness, battery, inhibit, power- Polling/wakeups: - Mako status script: 5000ms, shell + `makoctl list | grep` - WiFi status script: 30000ms, shell + `iwctl station wlan0 show` - sys_info CPU: interval 2 - workspace state: Hypr socket2 event watcher, 10s idle refresh, no label polling- Scroll handlers: - volume: `wpctl set-volume -l 1 @DEFAULT_AUDIO_SINK@ 2%+` / `wpctl set-volume @DEFAULT_AUDIO_SINK@ 2%-`, `smooth_scroll_speed = 1.0` - brightness: builtin systemd backlight backend, `smooth_scroll_speed = 0.5`- Hardcoded color grep reports only generated `ironbar/nugu.css`; `style.css` uses semantic Nugu vars.- Known broken/unproven widget behavior: physical volume scroll only. Slider drag and the configured scroll commands are verified.## Checked facts- Installed Ironbar: `0.19.0`.- `ironbar --print-schema` exposes needed modules: - `battery`, `bindmode`, `bluetooth`, `brightness`, `clipboard`, `clock`, `custom`, `focused`, `inhibit`, `launcher`, `music`, `notifications`, `script`, `sys_info`, `tray`, `volume`, `workspaces`.- WiFi stack: `iwd` + systemd-networkd. - `iwd.service`: active. - `NetworkManager`: not installed. - Ironbar `network_manager` module is wrong unless we intentionally switch network stacks.- Notifications: Mako currently. - Ironbar `notifications` module requires SwayNC. - SwayNC would replace/compete with Mako, so defer.- `hyprshutdown` installed; keybind uses `--dry-run`.- Music config must use `player_type = "mpris"`, not `playerctl`.- Builtin Ironbar workspaces dispatch legacy Hypr syntax; custom switcher is used for Lua-dispatcher compatibility.- Workspace highlighting is event-driven via Hypr socket2 + Ironbar vars; no polling labels.## Upstream feature noteFrom Ironbar compiling wiki/features:- Default build enables all features.- Custom builds can disable defaults and enable selected features.- Must enable at least one config feature.- If custom-building for this setup:```textcli,config+json,workspaces+hyprland,focused,launcher,music+mpris,sys_info,script,custom,tray,volume,battery,bluetooth,brightness,bindmode,inhibit,clipboard,clock,notifications```Notes:- `cli` implies `ipc`.- `network_manager` omitted while using `iwd`.- `notifications` only useful if switching to SwayNC.## Preferences / launch policy- Work one thing at a time: propose → experiment → change → verify.- Prefer awesome fast TUIs when they exist (`bluetui`, `impala`, `btm`, `wiremix`, `yazi`, etc.).- Prefer mux-backed WezTerm tabs for TUI apps over standalone terminal windows.- Prefer implementation logic in Lua over shell snippets; shell command strings are acceptable only at process boundary.- Prefer `require(...)` modules over `dofile(...)` in normal config and shared helpers.- Shared TUI launch logic lives in Hypr Lua: `hypr/scripts/tui_tab.lua`.- 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.- TUI launcher should spawn into WezTerm mux and activate the new pane/tab.- Keep app-specific service/config files in app dirs when possible, e.g. WezTerm systemd unit under `wezterm/systemd/`.- Avoid fighting ugly GTK popups when a better TUI exists; use Ironbar as status/launcher if builtin popup is poor.## Package/dependency reportAlready installed:- `ironbar`- `hyprshutdown`- `playerctl`- `iwd`- `brightnessctl`- `bluez`- `bluez-utils`- `bluetui`- `impala`- `wezterm-nightly-bin`- `upower`- `pipewire-pulse`No longer planned:```shsudo pacman -S pavucontrol swaync networkmanager```Reasons:- `wiremix` replaces `pavucontrol` for audio.- Mako stays; SwayNC would replace/compete with it.- WiFi stack stays `iwd` + systemd-networkd; no NetworkManager.Optional only if requested later:```shsudo pacman -S resources```Avoid unless intentionally switching network stack:```shsudo pacman -S networkmanager```## Verification loop for every step1. Edit only one widget/behavior.2. Validate: ```sh ironbar --validate-config -c ~/.config/ironbar/config.json -t ~/.config/ironbar/style.css ```3. Restart: ```sh systemctl --user restart ironbar.service ```4. Inspect: ```sh systemctl --user status ironbar.service --no-pager journalctl --user -u ironbar.service -n 80 --no-pager ```5. Screenshot / visual check.6. Discuss before next step.## Click convention- Left: popup or primary action.- Right: toggle/mute/secondary action.- Middle: open full external tool/TUI.- Scroll: adjust continuous value.- Tooltip: document behavior.## WezTerm mux policy- WezTerm GUI should attach to Unix mux by default: - `cfg.unix_domains = { { name = "unix", no_serve_automatically = true } }` - `cfg.default_gui_startup_args = { "connect", "unix" }`- Mux server is systemd-managed: - `wezterm/systemd/wezterm-mux-server.service`- WezTerm status should make mux visible: - domain `unix` renders as `MUX`.- Hypr terminal bind should explicitly use mux: - `wezterm connect unix`- TUI app launcher should: 1. spawn into mux with `wezterm cli --prefer-mux spawn -- ...` 2. capture pane id in Lua 3. activate pane with `wezterm cli --prefer-mux activate-pane --pane-id ...`- Existing non-mux GUI sessions cannot be seamlessly transferred into mux; recreate/close manually.## Nugu styling rules- Generated colors stay in `ironbar/nugu.css`.- Layout/behavior stay in `ironbar/config.json` + `ironbar/style.css`.- Use vars: - normal fg: `--fg` - muted/empty: `--muted` / `--unfocus` - active bg: `--focus`, fg `--on-focus` - hover/accent bg: `--accent`, fg `--on-focus` - error: `--error`## Ordered implementation steps### Step 1 — Bluetooth — doneWhy first: explicit request.Implemented:- `bluez` + `bluez-utils` installed by user; `bluetooth.service` active.- `bluetui` installed and preferred.- Ironbar builtin `bluetooth` module used only for bar status.- Builtin Bluetooth popup disabled; GTK switch popup looked bad even after CSS work.- Left/middle click opens `bluetui` through shared Hypr Lua TUI launcher: - `hyprctl eval 'require("scripts.tui_tab").spawn("bluetui")'`- Bar label uses fixed semantic Bluetooth battery icon, not dynamic percentage icon: - ` {device_battery_percent}%`- `icon_theme` switched from missing `Papirus` to installed `Adwaita`; broken device image fixed.Verified:- Ironbar config validates.- Ironbar restarts and stays active.- Popup autohide works globally.- Bluetooth status visible; clicks open `bluetui`.Follow-up if wanted:- Tune bar label length/format.- Add notification if Bluetooth disconnected/low battery.### Step 2 — baseline validation + obvious fixesDifficulty: very easy.Scope:- Fix music `player_type`: `playerctl` → `mpris`.- Add `name`/`class` only where needed for CSS targeting.- No layout rework.Verify:- Config validates.- Ironbar starts cleanly.### Step 3 — trayDifficulty: very easy.Goal:- Keep tray widget.- Improve popover padding/colors if needed.Verify:- Existing tray icons render.- Menus/popovers readable.### Step 4 — clock/calendar colorsDifficulty: easy.Goal:- Fix hard-to-read calendar popup.Scope:- CSS only.- Explicit GTK calendar selectors: - `.popup-clock calendar` - `.popup-clock calendar header` - `.popup-clock calendar grid label.day-name` - `.popup-clock calendar grid label.day-number` - `.popup-clock calendar grid label.other-month` - `.popup-clock calendar grid label.today` - `.popup-clock calendar grid label:selected`Verify:- Popup readable in dark + light.- Today/current/other-month/day-name colors use Nugu vars.### Step 5 — clipboardDifficulty: easy.Goal:- Keep clipboard widget and make behavior explicit.Proposed behavior:- Left: popup/list.- Middle: optional external launcher later.- Right: do **not** clear history unless confirmed.Verify:- Popup readable.- Selection/paste still works.### Step 6 — volume — doneGoal:- Make volume behavior consistent.Implemented:- Builtin `volume` module.- Scroll adjusts PipeWire output volume.- Right click mutes output.- Middle click opens `wiremix` through shared Hypr Lua TUI launcher.- Sources hidden on bar to reduce clutter.Verified:- `pipewire-pulse.socket` active.- Ironbar logs show volume client connected, no `PAErr(-1)`.- `wiremix` spawned into WezTerm mux tab and activated.- Popup/device picker colors fixed for dark+light Nugu.- Slider drag verified with `wdotool`: volume changed from 55% to 7%, then restored to 55% and unmuted.- Scroll actions are configured as oneshot scripts and `smooth_scroll_speed = 1.0` is explicit for wheel/trackpad input.- The exact scroll commands were executed manually: 55% → 57% → 55%.- `wdotool scroll` does not trigger Ironbar layer-shell scroll events in this live setup, so physical scroll remains the remaining manual check.### Step 7 — battery — doneDifficulty: easy.Goal:- Add/keep robust battery widget.Implementation:- Builtin `battery` module.- Show icon + percent.- Style low/critical/charging states using Nugu semantic colors.Verified:- Hidden on machines without `BAT*` via `show_if`.- Shows X230 battery percentage.- `upower` active.- Warning/critical states styled with Nugu semantic colors.### Step 8 — brightness — doneDifficulty: easy-medium.Goal:- Add brightness widget.Implementation:- Builtin `brightness` module.- Use `systemd`/`backlight` backend.Implemented:- Builtin brightness module with `systemd`/`intel_backlight` backend.- Scroll adjusts brightness through Ironbar backend.- Rejected custom `brightnessctl` script experiment because direct set failed without permission.Verified:- Detects `intel_backlight`.- Brightness visible/readable in screenshots.- No config/service errors.Known issue (scroll does not change brightness):- `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.`- 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.Note on `udev` `uaccess`:- 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.Note on polkit `login1.set-brightness`:- `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.Arch 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. ```sh # udev/backlight.rules ACTION=="add", SUBSYSTEM=="backlight", KERNEL=="intel_backlight", RUN+="/usr/bin/chgrp video /sys/class/backlight/intel_backlight/brightness" ACTION=="add", SUBSYSTEM=="backlight", KERNEL=="intel_backlight", RUN+="/usr/bin/chmod g+w /sys/class/backlight/intel_backlight/brightness" ``` ```sh doas install -m 0644 /home/oli/Workspace/dotfiles/udev/backlight.rules /etc/udev/rules.d/backlight.rules doas udevadm control --reload doas udevadm trigger --subsystem-match=backlight --action=add doas usermod -aG video oli # log out / log in (or `newgrp video` for current shell) ``` 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).### Step 9 — bindmodeDifficulty: easy-medium.Goal:- Show Hyprland submap/bindmode only when active.Implementation:- Builtin `bindmode` module.Verify:- Hidden during normal use.- Appears/disappears correctly if a Hypr submap is active.### Step 10 — inhibit — doneDifficulty: medium.Goal:- Add sleep/lock inhibition toggle.Implementation:- Builtin `inhibit` module.Proposed behavior:- Left: toggle selected duration.- Right: cycle duration.- Format off/on clearly.Verified:- Toggle visible/readable.- Duration visible in screenshot.- No Ironbar errors.### Step 11 — cute cat widget — skipped/removedReason:- Cute but superfluous under the current goal.- Removed after screenshot showed the right/center area was already dense.Verified:- Bar validates/restarts without it.- Center media has more room.### Step 12 — media/player controls — doneDifficulty: medium.Goal:- Make media useful and compact.Implementation:- Builtin `music` module with MPRIS.- Format: status icon + truncated title/artist.- Popup: album art + controls.Implemented:- Builtin `music` module with MPRIS.- Compact title/artist format with truncation.- No extra scroll action; avoid accidental media changes.Verified:- Firefox/MPRIS player detected.- Title visible and compact at 1366px.- Popup styled by Nugu CSS.### Step 13 — system monitorsDifficulty: medium.Goal:- Add compact system monitor row.Implementation:- Builtin `sys_info` module.Candidate labels:- CPU percent.- RAM percent.- Temperature.- Disk root percent.- Network up/down.Implemented:- Compact CPU label via builtin `sys_info`.- Left/middle opens `btm` through shared Hypr Lua TUI launcher.Useful install:```shsudo pacman -S bottom```Optional GUI:```shsudo pacman -S resources```Verify:- Values update at sane intervals.- Compact enough for 1366px.- No excessive CPU wakeups.### Step 14 — power menuDifficulty: medium-hard.Goal:- Polish power menu using installed `hyprshutdown`.Implementation:- `custom` module popup.Candidate buttons:- poweroff: `hyprshutdown --post-cmd "systemctl poweroff"`- reboot: `hyprshutdown --post-cmd "systemctl reboot"`- logout: `hyprshutdown`- suspend: `loginctl lock-session && systemctl suspend`- lock: `hyprlock`- 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.Verify:- Popup opens.- Lock/suspend/logout work.- Do not test reboot/poweroff without explicit confirmation.### Step 15 — notifications — doneDecision:- Keep Mako.- Do not install SwayNC; it would replace/compete with Mako.- Ironbar builtin `notifications` module remains unused.Implemented:- Custom Mako indicator script: - empty: `` - active notifications: ` N`- Left click: `makoctl restore`.- Right click: `makoctl dismiss --all`.Verified:- Mako service active.- Count visible/readable in screenshots.- Dismissing all notifications via Mako works.- No SwayNC dependency.### Step 16 — WiFi / network — doneDecision:- Keep `iwd` + systemd-networkd.- Do not install/use NetworkManager.Implemented:- Custom script module reads `iwctl station wlan0 show`.- Connected state is icon-only to reduce clutter.- Disconnected state shows ` off`.- Left/middle click opens `impala` through shared Hypr Lua TUI launcher.Verified:- `iwd.service` active.- `networkctl status wlan0` routable/online.- WiFi icon visible/readable.- No NetworkManager dependency.### Step 17 — workspaces — doneGoal:- Show fixed workspace favorites.- Logical order: - `1 web` - `2 code` - `3 term` - `4 chat` - `5 media` - `9 misc`- Empty favorites remain visible.- Active/occupied/empty states readable.- Click focuses correct workspace.Problem found:- Builtin Ironbar `workspaces` sends legacy `hyprctl dispatch workspace N`.- Hyprland Lua dispatcher rejects that syntax: - `error: [string "return hl.dispatch(workspace 1)"]:1: ')' expected near '1'`Implemented:- Migrated Hypr workspace rules/binds/window rules to numeric IDs.- Replaced builtin Ironbar workspaces with a custom workspace switcher.- Each button uses Lua dispatcher syntax: - `hyprctl eval 'hl.dispatch(hl.dsp.focus({ workspace = "N" }))'`- Replaced old polling `ironbar/scripts/workspace-label.lua` with `ironbar/scripts/workspaces-watch.py`.- Watcher listens to Hypr socket2 and writes Ironbar vars (`#ws1`, `#ws2`, ...), making highlight update immediately on switch.- Watcher uses direct Hypr Unix socket IPC for state reads and only writes changed Ironbar vars.- Watcher caches the Hypr socket directory and Nugu CSS vars, avoiding repeated `hyprctl instances` subprocesses and repeated CSS file reads on every workspace event.- Added `hypr/systemd/ironbar-workspaces.service`, symlink manifest entry, and service enable recipe.- `ironbar-workspaces.service` is `PartOf=ironbar.service` so bar restarts immediately refresh workspace vars.- Removed unused builtin `.workspaces` CSS.- Removed launcher underline styling after screenshot showed it clashed with the active workspace/focused launcher pills.- Increased system-module spacing slightly; verified clock/power still fit on 1366px.- Removed unused `.notifications` CSS and normalized `.sysinfo` spacing.- Removed normal `scratch` workspace from the bar; special scratch remains on `SUPER+S`.Verified:- Hypr reload ok; no config errors.- Existing named `web`/`term` windows moved to numeric `1`/`3`.- All six icons visible; no tofu/question mark glyphs.- Empty workspace active-state update verified 0.2s after click.- Service active and low overhead: `ironbar` ~1.8% CPU shortly after restart, watcher ~0.2% CPU / 6.6M RSS on X230.- Clicks verified via `wdotool`: - workspace `1` focuses `id=1` - empty workspace `2` focuses `id=2` - workspace `3` focuses `id=3`- Ironbar logs contain no workspace dispatch errors after custom switcher.## Suggested final bar layoutStart:1. workspaces2. clipboard3. bindmodeRemoved:- focused window module; active app/title was redundant and made the left side noisy.- launcher module; colorful app/window icons broke the semantic Nugu bar aesthetic.Center:1. media/player2. clockEnd:1. Mako indicator2. WiFi icon4. Bluetooth battery/status5. tray6. sys_info CPU7. volume8. brightness9. battery10. inhibit11. power menuInteraction polish:- All hover states use the same semantic accent background + on-focus foreground, including music and clipboard.- Generic `:checked` styling was removed; persistent state is explicit per widget.- Power and volume checked/focus states are explicitly neutral so clicking elsewhere clears visible highlight.- Clock popup time/month/year/arrows/days were screenshot-verified readable after GTK calendar selector fixes.- Clipboard grouped with left utilities; notifications grouped with right status.- Bar edge padding increased so power does not sit flush against the display edge.- Region/group spacing added between workspace/utility and right-side connectivity/metrics/inhibit groups.- Active workspace pill widened to make instant highlight easier to see.- WiFi polling relaxed to 30s because connected state is icon-only and detail action opens `impala`.- 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.- Destructive power actions were not clicked during validation.- Power popup visual test confirmed destructive off/reboot buttons sit away from the opener cursor side.## Open decisions- Media scroll: next/prev, volume, or none? Current: no scroll action.- Optional later: richer Mako popup/history UI. Current: compact count + restore/dismiss actions.ironbar/config.json
Deleteddeleted file mode 100644+0 / −255 text lines
{ "icon_theme": "Adwaita", "position": "top", "height": 30, "popup_autohide": true, "popup_gap": 4, "start": [ { "type": "custom", "name": "workspace-switcher", "class": "nugu-workspaces", "bar": [ { "type": "box", "widgets": [ { "type": "button", "class": "workspace-item", "label": "#ws1", "on_click": "!hyprctl eval 'hl.dispatch(hl.dsp.focus({ workspace = \"1\" }))'" }, { "type": "button", "class": "workspace-item", "label": "#ws2", "on_click": "!hyprctl eval 'hl.dispatch(hl.dsp.focus({ workspace = \"2\" }))'" }, { "type": "button", "class": "workspace-item", "label": "#ws3", "on_click": "!hyprctl eval 'hl.dispatch(hl.dsp.focus({ workspace = \"3\" }))'" }, { "type": "button", "class": "workspace-item", "label": "#ws4", "on_click": "!hyprctl eval 'hl.dispatch(hl.dsp.focus({ workspace = \"4\" }))'" }, { "type": "button", "class": "workspace-item", "label": "#ws5", "on_click": "!hyprctl eval 'hl.dispatch(hl.dsp.focus({ workspace = \"5\" }))'" }, { "type": "button", "class": "workspace-item", "label": "#ws9", "on_click": "!hyprctl eval 'hl.dispatch(hl.dsp.focus({ workspace = \"9\" }))'" } ] } ], "tooltip": "Workspaces: web code term chat media misc" }, { "type": "clipboard", "max_items": 5, "truncate": { "mode": "end", "length": 30 } }, { "type": "bindmode", "truncate": { "mode": "end", "max_length": 20 } } ], "center": [ { "type": "music", "player_type": "mpris", "format": "{title} / {artist}", "truncate": { "mode": "end", "max_length": 42 } }, { "type": "clock", "format": "%H:%M" } ], "end": [ { "type": "script", "class": "mako-status", "cmd": "~/.config/ironbar/scripts/mako-status.sh", "mode": "poll", "interval": 5000, "on_click_left": "makoctl restore", "on_click_right": "makoctl dismiss --all", "tooltip": "Notifications: left restores last, right dismisses all" }, { "type": "script", "class": "wifi", "cmd": "~/.config/ironbar/scripts/wifi-status.sh", "mode": "poll", "interval": 30000, "on_click_left": "hyprctl eval 'require(\"scripts.tui_tab\").spawn(\"impala\")'", "on_click_middle": "hyprctl eval 'require(\"scripts.tui_tab\").spawn(\"impala\")'", "tooltip": "WiFi: left/middle opens impala" }, { "type": "bluetooth", "format": { "not_found": "", "disabled": "", "enabled": "", "connected": "", "connected_battery": " {device_battery_percent}%" }, "disable_popup": true, "on_click_left": "hyprctl eval 'require(\"scripts.tui_tab\").spawn(\"bluetui\")'", "on_click_middle": "hyprctl eval 'require(\"scripts.tui_tab\").spawn(\"bluetui\")'", "tooltip": "Bluetooth: left/middle opens bluetui" }, { "type": "tray", "icon_size": 14 }, { "type": "sys_info", "format": [" {cpu_percent:1}%"], "interval": { "cpu": 2 }, "on_click_left": "hyprctl eval 'require(\"scripts.tui_tab\").spawn(\"btm\")'", "on_click_middle": "hyprctl eval 'require(\"scripts.tui_tab\").spawn(\"btm\")'", "tooltip": "System monitor: left/middle opens btm" }, { "type": "volume", "on_scroll_up": "wpctl set-volume -l 1 @DEFAULT_AUDIO_SINK@ 2%+", "on_scroll_down": "wpctl set-volume @DEFAULT_AUDIO_SINK@ 2%-", "on_click_right": "wpctl set-mute @DEFAULT_AUDIO_SINK@ toggle", "on_click_middle": "hyprctl eval 'require(\"scripts.tui_tab\").spawn(\"wiremix\")'", "smooth_scroll_speed": 1.0, "show_sources": false, "tooltip": "Volume: scroll adjusts, right mutes, middle opens wiremix" }, { "type": "brightness", "format": "{percentage}%", "icon_label": "display-brightness-symbolic", "mode": { "type": "systemd", "subsystem": "backlight", "name": "intel_backlight" }, "smooth_scroll_speed": 0.5, "tooltip": "Brightness: scroll adjusts display" }, { "type": "battery", "format": "{percentage}%", "icon_size": 10, "show_if": "ls /sys/class/power_supply/ | grep -q '^BAT'", "profiles": { "warning": { "percent": 20 }, "critical": { "when": { "percent": 5, "charging": false }, "format": " {percentage}%" } }, "tooltip": "Battery: left opens details" }, { "type": "inhibit", "durations": ["00:30:00", "01:00:00", "02:00:00", "inf"], "default_duration": "00:30:00", "format_on": " {duration}", "format_off": " {duration}", "tooltip": "Inhibit: left toggles, right cycles duration" }, { "type": "custom", "name": "power-menu", "class": "power-menu", "bar": [ { "type": "button", "name": "power-btn", "label": "", "on_click": "popup:toggle" } ], "popup": [ { "type": "box", "orientation": "vertical", "widgets": [ { "type": "label", "name": "header", "label": "power" }, { "type": "box", "name": "buttons", "widgets": [ { "type": "button", "class": "power-btn danger", "label": " off", "on_click": "!hyprshutdown --post-cmd \"systemctl poweroff\"" }, { "type": "button", "class": "power-btn", "label": " reboot", "on_click": "!hyprshutdown --post-cmd \"systemctl reboot\"" }, { "type": "button", "class": "power-btn", "label": " out", "on_click": "!hyprshutdown" }, { "type": "button", "class": "power-btn", "label": " sleep", "on_click": "!loginctl lock-session && systemctl suspend" }, { "type": "button", "class": "power-btn", "label": " lock", "on_click": "!hyprlock" } ] }, { "type": "label", "name": "uptime", "label": "up {{30000:uptime -p | cut -d ' ' -f2-}}" } ] } ], "tooltip": "Power menu" } ]}ironbar/nugu.css
Deleteddeleted file mode 100644+0 / −17 text lines
/* Generated by hypr/scripts/theme.nu from Nugu palette. */:root { --bg: #242424; --bg-transparent: #242424ee; --surface: #9d9d9d; --fg: #dbdbdb; --accent: #d86dd8; --focus: #9aabae; --on-focus: #121212; --muted: #9d9d9d; --unfocus: #6f6f6f; --error: #ec6376; --warning: #f0ee69; --info: #3ec5e3; --debug: #ed5eed; --border: #d86dd8;}ironbar/scripts/mako-status.sh
Deleteddeleted file mode 100755+0 / −7 text lines
ironbar/scripts/wifi-status.sh
Deleteddeleted file mode 100755+0 / −12 text lines
ironbar/scripts/workspaces-watch.py
Deleteddeleted file mode 100755+0 / −148 text lines
#!/usr/bin/env python3import jsonimport osimport selectimport socketimport subprocessimport timefrom pathlib import PathWORKSPACES = [ ("1", ""), ("2", ""), ("3", ""), ("4", ""), ("5", ""), ("9", ""),]EVENT_PREFIXES = ( "workspace", "focusedmon", "createworkspace", "destroyworkspace", "moveworkspace", "openwindow", "closewindow", "movewindow", "urgent",)last_vars: dict[str, str] = {}color_mtime = 0color_vars: dict[str, str] = {}hypr_socket_dir = ""def css_vars() -> dict[str, str]: global color_mtime, color_vars config_home = Path(os.environ.get("XDG_CONFIG_HOME", Path.home() / ".config")) path = config_home / "ironbar" / "nugu.css" mtime = path.stat().st_mtime_ns if mtime == color_mtime: return color_vars colors: dict[str, str] = {} for line in path.read_text().splitlines(): if ":" not in line: continue name, value = line.strip().rstrip(";").split(":", 1) name = name.strip() value = value.strip() if name.startswith("--") and value.startswith("#"): colors[name[2:]] = value color_mtime = mtime color_vars = colors return colorsdef hypr_dir() -> str: global hypr_socket_dir if hypr_socket_dir: return hypr_socket_dir sig = os.environ.get("HYPRLAND_INSTANCE_SIGNATURE") if not sig: result = subprocess.run(("hyprctl", "instances", "-j"), text=True, capture_output=True, check=False) instances = json.loads(result.stdout or "[]") sig = instances[0]["instance"] hypr_socket_dir = f"{os.environ['XDG_RUNTIME_DIR']}/hypr/{sig}" return hypr_socket_dirdef hypr_cmd(command: str) -> str: with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as sock: sock.settimeout(1) sock.connect(f"{hypr_dir()}/.socket.sock") sock.sendall(command.encode()) chunks: list[bytes] = [] while True: chunk = sock.recv(65536) if not chunk: break chunks.append(chunk) return b"".join(chunks).decode("utf-8", "replace")def event_socket_path() -> str: return f"{hypr_dir()}/.socket2.sock"def markup(ws_id: str, icon: str, active: str, occupied: set[str], colors: dict[str, str]) -> str: if ws_id == active: return '<span foreground="{}" background="{}" font_weight="bold"> {} </span>'.format( colors["on-focus"], colors["focus"], icon, ) if ws_id in occupied: return '<span foreground="{}">{}</span>'.format(colors["fg"], icon) return '<span foreground="{}">{}</span>'.format(colors["muted"], icon)def hypr_state() -> tuple[str, set[str]]: active = json.loads(hypr_cmd("j/activeworkspace") or "{}") workspaces = json.loads(hypr_cmd("j/workspaces") or "[]") return str(active.get("id", "")), {str(ws.get("id")) for ws in workspaces if ws.get("windows", 0) > 0}def set_var(name: str, value: str) -> None: if last_vars.get(name) == value: return subprocess.run(("ironbar", "var", "set", name, value), stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, check=False) last_vars[name] = valuedef update() -> None: colors = css_vars() active, occupied = hypr_state() for ws_id, icon in WORKSPACES: set_var(f"ws{ws_id}", markup(ws_id, icon, active, occupied, colors))def watch() -> None: global hypr_socket_dir while True: update() try: with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as sock: sock.connect(event_socket_path()) pending = b"" while True: ready, _, _ = select.select([sock], [], [], 10) if not ready: update() continue chunk = sock.recv(4096) if not chunk: break pending += chunk while b"\n" in pending: raw, pending = pending.split(b"\n", 1) line = raw.decode("utf-8", "replace") if line.startswith(EVENT_PREFIXES): update() except Exception: hypr_socket_dir = "" time.sleep(1)if __name__ == "__main__": watch()ironbar/style.css
Deleteddeleted file mode 100644+0 / −617 text lines
@import url("nugu.css");:root { --radius: 7px; --font-size: 12px;}* { font-family: 'IBM Plex Mono'; font-size: var(--font-size); border: none; box-shadow: none; background-image: none; text-shadow: none; -gtk-icon-shadow: none; border-radius: 0;}window, popover, popover contents { background-color: var(--bg-transparent); color: var(--fg); border-radius: var(--radius);}#bar { background-color: var(--bg); padding: 0 20px; border-bottom: 2px solid var(--accent);}box, button, label { background: transparent; background-image: none; color: var(--fg);}button { min-height: 0; padding: 1px 7px; border-radius: var(--radius); background: transparent;}button:hover, button:active { background: var(--accent); color: var(--on-focus);}button:hover label,button:active label,button:hover image,button:active image { color: var(--on-focus);}.nugu-workspaces { margin-left: 4px; margin-right: 10px;}.nugu-workspaces .workspace-item { min-height: 0; margin: 0 2px; padding: 1px 5px; color: var(--muted);}.nugu-workspaces .workspace-item:hover { background: var(--accent); color: var(--on-focus);}.bindmode { margin-left: 8px; padding: 1px 7px; border-radius: var(--radius); background: var(--warning); color: var(--bg); font-weight: bold;}.popup-music { padding: 12px;}.popup-music .album-art { border-radius: var(--radius); margin-right: 12px;}.volume { margin: 0 7px;}.popup-volume { padding: 12px; background-color: var(--bg-transparent); color: var(--fg);}.popup-volume .device-box,.popup-volume .apps-box { background-color: transparent; color: var(--fg);}.popup-volume .device-selector,.popup-volume .device-selector button,.popup-volume dropdown,.popup-volume dropdown button { background: var(--accent); color: var(--on-focus); border-radius: var(--radius);}.popup-volume .device-selector label,.popup-volume .device-selector arrow,.popup-volume .device-selector *,.popup-volume dropdown button,.popup-volume dropdown button * { background: transparent; color: var(--on-focus);}.popup-volume .btn-mute { color: var(--fg);}.popup-volume .btn-mute:hover,.popup-volume .btn-mute:checked { background: var(--accent); color: var(--on-focus);}popover listview,popover list,popover row,popover modelbutton { background-color: var(--bg); color: var(--fg);}popover listview row,popover list row { padding: 6px 10px;}popover listview row label,popover list row label,popover row label,popover modelbutton label { color: var(--fg);}popover listview row:hover,popover list row:hover,popover row:hover,popover modelbutton:hover { background-color: var(--accent); color: var(--on-focus);}popover listview row:hover label,popover list row:hover label,popover row:hover label,popover modelbutton:hover label { color: var(--on-focus);}popover listview row:selected,popover list row:selected,popover row:selected,popover modelbutton:checked { background-color: var(--focus); color: var(--on-focus);}popover listview row:selected label,popover list row:selected label,popover row:selected label,popover modelbutton:checked label { color: var(--on-focus);}/* GTK dropdown popovers are separate popovers, not children of .popup-volume. */popover contents listview,popover contents list,popover contents row,popover contents modelbutton,popover contents button { background: var(--bg); color: var(--fg);}popover contents row *,popover contents modelbutton *,popover contents button * { color: var(--fg);}popover contents row:hover,popover contents modelbutton:hover,popover contents button:hover { background: var(--accent); color: var(--on-focus);}popover contents row:hover *,popover contents modelbutton:hover *,popover contents button:hover * { color: var(--on-focus);}popover contents row:selected,popover contents modelbutton:checked,popover contents button:checked { background: var(--focus); color: var(--on-focus);}popover contents row:selected *,popover contents modelbutton:checked *,popover contents button:checked * { color: var(--on-focus);}.popup-volume dropdown popover,.popup-volume dropdown popover contents,.popup-volume dropdown popover listview,.popup-volume dropdown popover row { background: var(--bg); color: var(--fg);}.popup-volume dropdown popover label,.popup-volume dropdown popover row *,.popup-volume dropdown popover listview * { color: var(--fg);}.popup-volume dropdown popover row:hover { background: var(--accent);}.popup-volume dropdown popover row:selected { background: var(--accent);}.popup-volume dropdown popover row:selected * { color: var(--on-focus);}scale trough { min-height: 6px; min-width: 6px; background-color: var(--unfocus); border-radius: var(--radius);}scale highlight { min-height: 6px; min-width: 6px; background-color: var(--accent); border-radius: var(--radius);}.brightness { margin: 0 7px; color: var(--fg);}.battery { margin: 0 7px; color: var(--fg);}.battery.warning { color: var(--warning);}.battery.critical { color: var(--error); font-weight: bold;}.popup-battery { padding: 10px 12px; background-color: var(--bg-transparent); color: var(--fg);}.popup-battery .details { color: var(--muted);}.inhibit { margin: 0 7px 0 12px; color: var(--muted);}.inhibit button:checked,.inhibit button:active { background: var(--accent); color: var(--on-focus);}.clock { font-weight: bold; margin: 0 7px; color: var(--accent);}.popup-clock { padding: 12px; background-color: var(--bg-transparent); color: var(--fg);}.popup-clock *,.popup-clock calendar.view header,.popup-clock calendar.view header *,.popup-clock calendar.view header stack.month,.popup-clock calendar.view header label.year { color: var(--fg);}.popup-clock .calendar-clock { background: var(--accent); color: var(--on-focus); border-radius: var(--radius); padding: 2px 8px; margin-bottom: 8px;}.popup-clock .calendar-clock,.popup-clock .calendar-clock * { color: var(--on-focus); font-weight: bold;}.popup-clock calendar { background: transparent; color: var(--fg); border-radius: var(--radius);}.popup-clock calendar header { border-bottom: 1px solid var(--unfocus); padding-bottom: 6px; margin-bottom: 6px;}.popup-clock calendar button:hover,.popup-clock calendar.view header button:hover,.popup-clock calendar.view header button:hover * { background: var(--accent); color: var(--on-focus);}.popup-clock calendar grid label.day-name,.popup-clock calendar grid label.week-number { color: var(--muted);}.popup-clock calendar grid label.day-number { color: var(--fg); border-radius: var(--radius);}.popup-clock calendar grid label.other-month { color: var(--unfocus);}.popup-clock calendar grid label.today { color: var(--accent); font-weight: bold;}.popup-clock calendar grid label:selected { background: var(--focus); color: var(--on-focus);}.music { margin: 0 7px; color: var(--fg);}.clipboard { margin: 0 10px 0 12px;}.popup-clipboard { padding: 8px;}.popup-clipboard .item { padding: 4px 8px; border-radius: var(--radius); color: var(--fg);}.popup-clipboard .item label { color: var(--fg);}.popup-clipboard .item:hover { background-color: var(--accent); color: var(--on-focus);}.popup-clipboard .item:hover label { color: var(--on-focus);}.mako-status { margin: 0 7px 0 12px; color: var(--fg);}.wifi { margin: 0 7px; color: var(--fg);}.bluetooth { margin: 0 7px;}.bluetooth.disabled,.bluetooth.not-found { color: var(--muted);}.bluetooth.enabled { color: var(--fg);}.bluetooth.connected { color: var(--fg);}.tray { margin: 0 7px 0 12px;}.tray popover contents { padding: 8px;}.power-menu { margin-left: 12px;}.power-menu button,.power-menu #power-btn { color: var(--muted);}.power-menu button:hover,.power-menu #power-btn:hover { background: var(--accent); color: var(--on-focus);}.power-menu button:checked,.power-menu button:focus,.power-menu #power-btn:checked,.power-menu #power-btn:focus { background: transparent; color: var(--muted);}.popup-power-menu { padding: 12px; background-color: var(--bg-transparent); color: var(--fg);}.popup-power-menu #header { font-size: 14px; font-weight: bold; margin-bottom: 8px; padding-bottom: 8px; color: var(--accent); border-bottom: 1px solid var(--unfocus);}.popup-power-menu #buttons { margin-bottom: 8px;}.popup-power-menu .power-btn { background-color: transparent; border: 1px solid var(--unfocus); border-radius: var(--radius); padding: 6px 10px; margin: 0 3px; color: var(--fg);}.popup-power-menu .power-btn:hover { background-color: var(--accent); border-color: var(--accent); color: var(--on-focus);}.popup-power-menu .power-btn.danger { border-color: var(--error);}.popup-power-menu .power-btn.danger:hover { background-color: var(--accent); border-color: var(--accent); color: var(--on-focus);}.popup-power-menu #uptime { color: var(--muted);}.sysinfo { margin: 0 7px 0 16px;}.sysinfo > .item + .item { margin-left: 8px;}.music:hover,.clipboard:hover,.mako-status:hover,.wifi:hover,.bluetooth:hover,.tray:hover,.sysinfo:hover,.volume:hover,.brightness:hover,.battery:hover,.inhibit:hover,.clock:hover { background: var(--accent); color: var(--on-focus); border-radius: var(--radius);}.music:hover label,.clipboard:hover label,.mako-status:hover label,.wifi:hover label,.bluetooth:hover label,.tray:hover label,.sysinfo:hover label,.volume:hover label,.brightness:hover label,.battery:hover label,.inhibit:hover label,.clock:hover label { color: var(--on-focus);}.music:checked,.music:focus,.clipboard:checked,.clipboard:focus,.mako-status:checked,.mako-status:focus,.wifi:checked,.wifi:focus,.bluetooth:checked,.bluetooth:focus,.tray:checked,.tray:focus,.sysinfo:checked,.sysinfo:focus,.volume:checked,.volume:focus,.volume button:checked,.volume button:focus,.brightness:checked,.brightness:focus,.battery:checked,.battery:focus,.clock:checked,.clock:focus { background: transparent; color: var(--fg);}.music:checked label,.music:focus label,.clipboard:checked label,.clipboard:focus label,.mako-status:checked label,.mako-status:focus label,.wifi:checked label,.wifi:focus label,.bluetooth:checked label,.bluetooth:focus label,.tray:checked label,.tray:focus label,.sysinfo:checked label,.sysinfo:focus label,.volume:checked label,.volume:focus label,.brightness:checked label,.brightness:focus label,.battery:checked label,.battery:focus label,.clock:checked label,.clock:focus label { color: var(--fg);}.popup { padding: 8px;}justfile
Deleteddeleted file mode 100644+0 / −223 text lines
set shell := ["nu", "--commands"]
default:
@just --list
# initialize crypto, install hooks, verify, link dorkfiles into HOME
link: nugu-linux-console nugu-hypr
java bootstripper.java bootstrap
# build generated files needed by linked shell config
nugu-linux-console:
just --justfile nugu/justfile --working-directory nugu linux-console
nugu-hypr:
just --justfile nugu/justfile --working-directory nugu hypr
# verify crypto filters, hooks, and staged secrets
check:
java bootstripper.java check
clean:
java bootstripper.java clean
# run the same checks as the Git pre-commit hook
pre-commit:
java bootstripper.java pre-commit
# integration test in ephemeral rootless Podman Linux; fresh system deps: git + java
# tests every *.symlinks manifest; primary hostname printed first for quick failure context
test hostname="desktop":
#!/usr/bin/env bash
set -euo pipefail
root="$(git rev-parse --show-toplevel)"
key="$root/.git/dotfiles-aes.key"
image="registry.fedoraproject.org/fedora:latest"
container="dotfiles-integration-$(date +%Y%m%d%H%M%S)-$$"
if [ ! -r "$key" ]; then
echo "missing $key"
exit 1
fi
trap 'podman rm -f "$container" >/dev/null 2>&1 || true' EXIT
echo "container=$container"
podman run --name "$container" --rm -i --hostname "{{hostname}}" \
-e PRIMARY_HOSTNAME="{{hostname}}" \
-v "$root:/src:ro" \
-v "$key:/dotfiles-aes.key:ro" \
"$image" bash -s <<'CONTAINER'
set -euo pipefail
ok() { echo "ok:$1"; }
fail() { echo "FAIL:$1"; exit 1; }
target_path() {
local home="$1"
local target="$2"
if [[ "$target" == ~* ]]; then
printf '%s%s\n' "$home" "${target:1}"
else
printf '%s\n' "$target"
fi
}
targets_for() {
awk '
{ sub(/\r$/, "") }
NF == 0 { next }
source == "" { source = $0; next }
{ print $0; source = "" }
END { if (source != "") exit 2 }
' "$1"
}
run_manifest() {
local host="$1"
local manifest="$host.symlinks"
local home="/tmp/home-$host"
local bootstrap_log="/tmp/bootstrap-$host.log"
local check_log="/tmp/check-$host.log"
local clean_log="/tmp/clean-$host.log"
echo "manifest=$manifest"
rm -rf "$home"
mkdir -p "$home"
HOSTNAME="$host" java -Duser.home="$home" bootstripper.java bootstrap >"$bootstrap_log" 2>&1 || {
echo "FAIL:bootstrap:$host"
tail -120 "$bootstrap_log"
exit 1
}
ok "bootstrap:$host"
HOSTNAME="$host" java -Duser.home="$home" bootstripper.java check >"$check_log" 2>&1 || {
echo "FAIL:check:$host"
cat "$check_log"
exit 1
}
ok "check:$host"
while IFS= read -r target; do
local path
path="$(target_path "$home" "$target")"
test -L "$path" || fail "link:$host:$target"
done < <(targets_for "$manifest")
ok "links:$host"
HOSTNAME="$host" java -Duser.home="$home" bootstripper.java clean >"$clean_log" 2>&1 || {
echo "FAIL:clean:$host"
cat "$clean_log"
exit 1
}
ok "clean:$host"
}
fresh_crypto_smoke() {
local repo=/tmp/fresh-crypto
rm -rf "$repo" /tmp/fresh-crypto-home
mkdir -p "$repo/tools" /tmp/fresh-crypto-home
cp bootstripper.java "$repo/"
cp tools/aes.java "$repo/tools/"
cd "$repo"
git init --quiet
printf 'secret.txt\n' > .secrets
printf 'dummy.txt\n~/dummy.txt\n' > mini.symlinks
printf 'not a real secret\n' > secret.txt
printf 'dummy\n' > dummy.txt
DOTFILES_AES_PASSPHRASE=test java bootstripper.java init-crypto >/tmp/fresh-init.log 2>&1 || { cat /tmp/fresh-init.log; fail fresh-init; }
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; }
git add .dotfiles-aes-salt .secrets bootstripper.java tools/aes.java mini.symlinks dummy.txt secret.txt
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; }
git show :secret.txt | head -c 6 | grep -qx DFAES1 || fail fresh-staged-encrypted
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; }
test -L /tmp/fresh-crypto-home/dummy.txt || fail fresh-link
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; }
ok fresh-crypto
}
printf 'rootless='
awk 'NR == 1 { print ($1 == 0 && $2 != 0) ? "yes" : "unknown" }' /proc/self/uid_map
if ! dnf -qy --setopt=install_weak_deps=False install git-core java-latest-openjdk-headless >/tmp/dnf.log 2>&1; then
cat /tmp/dnf.log
fail deps
fi
ok deps
git --version
java -version 2>&1 | sed -n '1p'
mkdir -p /root/work
git config --global --add safe.directory /src
git clone --quiet --no-local /src /root/work/dotfiles || fail clone
install -m 600 /dotfiles-aes.key /root/work/dotfiles/.git/dotfiles-aes.key
cd /root/work/dotfiles
java bootstripper.java install-hooks >/tmp/install-hooks.log 2>&1 || { cat /tmp/install-hooks.log; fail install-hooks; }
test -x .git/hooks/pre-commit || fail hook-executable
grep -qx 'exec java bootstripper.java pre-commit' .git/hooks/pre-commit || fail hook-content
ok install-hooks
git show HEAD:nushell/secrets.nu | head -c 6 | grep -qx DFAES1 || fail committed-encrypted
ok committed-encrypted
mapfile -t hosts < <(find . -maxdepth 1 -name '*.symlinks' -printf '%f\n' | sed 's/\.symlinks$//' | sort)
printf 'primary-manifest=%s.symlinks\n' "$PRIMARY_HOSTNAME"
printf 'manifests=%s\n' "${hosts[*]}"
for host in "${hosts[@]}"; do
run_manifest "$host"
done
ok "symlink-manifests:${#hosts[@]}"
if head -c 6 nushell/secrets.nu | grep -qx DFAES1; then
fail worktree-still-encrypted
fi
ok worktree-decrypted
java bootstripper.java pre-commit >/tmp/precommit.log 2>&1 || { echo FAIL:pre-commit; cat /tmp/precommit.log; exit 1; }
grep -q 'Skipping gitleaks: command not found' /tmp/precommit.log || fail gitleaks-optional
ok pre-commit
fresh_crypto_smoke
echo RESULT:ok
CONTAINER
# create initial crypto salt
init-crypto:
java bootstripper.java init-crypto
# install Git hooks
hooks:
java bootstripper.java install-hooks
# enable some user systemd services
services:
nu enable_user_services.nu
# remove links to dorkfiles from HOME
unlink:
java bootstripper.java clean
# typically the initial git remote for the dotfiles repo is https
# this command changes the remote to ssh
ssh-remote:
git remote rm origin
git remote add origin git@github.com:bugabinga/dotfiles.git
git fetch
git branch --set-upstream-to=origin/trunk trunk
# initial setup: link dotfiles, enable services, fix permissions
setup: link services fix_permissions
# install previously exported winget apps. see topgrade config for exports.
import_winget:
winget import C:/Users/okr/Tools/winget_installed_apps.json
# fix some file permissions
fix_permissions:
let firefox_profile = ('~/.mozilla/firefox/qrza8u52.default-release' | path expand); if ($firefox_profile | path exists) { chmod 700 $firefox_profile }
mako/config
Deleteddeleted file mode 100644+0 / −43 text lines
include=~/.config/mako/nugu.conffont=IBM Plex Sans 10border-size=2border-radius=12padding=12,14margin=8outer-margin=14anchor=top-rightlayer=overlaywidth=360height=160max-visible=4max-history=80sort=-priorityicons=1max-icon-size=48icon-border-radius=7markup=1actions=1history=1ignore-timeout=1default-timeout=6500format=%a\n<b>%s</b>\n%bon-button-left=invoke-default-actionon-button-middle=dismiss-groupon-button-right=dismiss[urgency=low]default-timeout=2500[urgency=normal]default-timeout=6500[urgency=critical]border-size=3default-timeout=0[grouped]format=%a · %g\n<b>%s</b>\n%b[hidden]format=+%h more notificationsmako/nugu.conf
Deleteddeleted file mode 100644+0 / −33 text lines
# Generated by hypr/scripts/theme.nu from Nugu palette.background-color=#242424eetext-color=#dbdbdbffborder-color=#d86dd8ffprogress-color=over #9aabaeff[urgency=low]background-color=#121212e6text-color=#8b8b8bffborder-color=#6f6f6fffprogress-color=over #8b8b8bff[urgency=normal]border-color=#d86dd8ffprogress-color=over #9aabaeff[urgency=critical]background-color=#242424fftext-color=#f3effbffborder-color=#ec6376ffprogress-color=over #ec6376ff[summary~="[Ee]rror|[Ff]ailed|[Ff]ailure|[Cc]rash"]border-color=#ec6376ffprogress-color=over #ec6376ff[summary~="[Ww]arn|[Ww]arning"]border-color=#f0ee69ffprogress-color=over #f0ee69ff[summary~="[Ii]nfo|[Nn]otice"]border-color=#3ec5e3ffprogress-color=over #3ec5e3ffmise.android.toml
Addednew file mode 100644+2 / −0 text lines
mise.lock
Addednew file mode 100644+20 / −0 text lines
# @generated - this file is auto-generated by `mise lock` https://mise.jdx.dev/dev-tools/mise-lock.html[[tools.java]]version = "27.0.1+0"backend = "core:java"[tools.java.options]shorthand_vendor = "temurin"[tools.java."platforms.linux-arm64"]checksum = "sha256:5ddacf925244a00b60cac828b61ff2f67a68cd32b8dfe5cee1405e333b4589e5"url = "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"[tools.java."platforms.linux-x64"]checksum = "sha256:30cb129f6cf299c852cec0feca9ea2a596d2ee9f26d8605d3a253951f6c8b20f"url = "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"[tools.java."platforms.windows-x64"]checksum = "sha256:5fac419f00d2256941a6b1253a827bb8b904da215a1ec0667035e5592811c1dc"url = "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
Addednew file mode 100644+141 / −0 text lines
[tools]java = "latest"[task_config]shell = "java scripts/mise_shell.java"[tasks.default]description = "List tasks"hide = truerun = 'run("mise", "tasks", "ls");'[tasks.check]description = "Verify crypto, hooks, secrets, and symlink manifests"run = 'run("java", "bootstripper.java", "check");'[tasks.ci]description = "Run committed-state Podman CI check"run = 'run("java", "./scripts/dotfiles_integration_test.java");'[tasks.ci-check]description = "Run the CI check suite"hide = truerun = 'run("java", "./scripts/dotfiles_integration_test.java", "--inside");'[tasks.crypto-test]description = "Run the complete crypto acceptance suite"hide = truerun = 'run("java", "./scripts/dotfiles_integration_test.java", "--crypto");'[tasks.crypto-git-test]description = "Run focused encrypted Git filter and merge tests"run = 'run("java", "./scripts/dotfiles_integration_test.java", "--crypto-git");'[tasks.crypto-restore-test]description = "Run focused encrypted-secret restoration tests"run = 'run("java", "./scripts/dotfiles_integration_test.java", "--crypto-restore");'[tasks.fresh-checkout-crypto-test]description = "Test link-time crypto setup from a fresh encrypted checkout"run = 'run("java", "./scripts/dotfiles_integration_test.java", "--fresh-checkout-crypto");'[tasks.bootstrap-test]description = "Run focused bootstrap and platform-selection tests"run = 'run("java", "./scripts/dotfiles_integration_test.java", "--bootstrap");'[tasks.hooks-test]description = "Run isolated Git hook and link integration tests"run = 'run("java", "./scripts/dotfiles_integration_test.java", "--hooks");'[tasks.mise-shell-test]description = "Run focused Mise Java task-shell tests"run = 'run("java", "./scripts/dotfiles_integration_test.java", "--mise-shell");'[tasks.mise-route-test]description = "Test the production Mise link-task route"run = 'run("java", "./scripts/dotfiles_integration_test.java", "--mise-route");'[tasks.manifests-test]description = "Validate all repository symlink manifest contracts"run = 'run("java", "./scripts/dotfiles_integration_test.java", "--manifest-contracts");'[tasks.process-harness-test]description = "Test integration subprocess timeout and cleanup"run = 'run("java", "./scripts/dotfiles_integration_test.java", "--process-cleanup");'[tasks.secrets-scan]description = "Scan committed Git history for plaintext secrets"run = 'run("gitleaks", "git", "--redact=100", "--no-banner", "--log-opts=--all --full-history --diff-merges=first-parent --no-ext-diff --no-textconv");'[tasks.link]description = "Converge crypto and hooks, validate manifests, and link dorkfiles into HOME"run = 'run("java", "bootstripper.java", "link");'[tasks.setup-crypto]description = "Configure crypto and decrypt unchanged checkout secrets; refuse local changes"run = 'run("java", "bootstripper.java", "setup-crypto");'[tasks.clean]description = "Remove managed dorkfiles links from HOME"run = 'run("java", "bootstripper.java", "clean");'[tasks.init]description = "Create initial crypto salt"hide = truerun = 'run("java", "bootstripper.java", "init-crypto");'[tasks.hook]description = "Install Git hooks"hide = truerun = 'run("java", "bootstripper.java", "install-hooks");'[tasks.fix]description = "Fix local file permissions"hide = truerun = 'run("java", "scripts/fix_permissions.java");'[tasks.niri-test]description = "Test Niri modernization inspector, Nugu generation, and config loading"run = '''run("node", "--test", "niri/.pi/skills/modernize/scripts/inspect.test.mjs");run("node", "--test", "niri/config.test.mjs", "niri/theme.test.mjs");run("nu", "--no-config-file", "nugu/mode.test.nu");'''[tasks.nugu-termux]description = "Generate both Nugu Termux palettes without selecting a mode"run = '''cd("nugu");run("just", "--shell", "nu", "--clear-shell-args", "--shell-arg=--no-config-file", "--shell-arg=--commands", "termux");'''[tasks.termux-test]description = "Test Nugu Termux generation and manual theme switching"run = '''run("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)'} } }");run("node", "--test", "termux/theme.test.mjs");'''[tasks.wezterm-test]description = "Test WezTerm modernization and instance helpers"run = '''run("node", "--test", "wezterm/.pi/skills/modernize/scripts/inspect.test.mjs");run("nu", "--no-config-file", "wezterm/tests/wezterm_instances_test.nu");'''[tasks.nushell-markdown-test]description = "Test standalone Markdown rendering and To-Do integration"run = 'run("nu", "--no-config-file", "nushell/tests/markdown.test.nu");'[tasks.nushell-pi-test]description = "Test Pi discovery, full-history reader, rendering, and CLI passthrough"run = '''run("nu", "--no-config-file", "nushell/tests/pi.test.nu");run("nu", "--no-config-file", "nushell/tests/pi-reader.test.nu");'''[tasks.win32-drive-test]description = "Test the win32-drive skill script against a fixture window (takes over the Windows desktop)"run = '''run("powershell.exe", "-NoProfile", "-ExecutionPolicy", "Bypass", "-File", "pi/agent/skillz/win32-drive/scripts/win32-drive.test.ps1");'''mise/.mise/locks/npm-cf/1.0.0-beta.16/aube-lock.yaml
Addednew file mode 100644+615 / −0 text lines
lockfileVersion: '9.0'settings: autoInstallPeers: true excludeLinksFromLockfile: falseimporters: .: dependencies: cf: specifier: 1.0.0-beta.16 version: 1.0.0-beta.16packages: '@cloudflare/build-output-utils@0.9.1': resolution: {integrity: sha512-zTzHGwXD7dJ1+vWlVgvTWbg1k0x53+Wu1aR6MDWAflOwJD9KtHjz7Qqq6pnTbVxlR0m5GLlD6sshEuiKnB1KQA==} '@cloudflare/codemods@0.4.2': resolution: {integrity: sha512-oHvDlfhQEIkdf8Mvz4SMgk+6evVlu9rrntRv5KQfRK3H4RkXUmawzYQ7+zdBG0wiWdp/Ku/PqNMWVYAs8T4jrQ==} hasBin: true '@cloudflare/config@0.25.0': resolution: {integrity: sha512-h4tgL9/pmeoIdKfs/irfV/eCotbEpbadO2RGPbHwRij6Ek7q8Gqx4juSoDSb/fk9IclansgAHXF9b8rb3Kw4jg==} '@cloudflare/runtime-types@0.1.10': resolution: {integrity: sha512-OXEpo7VZ/ALsLGzKCX4n0Dknnf1w3W6wCWELiKyW6MUd7JRvd23KSTrUKIHLJaBpXR1hTKCqWBUWUHBn2wZbnQ==} '@cloudflare/workerd-darwin-64@1.20261006.1': resolution: {integrity: sha512-lCX6avJO2It9AyDEYitjmOtJRVp/xmaW0TziyoLAnfxlzozyyRbSFfIIMMCiDx/sTP1++E4VLbV+7BHSD33f0Q==} engines: {node: '>=16'} cpu: [x64] os: [darwin] '@cloudflare/workerd-darwin-arm64@1.20261006.1': resolution: {integrity: sha512-PyFGjOaldtppnLuKsdkoYWXfLVpDjuf8u+uoykX+1Xvxo2EPmCVViq0iDKm+U7c7PRno85ehS3/MPVXyk2HwHw==} engines: {node: '>=16'} cpu: [arm64] os: [darwin] '@cloudflare/workerd-linux-64@1.20261006.1': resolution: {integrity: sha512-Ntf9S8eesmVufdjaT2kzWlz6Ng9XGYTc6cHQVRKAg59lFufwsIabGeMT6U4KkrpEeSIxgHq8aPtuLbZXE19tCA==} engines: {node: '>=16'} cpu: [x64] os: [linux] '@cloudflare/workerd-linux-arm64@1.20261006.1': resolution: {integrity: sha512-JyeDBymVWw5tVRebSsVE8ojDYxd6UlZrAseHU8G+NpIyd5wF61tXlF/axLeCUqu0pOhBFHb8I5QKi0jwrCK41Q==} engines: {node: '>=16'} cpu: [arm64] os: [linux] '@cloudflare/workerd-windows-64@1.20261006.1': resolution: {integrity: sha512-nWP0URNqOBN9fa/gZ7eh/w051DwjOXN8j4lDZDYVXyQPsux6sV3DfyYZT+CjR/rt9nKBSmJT9QE9/bWT18+84w==} engines: {node: '>=16'} cpu: [x64] os: [win32] '@cspotcode/source-map-support@0.8.1': resolution: {integrity: sha512-IchNf6dN4tHoMFIn/7OE8LWZ19Y6q/67Bmf6vnGREv8RSbBVb9LPJxEcnwrcwX6ixSvaiGoomAUvu4YSxXrVgw==} engines: {node: '>=12'} '@emnapi/runtime@1.11.3': resolution: {integrity: sha512-Xz4Tpyki7XyrpbUK1jR1AhdAdaXyhhY4lZ3neLodmhpuWfy2PAQN5B46sAiU4liOXGLkHypn/qU+jvfWSCYYLA==} '@img/colour@1.1.0': resolution: {integrity: sha512-Td76q7j57o/tLVdgS746cYARfSyxk8iEfRxewL9h4OMzYhbW4TAcppl0mT4eyqXddh6L/jwoM75mo7ixa/pCeQ==} engines: {node: '>=18'} '@img/sharp-darwin-arm64@0.35.5': resolution: {integrity: sha512-QRUlFQ0WxvdWyqqG/WtI3iupfD5rBzmCHXSdPsY91sAtVtTo7Q4cb6zOccZ3gqEqkr0f1As1ehLqmEpDsRf+lg==} engines: {node: '>=20.9.0'} cpu: [arm64] os: [darwin] '@img/sharp-darwin-x64@0.35.5': resolution: {integrity: sha512-+BR255RhDlpygUpOc/Jdt1nT6DQ3XG/ERo5wbcdOf5Q320dKtPCKPLR1LJs9VGXRaMa8l1uUa0tkCNOXiAxZUw==} engines: {node: '>=20.9.0'} cpu: [x64] os: [darwin] '@img/sharp-freebsd-wasm32@0.35.5': resolution: {integrity: sha512-Y/z91nEZ4uIBX5X3nfTovjU9lHNKFYbL2lpHCLVNmXQK03VIZvXBBt0KxbPGp2SdGSF+2mQU4e+hQaWOt86iAw==} engines: {node: '>=20.9.0'} os: [freebsd] '@img/sharp-libvips-darwin-arm64@1.3.4': resolution: {integrity: sha512-5R89nBYiRdUlSWJxPhO+GVtaXzXSxKnRu/xqMn3KTA3L9EB9Oy/P+Nn2f2vlhPuUdy/Zusb2DarbyTpGCfEDuw==} cpu: [arm64] os: [darwin] '@img/sharp-libvips-darwin-x64@1.3.4': resolution: {integrity: sha512-iR2OKH80yi0U+dUplyh3/xdpFvps6YkCwsXenIJxqxR1v9o+xtKTGbS9H7cps+2Vxjc8B1j96p75NmTGjIhtpQ==} cpu: [x64] os: [darwin] '@img/sharp-libvips-linux-arm64@1.3.4': resolution: {integrity: sha512-Y3dgX/6lE2QhQb+Gxy0WZxfg9MEm/JBjamZpS2IklP7xIQoKN4hzAm7KcMVGtaVDt3neE9OKBC7vAfonA/Lr1A==} cpu: [arm64] os: [linux] libc: [glibc] '@img/sharp-libvips-linux-arm@1.3.4': resolution: {integrity: sha512-LmRtTsOHuvM2+wlO2Db37dx5MiZhB0FvSunciw48YjdOkZz9KAiRbm8ujeMOA1INqmei5NapFxYEK1D1ZSidmw==} cpu: [arm] os: [linux] libc: [glibc] '@img/sharp-libvips-linux-ppc64@1.3.4': resolution: {integrity: sha512-Le6boB8Tai0Nis+gIxIpKx68UDVVIqdR8Tin5Yf1z2LJJQLDJvCDRqRu+jC2qCoD+eIomonmOwB4smBRxfVpYQ==} cpu: [ppc64] os: [linux] libc: [glibc] '@img/sharp-libvips-linux-riscv64@1.3.4': resolution: {integrity: sha512-aHkkIEHPRdQEegJN20MLmGtxYD9R2wQr3Cwpddnu5+YKMt6Uzax7S9h5gpZTo8wyrGuZSlfQ63OevL5mTyOC7Q==} cpu: [riscv64] os: [linux] libc: [glibc] '@img/sharp-libvips-linux-s390x@1.3.4': resolution: {integrity: sha512-ra/mB6MikESDUO7Yg+Mi95bFBb9GsObURuhnOv3OqknjGe9sZrG8tCe9q0xSIGrtLgvgw0gKnFWcK4blSgQOuQ==} cpu: [s390x] os: [linux] libc: [glibc] '@img/sharp-libvips-linux-x64@1.3.4': resolution: {integrity: sha512-GJ//SSXbnwSDes02umB3nDJLFcQzw8a18V8fyhqr6tV515tOEMdImjjxj1AoafMRz56F3PHgftnj1QEKSU1zkw==} cpu: [x64] os: [linux] libc: [glibc] '@img/sharp-libvips-linuxmusl-arm64@1.3.4': resolution: {integrity: sha512-hvulFwtjUcagsis6BBxHwGFwWoNZjgYmULGVrZcyfNbjA8hKILbRxGg15/7w5HDyXHXUos/j6baAWqnCyQ2DWA==} cpu: [arm64] os: [linux] libc: [musl] '@img/sharp-libvips-linuxmusl-x64@1.3.4': resolution: {integrity: sha512-6zXKeE/p39I1AmA3cJG35eyBGNqNddLnUXjhwBnsGjFPWqf5VKkDBEqaEkPDoTEtkxwi2vv8Tcr2mDyP4So7Fg==} cpu: [x64] os: [linux] libc: [musl] '@img/sharp-linux-arm64@0.35.5': resolution: {integrity: sha512-LYVx5JTsOM2CBzmxreh+nl64/3H6Xb09iSLknqH47z2T2DFFxDeFLP5y4dJwe6H7uGQlHPyEEtIqyo3DYsRwdQ==} engines: {node: '>=20.9.0'} cpu: [arm64] os: [linux] libc: [glibc] '@img/sharp-linux-arm@0.35.5': resolution: {integrity: sha512-LEaXK2WdXVK5ykcw0buWyPMsmLLL2vpHLD6yrNSW+JGEL3BZPA4tpKN6iaMc4AxTTAoaX/sU1rOL51lcIz48ZQ==} engines: {node: '>=20.9.0'} cpu: [arm] os: [linux] libc: [glibc] '@img/sharp-linux-ppc64@0.35.5': resolution: {integrity: sha512-QVxAAq8evVRI9ia2vqgwrmWucn5Dfv+JdWzj75pD8omHLPSP7f8p20O8jxzjCcuCEQEOtYOZUmX1hkiZ0kdevA==} engines: {node: '>=20.9.0'} cpu: [ppc64] os: [linux] libc: [glibc] '@img/sharp-linux-riscv64@0.35.5': resolution: {integrity: sha512-LtdreXguaavKODPIfzJ4kffx7UNt1omwtK0rch4EBbbSTXPnxWmYSayXdLJw0fJzQ97kHt1gL/yh4tvU+nCyRQ==} engines: {node: '>=20.9.0'} cpu: [riscv64] os: [linux] libc: [glibc] '@img/sharp-linux-s390x@0.35.5': resolution: {integrity: sha512-UZasTOFiYzotTsGOCu42BfUzP6Tu6Do/947iRm1RsLKvlllxwGcn4RN27LibGWceix4Y+Pmw3jsnTcCQIgWjqA==} engines: {node: '>=20.9.0'} cpu: [s390x] os: [linux] libc: [glibc] '@img/sharp-linux-x64@0.35.5': resolution: {integrity: sha512-SxFtLTeJInhAA9Q836kux2vZNeOBQEx658qvbboZScr0wIARym3IcGmW7KpVD5sbVg0Ojy+udFQdayYIZyoNog==} engines: {node: '>=20.9.0'} cpu: [x64] os: [linux] libc: [glibc] '@img/sharp-linuxmusl-arm64@0.35.5': resolution: {integrity: sha512-9HbMclmI1zlNkFRs3z9/eBtDjfD0sGlrX1z6b1qwmiFY5ElDLh4BC0LPBdVp7z1DXFiKlIcznf+ZlsuZzLxQqg==} engines: {node: '>=20.9.0'} cpu: [arm64] os: [linux] libc: [musl] '@img/sharp-linuxmusl-x64@0.35.5': resolution: {integrity: sha512-4KOphqB035HrVdqLZfCgMzzERrQkkzOwRhl4OAkRO1YCldbaFjySXMaK534Mo0V+LndnlJk+sbUyLeU0ULyD1A==} engines: {node: '>=20.9.0'} cpu: [x64] os: [linux] libc: [musl] '@img/sharp-wasm32@0.35.5': resolution: {integrity: sha512-Ptsga1su4tQx+LLF1ECS9U6nz5kmrXKo6XVbtR48Ke3ZRxxgaWBu7IDtEe1quo8hiupwm6WFqxVlXaSf7IINGQ==} engines: {node: '>=20.9.0'} '@img/sharp-webcontainers-wasm32@0.35.5': resolution: {integrity: sha512-hfhF/FmoQyTUkA0bIKFOtw536BQSeBMe6BF6QyWlrPxT754+TFLaZ7sKKTfvvM0yJgKgaYTwnFCIZ/GuDw5SUA==} engines: {node: '>=20.9.0'} cpu: [wasm32] '@img/sharp-win32-arm64@0.35.5': resolution: {integrity: sha512-X4t7g+7ZA5DKblCBEXGjUqqemj4vczING/5viFwAL8h4N3qYeyjwdCvRLHi4EdOUI+2Z7UFlp1VM+p/AuEtm6Q==} engines: {node: '>=20.9.0'} cpu: [arm64] os: [win32] '@img/sharp-win32-ia32@0.35.5': resolution: {integrity: sha512-5Zm82LoBc43nhwNybZlG7Y1KO//Zhsn306fQl29ZOuStHLGTo3BWL83q3cznX0poxSAMuYL1On/BHBxkBeKr6A==} engines: {node: ^20.9.0} cpu: [ia32] os: [win32] '@img/sharp-win32-x64@0.35.5': resolution: {integrity: sha512-x76eH0vEiHlcMQu8Y8IenntaACtddpT6W0wmXtWrnKcnKI7ME5DdgqhAD6SEWOEl1v2zDvkZDhFA9KnURwpfqg==} engines: {node: '>=20.9.0'} cpu: [x64] os: [win32] '@jridgewell/resolve-uri@3.1.2': resolution: {integrity: sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==} engines: {node: '>=6.0.0'} '@jridgewell/sourcemap-codec@1.6.0': resolution: {integrity: sha512-T7jf+5zgsZHwNJ4lvQ7/aezbyk0nNX+zJVWpmHA7VYsEx7a7qr5Rg5IbtJFqkgze5Y2sruq1RUY8Q837Od7iFw==} '@jridgewell/trace-mapping@0.3.9': resolution: {integrity: sha512-3Belt6tdc8bPgAtbcmdtNJlirVoTmEb5e2gC94PnkwEW9jI6CAHUeoG85tjWP5WquqfavoMtMwiG4P926ZKKuQ==} '@poppinss/colors@4.1.6': resolution: {integrity: sha512-H9xkIdFswbS8n1d6vmRd8+c10t2Qe+rZITbbDHHkQixH5+2x1FDGmi/0K+WgWiqQFKPSlIYB7jlH6Kpfn6Fleg==} '@poppinss/dumper@0.6.5': resolution: {integrity: sha512-NBdYIb90J7LfOI32dOewKI1r7wnkiH6m920puQ3qHUeZkxNkQiFnXVWoE6YtFSv6QOiPPf7ys6i+HWWecDz7sw==} '@poppinss/exception@1.2.3': resolution: {integrity: sha512-dCED+QRChTVatE9ibtoaxc+WkdzOSjYTKi/+uacHWIsfodVfpsueo3+DKpgU5Px8qXjgmXkSvhXvSCz3fnP9lw==} '@sindresorhus/is@7.2.0': resolution: {integrity: sha512-P1Cz1dWaFfR4IR+U13mqqiGsLFf1KbayybWwdd2vfctdV6hDpUkgCY0nKOLLTMSoRd/jJNjtbqzf13K8DCCXQw==} engines: {node: '>=18'} '@speed-highlight/core@1.2.24': resolution: {integrity: sha512-qeW2e1l78afw8VhRPfPQ1Gjj+KU5XFQ/OFV5ti6eTa9bruO7mJyZtA4vw0ofqmA3tKCkROE9xLk3VZoeRc98nw==} blake3-wasm@2.1.5: resolution: {integrity: sha512-F1+K8EbfOZE49dtoPtmxUQrpXaBIl3ICvasLh+nJta0xkz+9kF/7uet9fLnwKqhDrmj6g+6K3Tw9yQPUg2ka5g==} cf@1.0.0-beta.16: resolution: {integrity: sha512-buY0XUHp+wAA0paOKxdUr5UgLKhO8xkeJL5Pn2Xt1UQLfqPFKrqTC3mKrGsrmOhf8Qyn4Omxc4F/8x37fa9kVA==} engines: {node: '>=22'} hasBin: true cookie@1.1.1: resolution: {integrity: sha512-ei8Aos7ja0weRpFzJnEA9UHJ/7XQmqglbRwnf2ATjcB9Wq874VKH9kfjjirM6UhU2/E5fFYadylyhFldcqSidQ==} engines: {node: '>=18'} detect-libc@2.1.2: resolution: {integrity: sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==} engines: {node: '>=8'} error-stack-parser-es@1.0.5: resolution: {integrity: sha512-5qucVt2XcuGMcEGgWI7i+yZpmpByQ8J1lHhcL7PwqCwu9FPP3VUXzT4ltHe5i2z9dePwEHcDVOAfSnHsOlCXRA==} kleur@4.1.5: resolution: {integrity: sha512-o+NO+8WrRiQEE4/7nwRJhN1HWpVmJm511pBHUxPLtp0BUISzlBplORYSmTclCnJvQq2tKu/sgl3xVpkc7ZWuQQ==} engines: {node: '>=6'} miniflare@5.20261006.2-beta: resolution: {integrity: sha512-agufWI3mXF8xGzry2/sOF8Im8AoYs04DWBCLDWDmd4QtMSGEo9IgrPmYOwsCmQA3K3MbLzsvr01GpWc8x3Duqw==} engines: {node: '>=22.0.0'} minisearch@7.2.0: resolution: {integrity: sha512-dqT2XBYUOZOiC5t2HRnwADjhNS2cecp9u+TJRiJ1Qp/f5qjkeT5APcGPjHw+bz89Ms8Jp+cG4AlE+QZ/QnDglg==} semver@7.8.6: resolution: {integrity: sha512-9lpSSU4Mly3mrtruwLs1eLK6+gzbzqeBFwRNjIjE+9LuDpWdYctrQlQ3ej1Ilgi7gknpsTRnPoLP8DpCHqHIJw==} engines: {node: '>=10'} hasBin: true sharp@0.35.5: resolution: {integrity: sha512-Ywn4OnzGukp7CDMrp08RQ50YKmuwG47brZgIVPTvBaaAfQlRlygrRqSrxdCiL9M+LlzLBiJ68IR1QqvzHyjC7g==} engines: {node: '>=20.9.0'} peerDependencies: '@types/node': '*' peerDependenciesMeta: '@types/node': optional: true supports-color@10.2.2: resolution: {integrity: sha512-SS+jx45GF1QjgEXQx4NJZV9ImqmO2NPz5FNsIHrsDjh2YsHnawpan7SNQ1o8NuhrbHZy9AZhIoCUiCeaW/C80g==} engines: {node: '>=18'} tslib@2.9.1: resolution: {integrity: sha512-a4Ux9VKuIMHsOS7ENbEq6hK2ZGYIT27Rtl0E4eD9KqwxhKiQeMZE/9xb3IdYwWaSOyIBQLExhQgXDTYoiCxnWA==} undici@7.29.1: resolution: {integrity: sha512-RYONW2MeafgYlkVOKYKkA/Ag7BmXqgIWCa8t1m0JcxrQg9pI9lEqRhAOruOBCbAohOa/gkCF+iPi9hrgvTzu6Q==} engines: {node: '>=20.18.1'} workerd@1.20261006.1: resolution: {integrity: sha512-8MadBuffZ5NdpLwZjUmsqT5QlaKXq4gjgT6wzcKeynZTICNXyePhc+5QVoKiK7+MMhFTLNrRO2KXLlpk8Q6BkA==} engines: {node: '>=16'} hasBin: true ws@8.21.0: resolution: {integrity: sha512-Vsp28b7DRcimFQvrqu2Wek3z1iYxDCWqHYB8Qsnk/S4RfaCQzPGPyBNuVjJV3cd6UiKtUtp6sNM77gWvzcCH+g==} engines: {node: '>=10.0.0'} peerDependencies: bufferutil: ^4.0.1 utf-8-validate: '>=5.0.2' peerDependenciesMeta: bufferutil: optional: true utf-8-validate: optional: true youch-core@0.3.3: resolution: {integrity: sha512-ho7XuGjLaJ2hWHoK8yFnsUGy2Y5uDpqSTq1FkHLK4/oqKtyUU1AFbOOxY4IpC9f0fTLjwYbslUz0Po5BpD1wrA==} youch@4.1.0-beta.10: resolution: {integrity: sha512-rLfVLB4FgQneDr0dv1oddCVZmKjcJ6yX6mS4pU82Mq/Dt9a3cLZQ62pDBL4AUO+uVrCvtWz3ZFUL2HFAFJ/BXQ==} zod@4.6.5: resolution: {integrity: sha512-v5l/aFXZQeai4awLbOpSoHecE9UiMrnfx75tEXLjNonXVARxQ5mOeipTjROUchszUNCqnE+hqAMujRsRHsut2Q==}snapshots: '@cloudflare/build-output-utils@0.9.1': dependencies: '@cloudflare/config': 0.25.0 '@cloudflare/codemods@0.4.2': {} '@cloudflare/config@0.25.0': dependencies: zod: 4.6.5 '@cloudflare/runtime-types@0.1.10': dependencies: miniflare: 5.20261006.2-beta workerd: 1.20261006.1 transitivePeerDependencies: - '@types/node' - bufferutil - utf-8-validate '@cloudflare/workerd-darwin-64@1.20261006.1': optional: true '@cloudflare/workerd-darwin-arm64@1.20261006.1': optional: true '@cloudflare/workerd-linux-64@1.20261006.1': optional: true '@cloudflare/workerd-linux-arm64@1.20261006.1': optional: true '@cloudflare/workerd-windows-64@1.20261006.1': optional: true '@cspotcode/source-map-support@0.8.1': dependencies: '@jridgewell/trace-mapping': 0.3.9 '@emnapi/runtime@1.11.3': dependencies: tslib: 2.9.1 optional: true '@img/colour@1.1.0': {} '@img/sharp-darwin-arm64@0.35.5': optionalDependencies: '@img/sharp-libvips-darwin-arm64': 1.3.4 optional: true '@img/sharp-darwin-x64@0.35.5': optionalDependencies: '@img/sharp-libvips-darwin-x64': 1.3.4 optional: true '@img/sharp-freebsd-wasm32@0.35.5': dependencies: '@img/sharp-wasm32': 0.35.5 optional: true '@img/sharp-libvips-darwin-arm64@1.3.4': optional: true '@img/sharp-libvips-darwin-x64@1.3.4': optional: true '@img/sharp-libvips-linux-arm64@1.3.4': optional: true '@img/sharp-libvips-linux-arm@1.3.4': optional: true '@img/sharp-libvips-linux-ppc64@1.3.4': optional: true '@img/sharp-libvips-linux-riscv64@1.3.4': optional: true '@img/sharp-libvips-linux-s390x@1.3.4': optional: true '@img/sharp-libvips-linux-x64@1.3.4': optional: true '@img/sharp-libvips-linuxmusl-arm64@1.3.4': optional: true '@img/sharp-libvips-linuxmusl-x64@1.3.4': optional: true '@img/sharp-linux-arm64@0.35.5': optionalDependencies: '@img/sharp-libvips-linux-arm64': 1.3.4 optional: true '@img/sharp-linux-arm@0.35.5': optionalDependencies: '@img/sharp-libvips-linux-arm': 1.3.4 optional: true '@img/sharp-linux-ppc64@0.35.5': optionalDependencies: '@img/sharp-libvips-linux-ppc64': 1.3.4 optional: true '@img/sharp-linux-riscv64@0.35.5': optionalDependencies: '@img/sharp-libvips-linux-riscv64': 1.3.4 optional: true '@img/sharp-linux-s390x@0.35.5': optionalDependencies: '@img/sharp-libvips-linux-s390x': 1.3.4 optional: true '@img/sharp-linux-x64@0.35.5': optionalDependencies: '@img/sharp-libvips-linux-x64': 1.3.4 optional: true '@img/sharp-linuxmusl-arm64@0.35.5': optionalDependencies: '@img/sharp-libvips-linuxmusl-arm64': 1.3.4 optional: true '@img/sharp-linuxmusl-x64@0.35.5': optionalDependencies: '@img/sharp-libvips-linuxmusl-x64': 1.3.4 optional: true '@img/sharp-wasm32@0.35.5': dependencies: '@emnapi/runtime': 1.11.3 optional: true '@img/sharp-webcontainers-wasm32@0.35.5': dependencies: '@img/sharp-wasm32': 0.35.5 optional: true '@img/sharp-win32-arm64@0.35.5': optional: true '@img/sharp-win32-ia32@0.35.5': optional: true '@img/sharp-win32-x64@0.35.5': optional: true '@jridgewell/resolve-uri@3.1.2': {} '@jridgewell/sourcemap-codec@1.6.0': {} '@jridgewell/trace-mapping@0.3.9': dependencies: '@jridgewell/resolve-uri': 3.1.2 '@jridgewell/sourcemap-codec': 1.6.0 '@poppinss/colors@4.1.6': dependencies: kleur: 4.1.5 '@poppinss/dumper@0.6.5': dependencies: '@poppinss/colors': 4.1.6 '@sindresorhus/is': 7.2.0 supports-color: 10.2.2 '@poppinss/exception@1.2.3': {} '@sindresorhus/is@7.2.0': {} '@speed-highlight/core@1.2.24': {} blake3-wasm@2.1.5: {} cf@1.0.0-beta.16: dependencies: '@cloudflare/build-output-utils': 0.9.1 '@cloudflare/codemods': 0.4.2 '@cloudflare/config': 0.25.0 '@cloudflare/runtime-types': 0.1.10 blake3-wasm: 2.1.5 miniflare: 5.20261006.2-beta minisearch: 7.2.0 transitivePeerDependencies: - '@types/node' - bufferutil - utf-8-validate cookie@1.1.1: {} detect-libc@2.1.2: {} error-stack-parser-es@1.0.5: {} kleur@4.1.5: {} miniflare@5.20261006.2-beta: dependencies: '@cspotcode/source-map-support': 0.8.1 sharp: 0.35.5 undici: 7.29.1 workerd: 1.20261006.1 ws: 8.21.0 youch: 4.1.0-beta.10 transitivePeerDependencies: - '@types/node' - bufferutil - utf-8-validate minisearch@7.2.0: {} semver@7.8.6: {} sharp@0.35.5: dependencies: '@img/colour': 1.1.0 detect-libc: 2.1.2 semver: 7.8.6 optionalDependencies: '@img/sharp-darwin-arm64': 0.35.5 '@img/sharp-darwin-x64': 0.35.5 '@img/sharp-freebsd-wasm32': 0.35.5 '@img/sharp-libvips-darwin-arm64': 1.3.4 '@img/sharp-libvips-darwin-x64': 1.3.4 '@img/sharp-libvips-linux-arm': 1.3.4 '@img/sharp-libvips-linux-arm64': 1.3.4 '@img/sharp-libvips-linux-ppc64': 1.3.4 '@img/sharp-libvips-linux-riscv64': 1.3.4 '@img/sharp-libvips-linux-s390x': 1.3.4 '@img/sharp-libvips-linux-x64': 1.3.4 '@img/sharp-libvips-linuxmusl-arm64': 1.3.4 '@img/sharp-libvips-linuxmusl-x64': 1.3.4 '@img/sharp-linux-arm': 0.35.5 '@img/sharp-linux-arm64': 0.35.5 '@img/sharp-linux-ppc64': 0.35.5 '@img/sharp-linux-riscv64': 0.35.5 '@img/sharp-linux-s390x': 0.35.5 '@img/sharp-linux-x64': 0.35.5 '@img/sharp-linuxmusl-arm64': 0.35.5 '@img/sharp-linuxmusl-x64': 0.35.5 '@img/sharp-webcontainers-wasm32': 0.35.5 '@img/sharp-win32-arm64': 0.35.5 '@img/sharp-win32-ia32': 0.35.5 '@img/sharp-win32-x64': 0.35.5 supports-color@10.2.2: {} tslib@2.9.1: optional: true undici@7.29.1: {} workerd@1.20261006.1: optionalDependencies: '@cloudflare/workerd-darwin-64': 1.20261006.1 '@cloudflare/workerd-darwin-arm64': 1.20261006.1 '@cloudflare/workerd-linux-64': 1.20261006.1 '@cloudflare/workerd-linux-arm64': 1.20261006.1 '@cloudflare/workerd-windows-64': 1.20261006.1 ws@8.21.0: {} youch-core@0.3.3: dependencies: '@poppinss/exception': 1.2.3 error-stack-parser-es: 1.0.5 youch@4.1.0-beta.10: dependencies: '@poppinss/colors': 4.1.6 '@poppinss/dumper': 0.6.5 '@speed-highlight/core': 1.2.24 cookie: 1.1.1 youch-core: 0.3.3 zod@4.6.5: {}mise/.mise/locks/npm-cf/1.0.0-beta.16/package.json
Addednew file mode 100644+7 / −0 text lines
mise/config.linux-x64.toml
Addednew file mode 100644+7 / −0 text lines
# Private Godot client: Forward+ builds only.[tools."github:Bios-Marcel/call_of_slop_modern_warefare_2"]version = "latest"os = ["linux/x64"]lazy = truelazy_bins = ["rust-intervention"]platforms.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
Addednew file mode 100644+3 / −0 text lines
mise/config.local.toml
Addednew file mode 100644+3 / −0 text lines
mise/config.macos.toml
Addednew file mode 100644+3 / −0 text lines
mise/config.toml
Modified+28 / −3 text lines
"cargo:kdl-lsp" = "latest""github:dev-cycles/contextive" = "latest""npm:gh-actions-language-server" = "latest"# Android builds ast-grep via Cargo; aqua has no matching Android asset.ast-grep = { version = "latest", os = ["linux", "macos", "windows"] }"cargo:ast-grep" = { version = "latest", os = ["android"] }# Android/Termux uses the system carapace package.carapace = { version = "latest", os = ["linux", "macos", "windows"] }# Android/Termux has no aqua asset (cargo-binstall-aarch64-android.*); there the# binary comes from `pkg install cargo-binstall`, so skip the tool on that OS.cargo-binstall = { version = "latest", os = ["linux", "macos", "windows"] }"cargo:kdl-lsp" = { version = "latest", depends = "cargo-binstall" }"cargo:resvg" = { version = "latest", os = ["windows"], depends = "cargo-binstall" }# Syntax-aware git merge driver (see git/gitconfig). Not in pkg or the mise# registry; Codeberg publishes static musl builds that also run on Termux."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" } } }"npm:cf" = { version = "1.0.0-beta.16", os = ["linux", "macos", "windows"] }[tools."http:git-revue"]version = "0.1.0"os = ["linux/x64", "android/arm64"]platforms.linux-x64 = { url = "https://pkg.bugabinga.net/releases/revue/git-revue-0.1.0-x86_64-unknown-linux-gnu.tar.gz" }platforms.android-arm64 = { url = "https://pkg.bugabinga.net/releases/revue/cross/git-revue-0.1.0-aarch64-linux-android.tar.gz" }mise/config.windows-x64.toml
Addednew file mode 100644+7 / −0 text lines
# Private Godot client: Forward+ builds only.[tools."github:Bios-Marcel/call_of_slop_modern_warefare_2"]version = "latest"os = ["windows/x64"]lazy = truelazy_bins = ["rust-intervention"]platforms.windows-x64 = { asset_pattern = "rust-intervention-{{ version }}-windows-x86_64-forward-plus.zip" }mise/config.windows.toml
Addednew file mode 100644+3 / −0 text lines
mise/locks/npm-cf/1.0.0-beta.16/aube-lock.yaml
Addednew file mode 100644+615 / −0 text lines
lockfileVersion: '9.0'settings: autoInstallPeers: true excludeLinksFromLockfile: falseimporters: .: dependencies: cf: specifier: 1.0.0-beta.16 version: 1.0.0-beta.16packages: '@cloudflare/build-output-utils@0.9.1': resolution: {integrity: sha512-zTzHGwXD7dJ1+vWlVgvTWbg1k0x53+Wu1aR6MDWAflOwJD9KtHjz7Qqq6pnTbVxlR0m5GLlD6sshEuiKnB1KQA==} '@cloudflare/codemods@0.4.2': resolution: {integrity: sha512-oHvDlfhQEIkdf8Mvz4SMgk+6evVlu9rrntRv5KQfRK3H4RkXUmawzYQ7+zdBG0wiWdp/Ku/PqNMWVYAs8T4jrQ==} hasBin: true '@cloudflare/config@0.25.0': resolution: {integrity: sha512-h4tgL9/pmeoIdKfs/irfV/eCotbEpbadO2RGPbHwRij6Ek7q8Gqx4juSoDSb/fk9IclansgAHXF9b8rb3Kw4jg==} '@cloudflare/runtime-types@0.1.10': resolution: {integrity: sha512-OXEpo7VZ/ALsLGzKCX4n0Dknnf1w3W6wCWELiKyW6MUd7JRvd23KSTrUKIHLJaBpXR1hTKCqWBUWUHBn2wZbnQ==} '@cloudflare/workerd-darwin-64@1.20261006.1': resolution: {integrity: sha512-lCX6avJO2It9AyDEYitjmOtJRVp/xmaW0TziyoLAnfxlzozyyRbSFfIIMMCiDx/sTP1++E4VLbV+7BHSD33f0Q==} engines: {node: '>=16'} cpu: [x64] os: [darwin] '@cloudflare/workerd-darwin-arm64@1.20261006.1': resolution: {integrity: sha512-PyFGjOaldtppnLuKsdkoYWXfLVpDjuf8u+uoykX+1Xvxo2EPmCVViq0iDKm+U7c7PRno85ehS3/MPVXyk2HwHw==} engines: {node: '>=16'} cpu: [arm64] os: [darwin] '@cloudflare/workerd-linux-64@1.20261006.1': resolution: {integrity: sha512-Ntf9S8eesmVufdjaT2kzWlz6Ng9XGYTc6cHQVRKAg59lFufwsIabGeMT6U4KkrpEeSIxgHq8aPtuLbZXE19tCA==} engines: {node: '>=16'} cpu: [x64] os: [linux] '@cloudflare/workerd-linux-arm64@1.20261006.1': resolution: {integrity: sha512-JyeDBymVWw5tVRebSsVE8ojDYxd6UlZrAseHU8G+NpIyd5wF61tXlF/axLeCUqu0pOhBFHb8I5QKi0jwrCK41Q==} engines: {node: '>=16'} cpu: [arm64] os: [linux] '@cloudflare/workerd-windows-64@1.20261006.1': resolution: {integrity: sha512-nWP0URNqOBN9fa/gZ7eh/w051DwjOXN8j4lDZDYVXyQPsux6sV3DfyYZT+CjR/rt9nKBSmJT9QE9/bWT18+84w==} engines: {node: '>=16'} cpu: [x64] os: [win32] '@cspotcode/source-map-support@0.8.1': resolution: {integrity: sha512-IchNf6dN4tHoMFIn/7OE8LWZ19Y6q/67Bmf6vnGREv8RSbBVb9LPJxEcnwrcwX6ixSvaiGoomAUvu4YSxXrVgw==} engines: {node: '>=12'} '@emnapi/runtime@1.11.3': resolution: {integrity: sha512-Xz4Tpyki7XyrpbUK1jR1AhdAdaXyhhY4lZ3neLodmhpuWfy2PAQN5B46sAiU4liOXGLkHypn/qU+jvfWSCYYLA==} '@img/colour@1.1.0': resolution: {integrity: sha512-Td76q7j57o/tLVdgS746cYARfSyxk8iEfRxewL9h4OMzYhbW4TAcppl0mT4eyqXddh6L/jwoM75mo7ixa/pCeQ==} engines: {node: '>=18'} '@img/sharp-darwin-arm64@0.35.5': resolution: {integrity: sha512-QRUlFQ0WxvdWyqqG/WtI3iupfD5rBzmCHXSdPsY91sAtVtTo7Q4cb6zOccZ3gqEqkr0f1As1ehLqmEpDsRf+lg==} engines: {node: '>=20.9.0'} cpu: [arm64] os: [darwin] '@img/sharp-darwin-x64@0.35.5': resolution: {integrity: sha512-+BR255RhDlpygUpOc/Jdt1nT6DQ3XG/ERo5wbcdOf5Q320dKtPCKPLR1LJs9VGXRaMa8l1uUa0tkCNOXiAxZUw==} engines: {node: '>=20.9.0'} cpu: [x64] os: [darwin] '@img/sharp-freebsd-wasm32@0.35.5': resolution: {integrity: sha512-Y/z91nEZ4uIBX5X3nfTovjU9lHNKFYbL2lpHCLVNmXQK03VIZvXBBt0KxbPGp2SdGSF+2mQU4e+hQaWOt86iAw==} engines: {node: '>=20.9.0'} os: [freebsd] '@img/sharp-libvips-darwin-arm64@1.3.4': resolution: {integrity: sha512-5R89nBYiRdUlSWJxPhO+GVtaXzXSxKnRu/xqMn3KTA3L9EB9Oy/P+Nn2f2vlhPuUdy/Zusb2DarbyTpGCfEDuw==} cpu: [arm64] os: [darwin] '@img/sharp-libvips-darwin-x64@1.3.4': resolution: {integrity: sha512-iR2OKH80yi0U+dUplyh3/xdpFvps6YkCwsXenIJxqxR1v9o+xtKTGbS9H7cps+2Vxjc8B1j96p75NmTGjIhtpQ==} cpu: [x64] os: [darwin] '@img/sharp-libvips-linux-arm64@1.3.4': resolution: {integrity: sha512-Y3dgX/6lE2QhQb+Gxy0WZxfg9MEm/JBjamZpS2IklP7xIQoKN4hzAm7KcMVGtaVDt3neE9OKBC7vAfonA/Lr1A==} cpu: [arm64] os: [linux] libc: [glibc] '@img/sharp-libvips-linux-arm@1.3.4': resolution: {integrity: sha512-LmRtTsOHuvM2+wlO2Db37dx5MiZhB0FvSunciw48YjdOkZz9KAiRbm8ujeMOA1INqmei5NapFxYEK1D1ZSidmw==} cpu: [arm] os: [linux] libc: [glibc] '@img/sharp-libvips-linux-ppc64@1.3.4': resolution: {integrity: sha512-Le6boB8Tai0Nis+gIxIpKx68UDVVIqdR8Tin5Yf1z2LJJQLDJvCDRqRu+jC2qCoD+eIomonmOwB4smBRxfVpYQ==} cpu: [ppc64] os: [linux] libc: [glibc] '@img/sharp-libvips-linux-riscv64@1.3.4': resolution: {integrity: sha512-aHkkIEHPRdQEegJN20MLmGtxYD9R2wQr3Cwpddnu5+YKMt6Uzax7S9h5gpZTo8wyrGuZSlfQ63OevL5mTyOC7Q==} cpu: [riscv64] os: [linux] libc: [glibc] '@img/sharp-libvips-linux-s390x@1.3.4': resolution: {integrity: sha512-ra/mB6MikESDUO7Yg+Mi95bFBb9GsObURuhnOv3OqknjGe9sZrG8tCe9q0xSIGrtLgvgw0gKnFWcK4blSgQOuQ==} cpu: [s390x] os: [linux] libc: [glibc] '@img/sharp-libvips-linux-x64@1.3.4': resolution: {integrity: sha512-GJ//SSXbnwSDes02umB3nDJLFcQzw8a18V8fyhqr6tV515tOEMdImjjxj1AoafMRz56F3PHgftnj1QEKSU1zkw==} cpu: [x64] os: [linux] libc: [glibc] '@img/sharp-libvips-linuxmusl-arm64@1.3.4': resolution: {integrity: sha512-hvulFwtjUcagsis6BBxHwGFwWoNZjgYmULGVrZcyfNbjA8hKILbRxGg15/7w5HDyXHXUos/j6baAWqnCyQ2DWA==} cpu: [arm64] os: [linux] libc: [musl] '@img/sharp-libvips-linuxmusl-x64@1.3.4': resolution: {integrity: sha512-6zXKeE/p39I1AmA3cJG35eyBGNqNddLnUXjhwBnsGjFPWqf5VKkDBEqaEkPDoTEtkxwi2vv8Tcr2mDyP4So7Fg==} cpu: [x64] os: [linux] libc: [musl] '@img/sharp-linux-arm64@0.35.5': resolution: {integrity: sha512-LYVx5JTsOM2CBzmxreh+nl64/3H6Xb09iSLknqH47z2T2DFFxDeFLP5y4dJwe6H7uGQlHPyEEtIqyo3DYsRwdQ==} engines: {node: '>=20.9.0'} cpu: [arm64] os: [linux] libc: [glibc] '@img/sharp-linux-arm@0.35.5': resolution: {integrity: sha512-LEaXK2WdXVK5ykcw0buWyPMsmLLL2vpHLD6yrNSW+JGEL3BZPA4tpKN6iaMc4AxTTAoaX/sU1rOL51lcIz48ZQ==} engines: {node: '>=20.9.0'} cpu: [arm] os: [linux] libc: [glibc] '@img/sharp-linux-ppc64@0.35.5': resolution: {integrity: sha512-QVxAAq8evVRI9ia2vqgwrmWucn5Dfv+JdWzj75pD8omHLPSP7f8p20O8jxzjCcuCEQEOtYOZUmX1hkiZ0kdevA==} engines: {node: '>=20.9.0'} cpu: [ppc64] os: [linux] libc: [glibc] '@img/sharp-linux-riscv64@0.35.5': resolution: {integrity: sha512-LtdreXguaavKODPIfzJ4kffx7UNt1omwtK0rch4EBbbSTXPnxWmYSayXdLJw0fJzQ97kHt1gL/yh4tvU+nCyRQ==} engines: {node: '>=20.9.0'} cpu: [riscv64] os: [linux] libc: [glibc] '@img/sharp-linux-s390x@0.35.5': resolution: {integrity: sha512-UZasTOFiYzotTsGOCu42BfUzP6Tu6Do/947iRm1RsLKvlllxwGcn4RN27LibGWceix4Y+Pmw3jsnTcCQIgWjqA==} engines: {node: '>=20.9.0'} cpu: [s390x] os: [linux] libc: [glibc] '@img/sharp-linux-x64@0.35.5': resolution: {integrity: sha512-SxFtLTeJInhAA9Q836kux2vZNeOBQEx658qvbboZScr0wIARym3IcGmW7KpVD5sbVg0Ojy+udFQdayYIZyoNog==} engines: {node: '>=20.9.0'} cpu: [x64] os: [linux] libc: [glibc] '@img/sharp-linuxmusl-arm64@0.35.5': resolution: {integrity: sha512-9HbMclmI1zlNkFRs3z9/eBtDjfD0sGlrX1z6b1qwmiFY5ElDLh4BC0LPBdVp7z1DXFiKlIcznf+ZlsuZzLxQqg==} engines: {node: '>=20.9.0'} cpu: [arm64] os: [linux] libc: [musl] '@img/sharp-linuxmusl-x64@0.35.5': resolution: {integrity: sha512-4KOphqB035HrVdqLZfCgMzzERrQkkzOwRhl4OAkRO1YCldbaFjySXMaK534Mo0V+LndnlJk+sbUyLeU0ULyD1A==} engines: {node: '>=20.9.0'} cpu: [x64] os: [linux] libc: [musl] '@img/sharp-wasm32@0.35.5': resolution: {integrity: sha512-Ptsga1su4tQx+LLF1ECS9U6nz5kmrXKo6XVbtR48Ke3ZRxxgaWBu7IDtEe1quo8hiupwm6WFqxVlXaSf7IINGQ==} engines: {node: '>=20.9.0'} '@img/sharp-webcontainers-wasm32@0.35.5': resolution: {integrity: sha512-hfhF/FmoQyTUkA0bIKFOtw536BQSeBMe6BF6QyWlrPxT754+TFLaZ7sKKTfvvM0yJgKgaYTwnFCIZ/GuDw5SUA==} engines: {node: '>=20.9.0'} cpu: [wasm32] '@img/sharp-win32-arm64@0.35.5': resolution: {integrity: sha512-X4t7g+7ZA5DKblCBEXGjUqqemj4vczING/5viFwAL8h4N3qYeyjwdCvRLHi4EdOUI+2Z7UFlp1VM+p/AuEtm6Q==} engines: {node: '>=20.9.0'} cpu: [arm64] os: [win32] '@img/sharp-win32-ia32@0.35.5': resolution: {integrity: sha512-5Zm82LoBc43nhwNybZlG7Y1KO//Zhsn306fQl29ZOuStHLGTo3BWL83q3cznX0poxSAMuYL1On/BHBxkBeKr6A==} engines: {node: ^20.9.0} cpu: [ia32] os: [win32] '@img/sharp-win32-x64@0.35.5': resolution: {integrity: sha512-x76eH0vEiHlcMQu8Y8IenntaACtddpT6W0wmXtWrnKcnKI7ME5DdgqhAD6SEWOEl1v2zDvkZDhFA9KnURwpfqg==} engines: {node: '>=20.9.0'} cpu: [x64] os: [win32] '@jridgewell/resolve-uri@3.1.2': resolution: {integrity: sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==} engines: {node: '>=6.0.0'} '@jridgewell/sourcemap-codec@1.6.0': resolution: {integrity: sha512-T7jf+5zgsZHwNJ4lvQ7/aezbyk0nNX+zJVWpmHA7VYsEx7a7qr5Rg5IbtJFqkgze5Y2sruq1RUY8Q837Od7iFw==} '@jridgewell/trace-mapping@0.3.9': resolution: {integrity: sha512-3Belt6tdc8bPgAtbcmdtNJlirVoTmEb5e2gC94PnkwEW9jI6CAHUeoG85tjWP5WquqfavoMtMwiG4P926ZKKuQ==} '@poppinss/colors@4.1.6': resolution: {integrity: sha512-H9xkIdFswbS8n1d6vmRd8+c10t2Qe+rZITbbDHHkQixH5+2x1FDGmi/0K+WgWiqQFKPSlIYB7jlH6Kpfn6Fleg==} '@poppinss/dumper@0.6.5': resolution: {integrity: sha512-NBdYIb90J7LfOI32dOewKI1r7wnkiH6m920puQ3qHUeZkxNkQiFnXVWoE6YtFSv6QOiPPf7ys6i+HWWecDz7sw==} '@poppinss/exception@1.2.3': resolution: {integrity: sha512-dCED+QRChTVatE9ibtoaxc+WkdzOSjYTKi/+uacHWIsfodVfpsueo3+DKpgU5Px8qXjgmXkSvhXvSCz3fnP9lw==} '@sindresorhus/is@7.2.0': resolution: {integrity: sha512-P1Cz1dWaFfR4IR+U13mqqiGsLFf1KbayybWwdd2vfctdV6hDpUkgCY0nKOLLTMSoRd/jJNjtbqzf13K8DCCXQw==} engines: {node: '>=18'} '@speed-highlight/core@1.2.24': resolution: {integrity: sha512-qeW2e1l78afw8VhRPfPQ1Gjj+KU5XFQ/OFV5ti6eTa9bruO7mJyZtA4vw0ofqmA3tKCkROE9xLk3VZoeRc98nw==} blake3-wasm@2.1.5: resolution: {integrity: sha512-F1+K8EbfOZE49dtoPtmxUQrpXaBIl3ICvasLh+nJta0xkz+9kF/7uet9fLnwKqhDrmj6g+6K3Tw9yQPUg2ka5g==} cf@1.0.0-beta.16: resolution: {integrity: sha512-buY0XUHp+wAA0paOKxdUr5UgLKhO8xkeJL5Pn2Xt1UQLfqPFKrqTC3mKrGsrmOhf8Qyn4Omxc4F/8x37fa9kVA==} engines: {node: '>=22'} hasBin: true cookie@1.1.1: resolution: {integrity: sha512-ei8Aos7ja0weRpFzJnEA9UHJ/7XQmqglbRwnf2ATjcB9Wq874VKH9kfjjirM6UhU2/E5fFYadylyhFldcqSidQ==} engines: {node: '>=18'} detect-libc@2.1.2: resolution: {integrity: sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==} engines: {node: '>=8'} error-stack-parser-es@1.0.5: resolution: {integrity: sha512-5qucVt2XcuGMcEGgWI7i+yZpmpByQ8J1lHhcL7PwqCwu9FPP3VUXzT4ltHe5i2z9dePwEHcDVOAfSnHsOlCXRA==} kleur@4.1.5: resolution: {integrity: sha512-o+NO+8WrRiQEE4/7nwRJhN1HWpVmJm511pBHUxPLtp0BUISzlBplORYSmTclCnJvQq2tKu/sgl3xVpkc7ZWuQQ==} engines: {node: '>=6'} miniflare@5.20261006.2-beta: resolution: {integrity: sha512-agufWI3mXF8xGzry2/sOF8Im8AoYs04DWBCLDWDmd4QtMSGEo9IgrPmYOwsCmQA3K3MbLzsvr01GpWc8x3Duqw==} engines: {node: '>=22.0.0'} minisearch@7.2.0: resolution: {integrity: sha512-dqT2XBYUOZOiC5t2HRnwADjhNS2cecp9u+TJRiJ1Qp/f5qjkeT5APcGPjHw+bz89Ms8Jp+cG4AlE+QZ/QnDglg==} semver@7.8.6: resolution: {integrity: sha512-9lpSSU4Mly3mrtruwLs1eLK6+gzbzqeBFwRNjIjE+9LuDpWdYctrQlQ3ej1Ilgi7gknpsTRnPoLP8DpCHqHIJw==} engines: {node: '>=10'} hasBin: true sharp@0.35.5: resolution: {integrity: sha512-Ywn4OnzGukp7CDMrp08RQ50YKmuwG47brZgIVPTvBaaAfQlRlygrRqSrxdCiL9M+LlzLBiJ68IR1QqvzHyjC7g==} engines: {node: '>=20.9.0'} peerDependencies: '@types/node': '*' peerDependenciesMeta: '@types/node': optional: true supports-color@10.2.2: resolution: {integrity: sha512-SS+jx45GF1QjgEXQx4NJZV9ImqmO2NPz5FNsIHrsDjh2YsHnawpan7SNQ1o8NuhrbHZy9AZhIoCUiCeaW/C80g==} engines: {node: '>=18'} tslib@2.9.1: resolution: {integrity: sha512-a4Ux9VKuIMHsOS7ENbEq6hK2ZGYIT27Rtl0E4eD9KqwxhKiQeMZE/9xb3IdYwWaSOyIBQLExhQgXDTYoiCxnWA==} undici@7.29.1: resolution: {integrity: sha512-RYONW2MeafgYlkVOKYKkA/Ag7BmXqgIWCa8t1m0JcxrQg9pI9lEqRhAOruOBCbAohOa/gkCF+iPi9hrgvTzu6Q==} engines: {node: '>=20.18.1'} workerd@1.20261006.1: resolution: {integrity: sha512-8MadBuffZ5NdpLwZjUmsqT5QlaKXq4gjgT6wzcKeynZTICNXyePhc+5QVoKiK7+MMhFTLNrRO2KXLlpk8Q6BkA==} engines: {node: '>=16'} hasBin: true ws@8.21.0: resolution: {integrity: sha512-Vsp28b7DRcimFQvrqu2Wek3z1iYxDCWqHYB8Qsnk/S4RfaCQzPGPyBNuVjJV3cd6UiKtUtp6sNM77gWvzcCH+g==} engines: {node: '>=10.0.0'} peerDependencies: bufferutil: ^4.0.1 utf-8-validate: '>=5.0.2' peerDependenciesMeta: bufferutil: optional: true utf-8-validate: optional: true youch-core@0.3.3: resolution: {integrity: sha512-ho7XuGjLaJ2hWHoK8yFnsUGy2Y5uDpqSTq1FkHLK4/oqKtyUU1AFbOOxY4IpC9f0fTLjwYbslUz0Po5BpD1wrA==} youch@4.1.0-beta.10: resolution: {integrity: sha512-rLfVLB4FgQneDr0dv1oddCVZmKjcJ6yX6mS4pU82Mq/Dt9a3cLZQ62pDBL4AUO+uVrCvtWz3ZFUL2HFAFJ/BXQ==} zod@4.6.5: resolution: {integrity: sha512-v5l/aFXZQeai4awLbOpSoHecE9UiMrnfx75tEXLjNonXVARxQ5mOeipTjROUchszUNCqnE+hqAMujRsRHsut2Q==}snapshots: '@cloudflare/build-output-utils@0.9.1': dependencies: '@cloudflare/config': 0.25.0 '@cloudflare/codemods@0.4.2': {} '@cloudflare/config@0.25.0': dependencies: zod: 4.6.5 '@cloudflare/runtime-types@0.1.10': dependencies: miniflare: 5.20261006.2-beta workerd: 1.20261006.1 transitivePeerDependencies: - '@types/node' - bufferutil - utf-8-validate '@cloudflare/workerd-darwin-64@1.20261006.1': optional: true '@cloudflare/workerd-darwin-arm64@1.20261006.1': optional: true '@cloudflare/workerd-linux-64@1.20261006.1': optional: true '@cloudflare/workerd-linux-arm64@1.20261006.1': optional: true '@cloudflare/workerd-windows-64@1.20261006.1': optional: true '@cspotcode/source-map-support@0.8.1': dependencies: '@jridgewell/trace-mapping': 0.3.9 '@emnapi/runtime@1.11.3': dependencies: tslib: 2.9.1 optional: true '@img/colour@1.1.0': {} '@img/sharp-darwin-arm64@0.35.5': optionalDependencies: '@img/sharp-libvips-darwin-arm64': 1.3.4 optional: true '@img/sharp-darwin-x64@0.35.5': optionalDependencies: '@img/sharp-libvips-darwin-x64': 1.3.4 optional: true '@img/sharp-freebsd-wasm32@0.35.5': dependencies: '@img/sharp-wasm32': 0.35.5 optional: true '@img/sharp-libvips-darwin-arm64@1.3.4': optional: true '@img/sharp-libvips-darwin-x64@1.3.4': optional: true '@img/sharp-libvips-linux-arm64@1.3.4': optional: true '@img/sharp-libvips-linux-arm@1.3.4': optional: true '@img/sharp-libvips-linux-ppc64@1.3.4': optional: true '@img/sharp-libvips-linux-riscv64@1.3.4': optional: true '@img/sharp-libvips-linux-s390x@1.3.4': optional: true '@img/sharp-libvips-linux-x64@1.3.4': optional: true '@img/sharp-libvips-linuxmusl-arm64@1.3.4': optional: true '@img/sharp-libvips-linuxmusl-x64@1.3.4': optional: true '@img/sharp-linux-arm64@0.35.5': optionalDependencies: '@img/sharp-libvips-linux-arm64': 1.3.4 optional: true '@img/sharp-linux-arm@0.35.5': optionalDependencies: '@img/sharp-libvips-linux-arm': 1.3.4 optional: true '@img/sharp-linux-ppc64@0.35.5': optionalDependencies: '@img/sharp-libvips-linux-ppc64': 1.3.4 optional: true '@img/sharp-linux-riscv64@0.35.5': optionalDependencies: '@img/sharp-libvips-linux-riscv64': 1.3.4 optional: true '@img/sharp-linux-s390x@0.35.5': optionalDependencies: '@img/sharp-libvips-linux-s390x': 1.3.4 optional: true '@img/sharp-linux-x64@0.35.5': optionalDependencies: '@img/sharp-libvips-linux-x64': 1.3.4 optional: true '@img/sharp-linuxmusl-arm64@0.35.5': optionalDependencies: '@img/sharp-libvips-linuxmusl-arm64': 1.3.4 optional: true '@img/sharp-linuxmusl-x64@0.35.5': optionalDependencies: '@img/sharp-libvips-linuxmusl-x64': 1.3.4 optional: true '@img/sharp-wasm32@0.35.5': dependencies: '@emnapi/runtime': 1.11.3 optional: true '@img/sharp-webcontainers-wasm32@0.35.5': dependencies: '@img/sharp-wasm32': 0.35.5 optional: true '@img/sharp-win32-arm64@0.35.5': optional: true '@img/sharp-win32-ia32@0.35.5': optional: true '@img/sharp-win32-x64@0.35.5': optional: true '@jridgewell/resolve-uri@3.1.2': {} '@jridgewell/sourcemap-codec@1.6.0': {} '@jridgewell/trace-mapping@0.3.9': dependencies: '@jridgewell/resolve-uri': 3.1.2 '@jridgewell/sourcemap-codec': 1.6.0 '@poppinss/colors@4.1.6': dependencies: kleur: 4.1.5 '@poppinss/dumper@0.6.5': dependencies: '@poppinss/colors': 4.1.6 '@sindresorhus/is': 7.2.0 supports-color: 10.2.2 '@poppinss/exception@1.2.3': {} '@sindresorhus/is@7.2.0': {} '@speed-highlight/core@1.2.24': {} blake3-wasm@2.1.5: {} cf@1.0.0-beta.16: dependencies: '@cloudflare/build-output-utils': 0.9.1 '@cloudflare/codemods': 0.4.2 '@cloudflare/config': 0.25.0 '@cloudflare/runtime-types': 0.1.10 blake3-wasm: 2.1.5 miniflare: 5.20261006.2-beta minisearch: 7.2.0 transitivePeerDependencies: - '@types/node' - bufferutil - utf-8-validate cookie@1.1.1: {} detect-libc@2.1.2: {} error-stack-parser-es@1.0.5: {} kleur@4.1.5: {} miniflare@5.20261006.2-beta: dependencies: '@cspotcode/source-map-support': 0.8.1 sharp: 0.35.5 undici: 7.29.1 workerd: 1.20261006.1 ws: 8.21.0 youch: 4.1.0-beta.10 transitivePeerDependencies: - '@types/node' - bufferutil - utf-8-validate minisearch@7.2.0: {} semver@7.8.6: {} sharp@0.35.5: dependencies: '@img/colour': 1.1.0 detect-libc: 2.1.2 semver: 7.8.6 optionalDependencies: '@img/sharp-darwin-arm64': 0.35.5 '@img/sharp-darwin-x64': 0.35.5 '@img/sharp-freebsd-wasm32': 0.35.5 '@img/sharp-libvips-darwin-arm64': 1.3.4 '@img/sharp-libvips-darwin-x64': 1.3.4 '@img/sharp-libvips-linux-arm': 1.3.4 '@img/sharp-libvips-linux-arm64': 1.3.4 '@img/sharp-libvips-linux-ppc64': 1.3.4 '@img/sharp-libvips-linux-riscv64': 1.3.4 '@img/sharp-libvips-linux-s390x': 1.3.4 '@img/sharp-libvips-linux-x64': 1.3.4 '@img/sharp-libvips-linuxmusl-arm64': 1.3.4 '@img/sharp-libvips-linuxmusl-x64': 1.3.4 '@img/sharp-linux-arm': 0.35.5 '@img/sharp-linux-arm64': 0.35.5 '@img/sharp-linux-ppc64': 0.35.5 '@img/sharp-linux-riscv64': 0.35.5 '@img/sharp-linux-s390x': 0.35.5 '@img/sharp-linux-x64': 0.35.5 '@img/sharp-linuxmusl-arm64': 0.35.5 '@img/sharp-linuxmusl-x64': 0.35.5 '@img/sharp-webcontainers-wasm32': 0.35.5 '@img/sharp-win32-arm64': 0.35.5 '@img/sharp-win32-ia32': 0.35.5 '@img/sharp-win32-x64': 0.35.5 supports-color@10.2.2: {} tslib@2.9.1: optional: true undici@7.29.1: {} workerd@1.20261006.1: optionalDependencies: '@cloudflare/workerd-darwin-64': 1.20261006.1 '@cloudflare/workerd-darwin-arm64': 1.20261006.1 '@cloudflare/workerd-linux-64': 1.20261006.1 '@cloudflare/workerd-linux-arm64': 1.20261006.1 '@cloudflare/workerd-windows-64': 1.20261006.1 ws@8.21.0: {} youch-core@0.3.3: dependencies: '@poppinss/exception': 1.2.3 error-stack-parser-es: 1.0.5 youch@4.1.0-beta.10: dependencies: '@poppinss/colors': 4.1.6 '@poppinss/dumper': 0.6.5 '@speed-highlight/core': 1.2.24 cookie: 1.1.1 youch-core: 0.3.3 zod@4.6.5: {}mise/locks/npm-cf/1.0.0-beta.16/package.json
Addednew file mode 100644+7 / −0 text lines
mise/mise.lock
Addednew file mode 100644+170 / −0 text lines
# @generated - this file is auto-generated by `mise lock` https://mise.jdx.dev/dev-tools/mise-lock.htmllockfile_version = 3[[tools.ast-grep]]version = "0.51.1"backend = "aqua:ast-grep/ast-grep"specifiers = ["latest"][tools.ast-grep."platforms.linux-x64"]checksum = "sha256:42514f77ae0c8a25d7d32154d31d3e7e16f3ab894f8ce76ce417de234ee49157"checksum_source = "mise-versions"url = "https://github.com/ast-grep/ast-grep/releases/download/0.51.1/app-x86_64-unknown-linux-gnu.zip"url_api = "https://api.github.com/repos/ast-grep/ast-grep/releases/assets/701823082"[tools.ast-grep."platforms.macos-arm64"]checksum = "sha256:a95772097b4d02bd9d45ed63b300c37041ae3c36632b3bf19250cc7c10187dc4"checksum_source = "mise-versions"url = "https://github.com/ast-grep/ast-grep/releases/download/0.51.1/app-aarch64-apple-darwin.zip"url_api = "https://api.github.com/repos/ast-grep/ast-grep/releases/assets/701845634"[tools.ast-grep."platforms.windows-x64"]checksum = "sha256:12a0cefb77498820ef6fb302ed8758cbda39be87d4c15120dc74c1dea968a50d"url = "https://github.com/ast-grep/ast-grep/releases/download/0.51.1/app-x86_64-pc-windows-msvc.zip"url_api = "https://api.github.com/repos/ast-grep/ast-grep/releases/assets/701859070"[[tools.carapace]]version = "1.8.2"backend = "aqua:carapace-sh/carapace-bin"specifiers = ["latest"][tools.carapace."platforms.linux-x64"]checksum = "sha256:1b3dc4cab51361d3443400aefa4314ad8d44d8414bf4b1d18f41a6fe71b1b0e4"checksum_source = "mise-versions"url = "https://github.com/carapace-sh/carapace-bin/releases/download/v1.8.2/carapace-bin_1.8.2_linux_amd64.tar.gz"url_api = "https://api.github.com/repos/carapace-sh/carapace-bin/releases/assets/698585320"[tools.carapace."platforms.macos-arm64"]checksum = "sha256:d9c05be343f19005f4bd568f2cedd8307c358e82aff32ebfb2d42af0c52b28ea"checksum_source = "mise-versions"url = "https://github.com/carapace-sh/carapace-bin/releases/download/v1.8.2/carapace-bin_1.8.2_darwin_arm64.tar.gz"url_api = "https://api.github.com/repos/carapace-sh/carapace-bin/releases/assets/698585380"[tools.carapace."platforms.windows-x64"]checksum = "sha256:44ac5d1f16bf38df559259783680925fe9625e467e020b180ea1e8d7c721d4e5"url = "https://github.com/carapace-sh/carapace-bin/releases/download/v1.8.2/carapace-bin_1.8.2_windows_amd64.zip"url_api = "https://api.github.com/repos/carapace-sh/carapace-bin/releases/assets/698585413"[[tools.cargo-binstall]]version = "1.26.2"backend = "aqua:cargo-bins/cargo-binstall"specifiers = ["latest"][tools.cargo-binstall."platforms.linux-x64"]checksum = "sha256:4f28eba175325f67f7c4bb8ae8686914d2d88fead279c0b8c4d3125264d7a512"url = "https://github.com/cargo-bins/cargo-binstall/releases/download/v1.26.2/cargo-binstall-x86_64-unknown-linux-gnu.tgz"url_api = "https://api.github.com/repos/cargo-bins/cargo-binstall/releases/assets/695464312"provenance = "github-attestations"[tools.cargo-binstall."platforms.macos-arm64"]checksum = "sha256:0f9ddd602d439ea64f03a5c188c59656d5ef389ecdcbff044c8d373e51c0e2b3"url = "https://github.com/cargo-bins/cargo-binstall/releases/download/v1.26.2/cargo-binstall-aarch64-apple-darwin.zip"url_api = "https://api.github.com/repos/cargo-bins/cargo-binstall/releases/assets/695465979"provenance = "github-attestations"[tools.cargo-binstall."platforms.windows-x64"]checksum = "sha256:c377a4977ffdbdcbf58dd263055b2f1d56ba873c69fbd6bfc60bef98256183a3"url = "https://github.com/cargo-bins/cargo-binstall/releases/download/v1.26.2/cargo-binstall-x86_64-pc-windows-msvc.zip"url_api = "https://api.github.com/repos/cargo-bins/cargo-binstall/releases/assets/695464456"provenance = "github-attestations"[[tools."cargo:kdl-lsp"]]version = "6.7.1"backend = "cargo:kdl-lsp"specifiers = ["latest"][[tools."cargo:resvg"]]version = "0.49.0"backend = "cargo:resvg"specifiers = ["latest"][[tools."github:Bios-Marcel/call_of_slop_modern_warefare_2"]]version = "0.5.9"backend = "github:Bios-Marcel/call_of_slop_modern_warefare_2"specifiers = ["latest"][tools."github:Bios-Marcel/call_of_slop_modern_warefare_2".options]asset_pattern = "rust-intervention-{{ version }}-linux-x86_64-forward-plus.zip"[tools."github:Bios-Marcel/call_of_slop_modern_warefare_2"."platforms.linux-x64"]checksum = "sha256:3368134eb44fb63c0382508476d8d0318401fd4088061f7c92389c825cb09e16"url = "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"url_api = "https://api.github.com/repos/Bios-Marcel/call_of_slop_modern_warefare_2/releases/assets/761122860"[[tools."github:Bios-Marcel/call_of_slop_modern_warefare_2"]]version = "0.5.9"backend = "github:Bios-Marcel/call_of_slop_modern_warefare_2"specifiers = ["latest"][tools."github:Bios-Marcel/call_of_slop_modern_warefare_2".options]asset_pattern = "rust-intervention-{{ version }}-windows-x86_64-forward-plus.zip"[tools."github:Bios-Marcel/call_of_slop_modern_warefare_2"."platforms.windows-x64"]checksum = "sha256:be38c84637f70d599ec0867cc49d14ba400216a78be9388865acbaa05f3dd6ff"url = "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"url_api = "https://api.github.com/repos/Bios-Marcel/call_of_slop_modern_warefare_2/releases/assets/761122859"[[tools."http:git-revue"]]version = "0.1.0"backend = "http:git-revue"specifiers = ["0.1.0"][tools."http:git-revue"."platforms.linux-x64"]checksum = "sha256:8e4de1339e27e5ce1af5aa22f8b0d547cf4fb4553cc41e02eb1c97465e396062"url = "https://pkg.bugabinga.net/releases/revue/git-revue-0.1.0-x86_64-unknown-linux-gnu.tar.gz"[tools."http:git-revue"."platforms.android-arm64"]checksum = "sha256:7189215130426cdbee92160192327ab318f3fa56fdb49d3d99c509a3c3d82768"url = "https://pkg.bugabinga.net/releases/revue/cross/git-revue-0.1.0-aarch64-linux-android.tar.gz"[[tools."http:mergiraf"]]version = "0.19.1"backend = "http:mergiraf"specifiers = ["0.19.1"][tools."http:mergiraf"."platforms.linux-x64"]checksum = "sha256:632ad77f90bf4874e8b89cfe7073bfbd6ad55c7565d2fa9530062b8df683cc30"url = "https://codeberg.org/mergiraf/mergiraf/releases/download/v0.19.1/mergiraf_x86_64-unknown-linux-musl.tar.gz"[tools."http:mergiraf"."platforms.macos-arm64"]checksum = "sha256:5bdcacc88dcabfd131591b3852a34c98fc9a23afdb5bc5ed1a58450269f7ddb2"url = "https://codeberg.org/mergiraf/mergiraf/releases/download/v0.19.1/mergiraf_aarch64-apple-darwin.tar.gz"[tools."http:mergiraf"."platforms.windows-x64"]checksum = "sha256:632ad77f90bf4874e8b89cfe7073bfbd6ad55c7565d2fa9530062b8df683cc30"url = "https://codeberg.org/mergiraf/mergiraf/releases/download/v0.19.1/mergiraf_x86_64-unknown-linux-musl.tar.gz"[[tools.mr-boxington]]version = "1.30.0"backend = "packslip:github.com/jdx/mr-boxington"specifiers = ["latest"][tools.mr-boxington."platforms.linux-x64"]checksum = "sha256:f4992b401fe65744b7c6e7400933d2106da205b499405621d088051a31a8f3f2"url = "https://github.com/jdx/mr-boxington/releases/download/v1.30.0/mbx-x86_64-unknown-linux-gnu.tar.gz"signer = "sigstore-oidc:https://github.com/jdx/mr-boxington/.github/workflows/release.yml"repository_ids = { repository = "1340721957" }[tools.mr-boxington."platforms.macos-arm64"]checksum = "sha256:d5b957216c8b61c2df91c9e7aaf5febd45ec74274a60d3714ebe316edc144543"url = "https://github.com/jdx/mr-boxington/releases/download/v1.30.0/mbx-aarch64-apple-darwin.tar.gz"signer = "sigstore-oidc:https://github.com/jdx/mr-boxington/.github/workflows/release.yml"repository_ids = { repository = "1340721957" }[tools.mr-boxington."platforms.windows-x64"]checksum = "sha256:2d709445957ea5dae95d51379aa9e7e575cfedb12c0d5731de4761a6972626f5"url = "https://github.com/jdx/mr-boxington/releases/download/v1.30.0/mbx-x86_64-pc-windows-msvc.zip"signer = "sigstore-oidc:https://github.com/jdx/mr-boxington/.github/workflows/release.yml"repository_ids = { repository = "1340721957" }[[tools."npm:cf"]]version = "1.0.0-beta.16"aube = { path = "locks/npm-cf/1.0.0-beta.16", digest = "sha256:8b59d85ea4e450bfdf4da508f9692c4e6f1331d89be7af4340a79e5c505c7ab6" }backend = "npm:cf"specifiers = ["1.0.0-beta.16"][[tools.rust]]version = "stable"backend = "core:rust"specifiers = ["latest"]mise/miserc.toml
Addednew file mode 100644+1 / −0 text lines
auto_env = truempv/scripts/skip.lua
Modified+29 / −29 text lines
-- Importing mpv module
local mpv = require('mp')
local mpv_options = require("mp.options")
local options = { -- setting default options
op_start = 0, op_end = 0, ed_start = 0, ed_end = 0,
}
mpv_options.read_options(options, "skip") --reading script-opts data
-- Main function to check and skip if within the defined section
local function skip()
local current_time = mp.get_property_number("time-pos")
if not current_time then
return
end
-- Check for opening sequence
if current_time >= options.op_start and current_time < options.op_end then
mp.set_property_number("time-pos", options.op_end)
end
-- Check for ending sequence
if current_time >= options.ed_start and current_time < options.ed_end then
mp.set_property_number("time-pos", options.ed_end)
end
end
-- Bind the function to be called whenever the time position is changed
-- Importing mpv modulelocal mpv = require('mp')local mpv_options = require("mp.options")local options = { -- setting default options op_start = 0, op_end = 0, ed_start = 0, ed_end = 0,}mpv_options.read_options(options, "skip") --reading script-opts data-- Main function to check and skip if within the defined sectionlocal function skip() local current_time = mp.get_property_number("time-pos") if not current_time then return end -- Check for opening sequence if current_time >= options.op_start and current_time < options.op_end then mp.set_property_number("time-pos", options.op_end) end -- Check for ending sequence if current_time >= options.ed_start and current_time < options.ed_end then mp.set_property_number("time-pos", options.ed_end) endend-- Bind the function to be called whenever the time position is changedmpv/shaders/Anime4K_AutoDownscalePre_x2.glsl
Modified+36 / −36 text lines
// This is free and unencumbered software released into the public domain.
// Anyone is free to copy, modify, publish, use, compile, sell, or
// distribute this software, either in source code form or as a compiled
// binary, for any purpose, commercial or non-commercial, and by any
// means.
// In jurisdictions that recognize copyright laws, the author or authors
// of this software dedicate any and all copyright interest in the
// software to the public domain. We make this dedication for the benefit
// of the public at large and to the detriment of our heirs and
// successors. We intend this dedication to be an overt act of
// relinquishment in perpetuity of all present and future rights to this
// software under copyright law.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
// OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
// For more information, please refer to <https://unlicense.org>
//!DESC Anime4K-v4.0-AutoDownscalePre-x2
//!HOOK MAIN
//!BIND HOOKED
//!BIND NATIVE
//!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 > * *
//!WIDTH OUTPUT.w
//!HEIGHT OUTPUT.h
vec4 hook() {
return HOOKED_tex(HOOKED_pos);
}
// This is free and unencumbered software released into the public domain.// Anyone is free to copy, modify, publish, use, compile, sell, or// distribute this software, either in source code form or as a compiled// binary, for any purpose, commercial or non-commercial, and by any// means.// In jurisdictions that recognize copyright laws, the author or authors// of this software dedicate any and all copyright interest in the// software to the public domain. We make this dedication for the benefit// of the public at large and to the detriment of our heirs and// successors. We intend this dedication to be an overt act of// relinquishment in perpetuity of all present and future rights to this// software under copyright law.// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.// IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR// OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR// OTHER DEALINGS IN THE SOFTWARE.// For more information, please refer to <https://unlicense.org>//!DESC Anime4K-v4.0-AutoDownscalePre-x2//!HOOK MAIN//!BIND HOOKED//!BIND NATIVE//!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 > * *//!WIDTH OUTPUT.w//!HEIGHT OUTPUT.hvec4 hook() { return HOOKED_tex(HOOKED_pos);}mpv/shaders/Anime4K_AutoDownscalePre_x4.glsl
Modified+36 / −36 text lines
// This is free and unencumbered software released into the public domain.
// Anyone is free to copy, modify, publish, use, compile, sell, or
// distribute this software, either in source code form or as a compiled
// binary, for any purpose, commercial or non-commercial, and by any
// means.
// In jurisdictions that recognize copyright laws, the author or authors
// of this software dedicate any and all copyright interest in the
// software to the public domain. We make this dedication for the benefit
// of the public at large and to the detriment of our heirs and
// successors. We intend this dedication to be an overt act of
// relinquishment in perpetuity of all present and future rights to this
// software under copyright law.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
// OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
// For more information, please refer to <https://unlicense.org>
//!DESC Anime4K-v3.2-AutoDownscalePre-x4
//!HOOK MAIN
//!BIND HOOKED
//!BIND NATIVE
//!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 > * *
//!WIDTH OUTPUT.w 2 /
//!HEIGHT OUTPUT.h 2 /
vec4 hook() {
return HOOKED_tex(HOOKED_pos);
}
// This is free and unencumbered software released into the public domain.// Anyone is free to copy, modify, publish, use, compile, sell, or// distribute this software, either in source code form or as a compiled// binary, for any purpose, commercial or non-commercial, and by any// means.// In jurisdictions that recognize copyright laws, the author or authors// of this software dedicate any and all copyright interest in the// software to the public domain. We make this dedication for the benefit// of the public at large and to the detriment of our heirs and// successors. We intend this dedication to be an overt act of// relinquishment in perpetuity of all present and future rights to this// software under copyright law.// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.// IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR// OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR// OTHER DEALINGS IN THE SOFTWARE.// For more information, please refer to <https://unlicense.org>//!DESC Anime4K-v3.2-AutoDownscalePre-x4//!HOOK MAIN//!BIND HOOKED//!BIND NATIVE//!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 > * *//!WIDTH OUTPUT.w 2 ///!HEIGHT OUTPUT.h 2 /vec4 hook() { return HOOKED_tex(HOOKED_pos);}mpv/shaders/Anime4K_Clamp_Highlights.glsl
Modified+89 / −89 text lines
// MIT License
// Copyright (c) 2019-2021 bloc97
// All rights reserved.
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//!DESC Anime4K-v4.0-De-Ring-Compute-Statistics
//!HOOK MAIN
//!BIND HOOKED
//!SAVE STATSMAX
//!COMPONENTS 1
#define KERNELSIZE 5 //Kernel size, must be an positive odd integer.
#define KERNELHALFSIZE 2 //Half of the kernel size without remainder. Must be equal to trunc(KERNELSIZE/2).
float get_luma(vec4 rgba) {
return dot(vec4(0.299, 0.587, 0.114, 0.0), rgba);
}
vec4 hook() {
float gmax = 0.0;
for (int i=0; i<KERNELSIZE; i++) {
float g = get_luma(MAIN_texOff(vec2(i - KERNELHALFSIZE, 0)));
gmax = max(g, gmax);
}
return vec4(gmax, 0.0, 0.0, 0.0);
}
//!DESC Anime4K-v4.0-De-Ring-Compute-Statistics
//!HOOK MAIN
//!BIND HOOKED
//!BIND STATSMAX
//!SAVE STATSMAX
//!COMPONENTS 1
#define KERNELSIZE 5 //Kernel size, must be an positive odd integer.
#define KERNELHALFSIZE 2 //Half of the kernel size without remainder. Must be equal to trunc(KERNELSIZE/2).
vec4 hook() {
float gmax = 0.0;
for (int i=0; i<KERNELSIZE; i++) {
float g = STATSMAX_texOff(vec2(0, i - KERNELHALFSIZE)).x;
gmax = max(g, gmax);
}
return vec4(gmax, 0.0, 0.0, 0.0);
}
//!DESC Anime4K-v4.0-De-Ring-Clamp
//!HOOK PREKERNEL
//!BIND HOOKED
//!BIND STATSMAX
float get_luma(vec4 rgba) {
return dot(vec4(0.299, 0.587, 0.114, 0.0), rgba);
}
vec4 hook() {
float current_luma = get_luma(HOOKED_tex(HOOKED_pos));
float new_luma = min(current_luma, STATSMAX_tex(HOOKED_pos).x);
//This trick is only possible if the inverse Y->RGB matrix has 1 for every row... (which is the case for BT.709)
//Otherwise we would need to convert RGB to YUV, modify Y then convert back to RGB.
return HOOKED_tex(HOOKED_pos) - (current_luma - new_luma);
// MIT License// Copyright (c) 2019-2021 bloc97// All rights reserved.// Permission is hereby granted, free of charge, to any person obtaining a copy// of this software and associated documentation files (the "Software"), to deal// in the Software without restriction, including without limitation the rights// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell// copies of the Software, and to permit persons to whom the Software is// furnished to do so, subject to the following conditions:// The above copyright notice and this permission notice shall be included in all// copies or substantial portions of the Software.// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE// SOFTWARE.//!DESC Anime4K-v4.0-De-Ring-Compute-Statistics//!HOOK MAIN//!BIND HOOKED//!SAVE STATSMAX//!COMPONENTS 1#define KERNELSIZE 5 //Kernel size, must be an positive odd integer.#define KERNELHALFSIZE 2 //Half of the kernel size without remainder. Must be equal to trunc(KERNELSIZE/2).float get_luma(vec4 rgba) { return dot(vec4(0.299, 0.587, 0.114, 0.0), rgba);}vec4 hook() { float gmax = 0.0; for (int i=0; i<KERNELSIZE; i++) { float g = get_luma(MAIN_texOff(vec2(i - KERNELHALFSIZE, 0))); gmax = max(g, gmax); } return vec4(gmax, 0.0, 0.0, 0.0);}//!DESC Anime4K-v4.0-De-Ring-Compute-Statistics//!HOOK MAIN//!BIND HOOKED//!BIND STATSMAX//!SAVE STATSMAX//!COMPONENTS 1#define KERNELSIZE 5 //Kernel size, must be an positive odd integer.#define KERNELHALFSIZE 2 //Half of the kernel size without remainder. Must be equal to trunc(KERNELSIZE/2).vec4 hook() { float gmax = 0.0; for (int i=0; i<KERNELSIZE; i++) { float g = STATSMAX_texOff(vec2(0, i - KERNELHALFSIZE)).x; gmax = max(g, gmax); } return vec4(gmax, 0.0, 0.0, 0.0);}//!DESC Anime4K-v4.0-De-Ring-Clamp//!HOOK PREKERNEL//!BIND HOOKED//!BIND STATSMAXfloat get_luma(vec4 rgba) { return dot(vec4(0.299, 0.587, 0.114, 0.0), rgba);}vec4 hook() { float current_luma = get_luma(HOOKED_tex(HOOKED_pos)); float new_luma = min(current_luma, STATSMAX_tex(HOOKED_pos).x); //This trick is only possible if the inverse Y->RGB matrix has 1 for every row... (which is the case for BT.709) //Otherwise we would need to convert RGB to YUV, modify Y then convert back to RGB. return HOOKED_tex(HOOKED_pos) - (current_luma - new_luma); mpv/shaders/Anime4K_Darken_Fast.glsl
Modified+216 / −216 text lines
// MIT License
// Copyright (c) 2019-2021 bloc97
// All rights reserved.
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//!DESC Anime4K-v3.2-Darken-DoG-(HQ)-Luma
//!HOOK MAIN
//!BIND HOOKED
//!SAVE LINELUMA
//!COMPONENTS 1
float get_luma(vec4 rgba) {
return dot(vec4(0.299, 0.587, 0.114, 0.0), rgba);
}
vec4 hook() {
return vec4(get_luma(HOOKED_tex(HOOKED_pos)), 0.0, 0.0, 0.0);
}
//!DESC Anime4K-v3.2-Darken-DoG-(Fast)-Difference-X
//!HOOK MAIN
//!BIND HOOKED
//!BIND LINELUMA
//!SAVE LINEKERNEL
//!WIDTH HOOKED.w 2 /
//!HEIGHT HOOKED.h 2 /
//!COMPONENTS 1
#define SPATIAL_SIGMA (1.0 * float(HOOKED_size.y) / 1080.0) //Spatial window size, must be a positive real number.
#define KERNELSIZE (max(int(ceil(SPATIAL_SIGMA * 2.0)), 1) * 2 + 1) //Kernel size, must be an positive odd integer.
#define KERNELHALFSIZE (int(KERNELSIZE/2)) //Half of the kernel size without remainder. Must be equal to trunc(KERNELSIZE/2).
#define KERNELLEN (KERNELSIZE * KERNELSIZE) //Total area of kernel. Must be equal to KERNELSIZE * KERNELSIZE.
float gaussian(float x, float s, float m) {
float scaled = (x - m) / s;
return exp(-0.5 * scaled * scaled);
}
float comp_gaussian_x() {
float g = 0.0;
float gn = 0.0;
for (int i=0; i<KERNELSIZE; i++) {
float di = float(i - KERNELHALFSIZE);
float gf = gaussian(di, SPATIAL_SIGMA, 0.0);
g = g + LINELUMA_texOff(vec2(di, 0.0)).x * gf;
gn = gn + gf;
}
return g / gn;
}
vec4 hook() {
return vec4(comp_gaussian_x(), 0.0, 0.0, 0.0);
}
//!DESC Anime4K-v3.2-Darken-DoG-(Fast)-Difference-Y
//!HOOK MAIN
//!BIND HOOKED
//!BIND LINELUMA
//!BIND LINEKERNEL
//!SAVE LINEKERNEL
//!WIDTH HOOKED.w 2 /
//!HEIGHT HOOKED.h 2 /
//!COMPONENTS 1
#define SPATIAL_SIGMA (0.5 * float(HOOKED_size.y) / 1080.0) //Spatial window size, must be a positive real number.
#define KERNELSIZE (max(int(ceil(SPATIAL_SIGMA * 2.0)), 1) * 2 + 1) //Kernel size, must be an positive odd integer.
#define KERNELHALFSIZE (int(KERNELSIZE/2)) //Half of the kernel size without remainder. Must be equal to trunc(KERNELSIZE/2).
#define KERNELLEN (KERNELSIZE * KERNELSIZE) //Total area of kernel. Must be equal to KERNELSIZE * KERNELSIZE.
float gaussian(float x, float s, float m) {
float scaled = (x - m) / s;
return exp(-0.5 * scaled * scaled);
}
float comp_gaussian_y() {
float g = 0.0;
float gn = 0.0;
for (int i=0; i<KERNELSIZE; i++) {
float di = float(i - KERNELHALFSIZE);
float gf = gaussian(di, SPATIAL_SIGMA, 0.0);
g = g + LINEKERNEL_texOff(vec2(0.0, di)).x * gf;
gn = gn + gf;
}
return g / gn;
}
vec4 hook() {
return vec4(min(LINELUMA_tex(HOOKED_pos).x - comp_gaussian_y(), 0.0), 0.0, 0.0, 0.0);
}
//!DESC Anime4K-v3.2-Darken-DoG-(Fast)-Gaussian-X
//!HOOK MAIN
//!BIND HOOKED
//!BIND LINEKERNEL
//!SAVE LINEKERNEL
//!WIDTH HOOKED.w 2 /
//!HEIGHT HOOKED.h 2 /
//!COMPONENTS 1
#define SPATIAL_SIGMA (0.5 * float(HOOKED_size.y) / 1080.0) //Spatial window size, must be a positive real number.
#define KERNELSIZE (max(int(ceil(SPATIAL_SIGMA * 2.0)), 1) * 2 + 1) //Kernel size, must be an positive odd integer.
#define KERNELHALFSIZE (int(KERNELSIZE/2)) //Half of the kernel size without remainder. Must be equal to trunc(KERNELSIZE/2).
#define KERNELLEN (KERNELSIZE * KERNELSIZE) //Total area of kernel. Must be equal to KERNELSIZE * KERNELSIZE.
float gaussian(float x, float s, float m) {
float scaled = (x - m) / s;
return exp(-0.5 * scaled * scaled);
}
float comp_gaussian_x() {
float g = 0.0;
float gn = 0.0;
for (int i=0; i<KERNELSIZE; i++) {
float di = float(i - KERNELHALFSIZE);
float gf = gaussian(di, SPATIAL_SIGMA, 0.0);
g = g + LINEKERNEL_texOff(vec2(di, 0.0)).x * gf;
gn = gn + gf;
}
return g / gn;
}
vec4 hook() {
return vec4(comp_gaussian_x(), 0.0, 0.0, 0.0);
}
//!DESC Anime4K-v3.2-Darken-DoG-(Fast)-Gaussian-Y
//!HOOK MAIN
//!BIND HOOKED
//!BIND LINEKERNEL
//!SAVE LINEKERNEL
//!WIDTH HOOKED.w 2 /
//!HEIGHT HOOKED.h 2 /
//!COMPONENTS 1
#define SPATIAL_SIGMA (0.5 * float(HOOKED_size.y) / 1080.0) //Spatial window size, must be a positive real number.
#define KERNELSIZE (max(int(ceil(SPATIAL_SIGMA * 2.0)), 1) * 2 + 1) //Kernel size, must be an positive odd integer.
#define KERNELHALFSIZE (int(KERNELSIZE/2)) //Half of the kernel size without remainder. Must be equal to trunc(KERNELSIZE/2).
#define KERNELLEN (KERNELSIZE * KERNELSIZE) //Total area of kernel. Must be equal to KERNELSIZE * KERNELSIZE.
float gaussian(float x, float s, float m) {
float scaled = (x - m) / s;
return exp(-0.5 * scaled * scaled);
}
float comp_gaussian_y() {
float g = 0.0;
float gn = 0.0;
for (int i=0; i<KERNELSIZE; i++) {
float di = float(i - KERNELHALFSIZE);
float gf = gaussian(di, SPATIAL_SIGMA, 0.0);
g = g + LINEKERNEL_texOff(vec2(0.0, di)).x * gf;
gn = gn + gf;
}
return g / gn;
}
vec4 hook() {
return vec4(comp_gaussian_y(), 0.0, 0.0, 0.0);
}
//!DESC Anime4K-v3.2-Darken-DoG-(Fast)-Upsample
//!HOOK MAIN
//!BIND HOOKED
//!BIND LINEKERNEL
#define STRENGTH 1.5 //Line darken proportional strength, higher is darker.
vec4 hook() {
//This trick is only possible if the inverse Y->RGB matrix has 1 for every row... (which is the case for BT.709)
//Otherwise we would need to convert RGB to YUV, modify Y then convert back to RGB.
return HOOKED_tex(HOOKED_pos) + (LINEKERNEL_tex(HOOKED_pos).x * STRENGTH);
}
// MIT License// Copyright (c) 2019-2021 bloc97// All rights reserved.// Permission is hereby granted, free of charge, to any person obtaining a copy// of this software and associated documentation files (the "Software"), to deal// in the Software without restriction, including without limitation the rights// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell// copies of the Software, and to permit persons to whom the Software is// furnished to do so, subject to the following conditions:// The above copyright notice and this permission notice shall be included in all// copies or substantial portions of the Software.// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE// SOFTWARE.//!DESC Anime4K-v3.2-Darken-DoG-(HQ)-Luma//!HOOK MAIN//!BIND HOOKED//!SAVE LINELUMA//!COMPONENTS 1float get_luma(vec4 rgba) { return dot(vec4(0.299, 0.587, 0.114, 0.0), rgba);}vec4 hook() { return vec4(get_luma(HOOKED_tex(HOOKED_pos)), 0.0, 0.0, 0.0);}//!DESC Anime4K-v3.2-Darken-DoG-(Fast)-Difference-X//!HOOK MAIN//!BIND HOOKED//!BIND LINELUMA//!SAVE LINEKERNEL//!WIDTH HOOKED.w 2 ///!HEIGHT HOOKED.h 2 ///!COMPONENTS 1#define SPATIAL_SIGMA (1.0 * float(HOOKED_size.y) / 1080.0) //Spatial window size, must be a positive real number.#define KERNELSIZE (max(int(ceil(SPATIAL_SIGMA * 2.0)), 1) * 2 + 1) //Kernel size, must be an positive odd integer.#define KERNELHALFSIZE (int(KERNELSIZE/2)) //Half of the kernel size without remainder. Must be equal to trunc(KERNELSIZE/2).#define KERNELLEN (KERNELSIZE * KERNELSIZE) //Total area of kernel. Must be equal to KERNELSIZE * KERNELSIZE.float gaussian(float x, float s, float m) { float scaled = (x - m) / s; return exp(-0.5 * scaled * scaled);}float comp_gaussian_x() { float g = 0.0; float gn = 0.0; for (int i=0; i<KERNELSIZE; i++) { float di = float(i - KERNELHALFSIZE); float gf = gaussian(di, SPATIAL_SIGMA, 0.0); g = g + LINELUMA_texOff(vec2(di, 0.0)).x * gf; gn = gn + gf; } return g / gn;}vec4 hook() { return vec4(comp_gaussian_x(), 0.0, 0.0, 0.0);}//!DESC Anime4K-v3.2-Darken-DoG-(Fast)-Difference-Y//!HOOK MAIN//!BIND HOOKED//!BIND LINELUMA//!BIND LINEKERNEL//!SAVE LINEKERNEL//!WIDTH HOOKED.w 2 ///!HEIGHT HOOKED.h 2 ///!COMPONENTS 1#define SPATIAL_SIGMA (0.5 * float(HOOKED_size.y) / 1080.0) //Spatial window size, must be a positive real number.#define KERNELSIZE (max(int(ceil(SPATIAL_SIGMA * 2.0)), 1) * 2 + 1) //Kernel size, must be an positive odd integer.#define KERNELHALFSIZE (int(KERNELSIZE/2)) //Half of the kernel size without remainder. Must be equal to trunc(KERNELSIZE/2).#define KERNELLEN (KERNELSIZE * KERNELSIZE) //Total area of kernel. Must be equal to KERNELSIZE * KERNELSIZE.float gaussian(float x, float s, float m) { float scaled = (x - m) / s; return exp(-0.5 * scaled * scaled);}float comp_gaussian_y() { float g = 0.0; float gn = 0.0; for (int i=0; i<KERNELSIZE; i++) { float di = float(i - KERNELHALFSIZE); float gf = gaussian(di, SPATIAL_SIGMA, 0.0); g = g + LINEKERNEL_texOff(vec2(0.0, di)).x * gf; gn = gn + gf; } return g / gn;}vec4 hook() { return vec4(min(LINELUMA_tex(HOOKED_pos).x - comp_gaussian_y(), 0.0), 0.0, 0.0, 0.0);}//!DESC Anime4K-v3.2-Darken-DoG-(Fast)-Gaussian-X//!HOOK MAIN//!BIND HOOKED//!BIND LINEKERNEL//!SAVE LINEKERNEL//!WIDTH HOOKED.w 2 ///!HEIGHT HOOKED.h 2 ///!COMPONENTS 1#define SPATIAL_SIGMA (0.5 * float(HOOKED_size.y) / 1080.0) //Spatial window size, must be a positive real number.#define KERNELSIZE (max(int(ceil(SPATIAL_SIGMA * 2.0)), 1) * 2 + 1) //Kernel size, must be an positive odd integer.#define KERNELHALFSIZE (int(KERNELSIZE/2)) //Half of the kernel size without remainder. Must be equal to trunc(KERNELSIZE/2).#define KERNELLEN (KERNELSIZE * KERNELSIZE) //Total area of kernel. Must be equal to KERNELSIZE * KERNELSIZE.float gaussian(float x, float s, float m) { float scaled = (x - m) / s; return exp(-0.5 * scaled * scaled);}float comp_gaussian_x() { float g = 0.0; float gn = 0.0; for (int i=0; i<KERNELSIZE; i++) { float di = float(i - KERNELHALFSIZE); float gf = gaussian(di, SPATIAL_SIGMA, 0.0); g = g + LINEKERNEL_texOff(vec2(di, 0.0)).x * gf; gn = gn + gf; } return g / gn;}vec4 hook() { return vec4(comp_gaussian_x(), 0.0, 0.0, 0.0);}//!DESC Anime4K-v3.2-Darken-DoG-(Fast)-Gaussian-Y//!HOOK MAIN//!BIND HOOKED//!BIND LINEKERNEL//!SAVE LINEKERNEL//!WIDTH HOOKED.w 2 ///!HEIGHT HOOKED.h 2 ///!COMPONENTS 1#define SPATIAL_SIGMA (0.5 * float(HOOKED_size.y) / 1080.0) //Spatial window size, must be a positive real number.#define KERNELSIZE (max(int(ceil(SPATIAL_SIGMA * 2.0)), 1) * 2 + 1) //Kernel size, must be an positive odd integer.#define KERNELHALFSIZE (int(KERNELSIZE/2)) //Half of the kernel size without remainder. Must be equal to trunc(KERNELSIZE/2).#define KERNELLEN (KERNELSIZE * KERNELSIZE) //Total area of kernel. Must be equal to KERNELSIZE * KERNELSIZE.float gaussian(float x, float s, float m) { float scaled = (x - m) / s; return exp(-0.5 * scaled * scaled);}float comp_gaussian_y() { float g = 0.0; float gn = 0.0; for (int i=0; i<KERNELSIZE; i++) { float di = float(i - KERNELHALFSIZE); float gf = gaussian(di, SPATIAL_SIGMA, 0.0); g = g + LINEKERNEL_texOff(vec2(0.0, di)).x * gf; gn = gn + gf; } return g / gn;}vec4 hook() { return vec4(comp_gaussian_y(), 0.0, 0.0, 0.0);}//!DESC Anime4K-v3.2-Darken-DoG-(Fast)-Upsample//!HOOK MAIN//!BIND HOOKED//!BIND LINEKERNEL#define STRENGTH 1.5 //Line darken proportional strength, higher is darker.vec4 hook() { //This trick is only possible if the inverse Y->RGB matrix has 1 for every row... (which is the case for BT.709) //Otherwise we would need to convert RGB to YUV, modify Y then convert back to RGB. return HOOKED_tex(HOOKED_pos) + (LINEKERNEL_tex(HOOKED_pos).x * STRENGTH);}mpv/shaders/Anime4K_Darken_HQ.glsl
Modified+198 / −198 text lines
// MIT License
// Copyright (c) 2019-2021 bloc97
// All rights reserved.
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//!DESC Anime4K-v3.2-Darken-DoG-(HQ)-Luma
//!HOOK MAIN
//!BIND HOOKED
//!SAVE LINELUMA
//!COMPONENTS 1
float get_luma(vec4 rgba) {
return dot(vec4(0.299, 0.587, 0.114, 0.0), rgba);
}
vec4 hook() {
return vec4(get_luma(HOOKED_tex(HOOKED_pos)), 0.0, 0.0, 0.0);
}
//!DESC Anime4K-v3.2-Darken-DoG-(HQ)-Difference-X
//!HOOK MAIN
//!BIND HOOKED
//!BIND LINELUMA
//!SAVE LINEKERNEL
//!COMPONENTS 1
#define SPATIAL_SIGMA (1.0 * float(HOOKED_size.y) / 1080.0) //Spatial window size, must be a positive real number.
#define KERNELSIZE (max(int(ceil(SPATIAL_SIGMA * 2.0)), 1) * 2 + 1) //Kernel size, must be an positive odd integer.
#define KERNELHALFSIZE (int(KERNELSIZE/2)) //Half of the kernel size without remainder. Must be equal to trunc(KERNELSIZE/2).
#define KERNELLEN (KERNELSIZE * KERNELSIZE) //Total area of kernel. Must be equal to KERNELSIZE * KERNELSIZE.
float gaussian(float x, float s, float m) {
float scaled = (x - m) / s;
return exp(-0.5 * scaled * scaled);
}
float comp_gaussian_x() {
float g = 0.0;
float gn = 0.0;
for (int i=0; i<KERNELSIZE; i++) {
float di = float(i - KERNELHALFSIZE);
float gf = gaussian(di, SPATIAL_SIGMA, 0.0);
g = g + LINELUMA_texOff(vec2(di, 0.0)).x * gf;
gn = gn + gf;
}
return g / gn;
}
vec4 hook() {
return vec4(comp_gaussian_x(), 0.0, 0.0, 0.0);
}
//!DESC Anime4K-v3.2-Darken-DoG-(HQ)-Difference-Y
//!HOOK MAIN
//!BIND HOOKED
//!BIND LINELUMA
//!BIND LINEKERNEL
//!SAVE LINEKERNEL
//!COMPONENTS 1
#define SPATIAL_SIGMA (1.0 * float(HOOKED_size.y) / 1080.0) //Spatial window size, must be a positive real number.
#define KERNELSIZE (max(int(ceil(SPATIAL_SIGMA * 2.0)), 1) * 2 + 1) //Kernel size, must be an positive odd integer.
#define KERNELHALFSIZE (int(KERNELSIZE/2)) //Half of the kernel size without remainder. Must be equal to trunc(KERNELSIZE/2).
#define KERNELLEN (KERNELSIZE * KERNELSIZE) //Total area of kernel. Must be equal to KERNELSIZE * KERNELSIZE.
float gaussian(float x, float s, float m) {
float scaled = (x - m) / s;
return exp(-0.5 * scaled * scaled);
}
float comp_gaussian_y() {
float g = 0.0;
float gn = 0.0;
for (int i=0; i<KERNELSIZE; i++) {
float di = float(i - KERNELHALFSIZE);
float gf = gaussian(di, SPATIAL_SIGMA, 0.0);
g = g + LINEKERNEL_texOff(vec2(0.0, di)).x * gf;
gn = gn + gf;
}
return g / gn;
}
vec4 hook() {
return vec4(min(LINELUMA_tex(HOOKED_pos).x - comp_gaussian_y(), 0.0), 0.0, 0.0, 0.0);
}
//!DESC Anime4K-v3.2-Darken-DoG-(HQ)-Gaussian-X
//!HOOK MAIN
//!BIND HOOKED
//!BIND LINEKERNEL
//!SAVE LINEKERNEL
//!COMPONENTS 1
#define SPATIAL_SIGMA (1.0 * float(HOOKED_size.y) / 1080.0) //Spatial window size, must be a positive real number.
#define KERNELSIZE (max(int(ceil(SPATIAL_SIGMA * 2.0)), 1) * 2 + 1) //Kernel size, must be an positive odd integer.
#define KERNELHALFSIZE (int(KERNELSIZE/2)) //Half of the kernel size without remainder. Must be equal to trunc(KERNELSIZE/2).
#define KERNELLEN (KERNELSIZE * KERNELSIZE) //Total area of kernel. Must be equal to KERNELSIZE * KERNELSIZE.
float gaussian(float x, float s, float m) {
float scaled = (x - m) / s;
return exp(-0.5 * scaled * scaled);
}
float comp_gaussian_x() {
float g = 0.0;
float gn = 0.0;
for (int i=0; i<KERNELSIZE; i++) {
float di = float(i - KERNELHALFSIZE);
float gf = gaussian(di, SPATIAL_SIGMA, 0.0);
g = g + LINEKERNEL_texOff(vec2(di, 0.0)).x * gf;
gn = gn + gf;
}
return g / gn;
}
vec4 hook() {
return vec4(comp_gaussian_x(), 0.0, 0.0, 0.0);
}
//!DESC Anime4K-v3.2-Darken-DoG-(HQ)-Gaussian-Y
//!HOOK MAIN
//!BIND HOOKED
//!BIND LINEKERNEL
#define SPATIAL_SIGMA (1.0 * float(HOOKED_size.y) / 1080.0) //Spatial window size, must be a positive real number.
#define KERNELSIZE (max(int(ceil(SPATIAL_SIGMA * 2.0)), 1) * 2 + 1) //Kernel size, must be an positive odd integer.
#define KERNELHALFSIZE (int(KERNELSIZE/2)) //Half of the kernel size without remainder. Must be equal to trunc(KERNELSIZE/2).
#define KERNELLEN (KERNELSIZE * KERNELSIZE) //Total area of kernel. Must be equal to KERNELSIZE * KERNELSIZE.
float gaussian(float x, float s, float m) {
float scaled = (x - m) / s;
return exp(-0.5 * scaled * scaled);
}
float comp_gaussian_y() {
float g = 0.0;
float gn = 0.0;
for (int i=0; i<KERNELSIZE; i++) {
float di = float(i - KERNELHALFSIZE);
float gf = gaussian(di, SPATIAL_SIGMA, 0.0);
g = g + LINEKERNEL_texOff(vec2(0.0, di)).x * gf;
gn = gn + gf;
}
return g / gn;
}
#define STRENGTH 1.5 //Line darken proportional strength, higher is darker.
vec4 hook() {
//This trick is only possible if the inverse Y->RGB matrix has 1 for every row... (which is the case for BT.709)
//Otherwise we would need to convert RGB to YUV, modify Y then convert back to RGB.
return HOOKED_tex(HOOKED_pos) + (comp_gaussian_y() * STRENGTH);
}
// MIT License// Copyright (c) 2019-2021 bloc97// All rights reserved.// Permission is hereby granted, free of charge, to any person obtaining a copy// of this software and associated documentation files (the "Software"), to deal// in the Software without restriction, including without limitation the rights// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell// copies of the Software, and to permit persons to whom the Software is// furnished to do so, subject to the following conditions:// The above copyright notice and this permission notice shall be included in all// copies or substantial portions of the Software.// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE// SOFTWARE.//!DESC Anime4K-v3.2-Darken-DoG-(HQ)-Luma//!HOOK MAIN//!BIND HOOKED//!SAVE LINELUMA//!COMPONENTS 1float get_luma(vec4 rgba) { return dot(vec4(0.299, 0.587, 0.114, 0.0), rgba);}vec4 hook() { return vec4(get_luma(HOOKED_tex(HOOKED_pos)), 0.0, 0.0, 0.0);}//!DESC Anime4K-v3.2-Darken-DoG-(HQ)-Difference-X//!HOOK MAIN//!BIND HOOKED//!BIND LINELUMA//!SAVE LINEKERNEL//!COMPONENTS 1#define SPATIAL_SIGMA (1.0 * float(HOOKED_size.y) / 1080.0) //Spatial window size, must be a positive real number.#define KERNELSIZE (max(int(ceil(SPATIAL_SIGMA * 2.0)), 1) * 2 + 1) //Kernel size, must be an positive odd integer.#define KERNELHALFSIZE (int(KERNELSIZE/2)) //Half of the kernel size without remainder. Must be equal to trunc(KERNELSIZE/2).#define KERNELLEN (KERNELSIZE * KERNELSIZE) //Total area of kernel. Must be equal to KERNELSIZE * KERNELSIZE.float gaussian(float x, float s, float m) { float scaled = (x - m) / s; return exp(-0.5 * scaled * scaled);}float comp_gaussian_x() { float g = 0.0; float gn = 0.0; for (int i=0; i<KERNELSIZE; i++) { float di = float(i - KERNELHALFSIZE); float gf = gaussian(di, SPATIAL_SIGMA, 0.0); g = g + LINELUMA_texOff(vec2(di, 0.0)).x * gf; gn = gn + gf; } return g / gn;}vec4 hook() { return vec4(comp_gaussian_x(), 0.0, 0.0, 0.0);}//!DESC Anime4K-v3.2-Darken-DoG-(HQ)-Difference-Y//!HOOK MAIN//!BIND HOOKED//!BIND LINELUMA//!BIND LINEKERNEL//!SAVE LINEKERNEL//!COMPONENTS 1#define SPATIAL_SIGMA (1.0 * float(HOOKED_size.y) / 1080.0) //Spatial window size, must be a positive real number.#define KERNELSIZE (max(int(ceil(SPATIAL_SIGMA * 2.0)), 1) * 2 + 1) //Kernel size, must be an positive odd integer.#define KERNELHALFSIZE (int(KERNELSIZE/2)) //Half of the kernel size without remainder. Must be equal to trunc(KERNELSIZE/2).#define KERNELLEN (KERNELSIZE * KERNELSIZE) //Total area of kernel. Must be equal to KERNELSIZE * KERNELSIZE.float gaussian(float x, float s, float m) { float scaled = (x - m) / s; return exp(-0.5 * scaled * scaled);}float comp_gaussian_y() { float g = 0.0; float gn = 0.0; for (int i=0; i<KERNELSIZE; i++) { float di = float(i - KERNELHALFSIZE); float gf = gaussian(di, SPATIAL_SIGMA, 0.0); g = g + LINEKERNEL_texOff(vec2(0.0, di)).x * gf; gn = gn + gf; } return g / gn;}vec4 hook() { return vec4(min(LINELUMA_tex(HOOKED_pos).x - comp_gaussian_y(), 0.0), 0.0, 0.0, 0.0);}//!DESC Anime4K-v3.2-Darken-DoG-(HQ)-Gaussian-X//!HOOK MAIN//!BIND HOOKED//!BIND LINEKERNEL//!SAVE LINEKERNEL//!COMPONENTS 1#define SPATIAL_SIGMA (1.0 * float(HOOKED_size.y) / 1080.0) //Spatial window size, must be a positive real number.#define KERNELSIZE (max(int(ceil(SPATIAL_SIGMA * 2.0)), 1) * 2 + 1) //Kernel size, must be an positive odd integer.#define KERNELHALFSIZE (int(KERNELSIZE/2)) //Half of the kernel size without remainder. Must be equal to trunc(KERNELSIZE/2).#define KERNELLEN (KERNELSIZE * KERNELSIZE) //Total area of kernel. Must be equal to KERNELSIZE * KERNELSIZE.float gaussian(float x, float s, float m) { float scaled = (x - m) / s; return exp(-0.5 * scaled * scaled);}float comp_gaussian_x() { float g = 0.0; float gn = 0.0; for (int i=0; i<KERNELSIZE; i++) { float di = float(i - KERNELHALFSIZE); float gf = gaussian(di, SPATIAL_SIGMA, 0.0); g = g + LINEKERNEL_texOff(vec2(di, 0.0)).x * gf; gn = gn + gf; } return g / gn;}vec4 hook() { return vec4(comp_gaussian_x(), 0.0, 0.0, 0.0);}//!DESC Anime4K-v3.2-Darken-DoG-(HQ)-Gaussian-Y//!HOOK MAIN//!BIND HOOKED//!BIND LINEKERNEL#define SPATIAL_SIGMA (1.0 * float(HOOKED_size.y) / 1080.0) //Spatial window size, must be a positive real number.#define KERNELSIZE (max(int(ceil(SPATIAL_SIGMA * 2.0)), 1) * 2 + 1) //Kernel size, must be an positive odd integer.#define KERNELHALFSIZE (int(KERNELSIZE/2)) //Half of the kernel size without remainder. Must be equal to trunc(KERNELSIZE/2).#define KERNELLEN (KERNELSIZE * KERNELSIZE) //Total area of kernel. Must be equal to KERNELSIZE * KERNELSIZE.float gaussian(float x, float s, float m) { float scaled = (x - m) / s; return exp(-0.5 * scaled * scaled);}float comp_gaussian_y() { float g = 0.0; float gn = 0.0; for (int i=0; i<KERNELSIZE; i++) { float di = float(i - KERNELHALFSIZE); float gf = gaussian(di, SPATIAL_SIGMA, 0.0); g = g + LINEKERNEL_texOff(vec2(0.0, di)).x * gf; gn = gn + gf; } return g / gn;}#define STRENGTH 1.5 //Line darken proportional strength, higher is darker.vec4 hook() { //This trick is only possible if the inverse Y->RGB matrix has 1 for every row... (which is the case for BT.709) //Otherwise we would need to convert RGB to YUV, modify Y then convert back to RGB. return HOOKED_tex(HOOKED_pos) + (comp_gaussian_y() * STRENGTH);}mpv/shaders/Anime4K_Darken_VeryFast.glsl
Modified+218 / −218 text lines
// MIT License
// Copyright (c) 2019-2021 bloc97
// All rights reserved.
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//!DESC Anime4K-v3.2-Darken-DoG-(HQ)-Luma
//!HOOK MAIN
//!BIND HOOKED
//!SAVE LINELUMA
//!WIDTH HOOKED.w 2 /
//!HEIGHT HOOKED.h 2 /
//!COMPONENTS 1
float get_luma(vec4 rgba) {
return dot(vec4(0.299, 0.587, 0.114, 0.0), rgba);
}
vec4 hook() {
return vec4(get_luma(HOOKED_tex(HOOKED_pos)), 0.0, 0.0, 0.0);
}
//!DESC Anime4K-v3.2-Darken-DoG-(VeryFast)-Gaussian-X
//!HOOK MAIN
//!BIND HOOKED
//!BIND LINELUMA
//!SAVE LINEKERNEL
//!WIDTH HOOKED.w 4 /
//!HEIGHT HOOKED.h 4 /
//!COMPONENTS 1
#define SPATIAL_SIGMA (0.5 * float(HOOKED_size.y) / 1080.0) //Spatial window size, must be a positive real number.
#define KERNELSIZE (max(int(ceil(SPATIAL_SIGMA * 2.0)), 1) * 2 + 1) //Kernel size, must be an positive odd integer.
#define KERNELHALFSIZE (int(KERNELSIZE/2)) //Half of the kernel size without remainder. Must be equal to trunc(KERNELSIZE/2).
#define KERNELLEN (KERNELSIZE * KERNELSIZE) //Total area of kernel. Must be equal to KERNELSIZE * KERNELSIZE.
float gaussian(float x, float s, float m) {
float scaled = (x - m) / s;
return exp(-0.5 * scaled * scaled);
}
float comp_gaussian_x() {
float g = 0.0;
float gn = 0.0;
for (int i=0; i<KERNELSIZE; i++) {
float di = float(i - KERNELHALFSIZE);
float gf = gaussian(di, SPATIAL_SIGMA, 0.0);
g = g + LINELUMA_texOff(vec2(di, 0.0)).x * gf;
gn = gn + gf;
}
return g / gn;
}
vec4 hook() {
return vec4(comp_gaussian_x(), 0.0, 0.0, 0.0);
}
//!DESC Anime4K-v3.2-Darken-DoG-(VeryFast)-Gaussian-Y
//!HOOK MAIN
//!BIND HOOKED
//!BIND LINELUMA
//!BIND LINEKERNEL
//!SAVE LINEKERNEL
//!WIDTH HOOKED.w 4 /
//!HEIGHT HOOKED.h 4 /
//!COMPONENTS 1
#define SPATIAL_SIGMA (0.25 * float(HOOKED_size.y) / 1080.0) //Spatial window size, must be a positive real number.
#define KERNELSIZE (max(int(ceil(SPATIAL_SIGMA * 2.0)), 1) * 2 + 1) //Kernel size, must be an positive odd integer.
#define KERNELHALFSIZE (int(KERNELSIZE/2)) //Half of the kernel size without remainder. Must be equal to trunc(KERNELSIZE/2).
#define KERNELLEN (KERNELSIZE * KERNELSIZE) //Total area of kernel. Must be equal to KERNELSIZE * KERNELSIZE.
float gaussian(float x, float s, float m) {
float scaled = (x - m) / s;
return exp(-0.5 * scaled * scaled);
}
float comp_gaussian_y() {
float g = 0.0;
float gn = 0.0;
for (int i=0; i<KERNELSIZE; i++) {
float di = float(i - KERNELHALFSIZE);
float gf = gaussian(di, SPATIAL_SIGMA, 0.0);
g = g + LINEKERNEL_texOff(vec2(0.0, di)).x * gf;
gn = gn + gf;
}
return g / gn;
}
vec4 hook() {
return vec4(min(LINELUMA_tex(HOOKED_pos).x - comp_gaussian_y(), 0.0), 0.0, 0.0, 0.0);
}
//!DESC Anime4K-v3.2-Darken-DoG-(VeryFast)-Gaussian-X
//!HOOK MAIN
//!BIND HOOKED
//!BIND LINEKERNEL
//!SAVE LINEKERNEL
//!WIDTH HOOKED.w 4 /
//!HEIGHT HOOKED.h 4 /
//!COMPONENTS 1
#define SPATIAL_SIGMA (0.25 * float(HOOKED_size.y) / 1080.0) //Spatial window size, must be a positive real number.
#define KERNELSIZE (max(int(ceil(SPATIAL_SIGMA * 2.0)), 1) * 2 + 1) //Kernel size, must be an positive odd integer.
#define KERNELHALFSIZE (int(KERNELSIZE/2)) //Half of the kernel size without remainder. Must be equal to trunc(KERNELSIZE/2).
#define KERNELLEN (KERNELSIZE * KERNELSIZE) //Total area of kernel. Must be equal to KERNELSIZE * KERNELSIZE.
float gaussian(float x, float s, float m) {
float scaled = (x - m) / s;
return exp(-0.5 * scaled * scaled);
}
float comp_gaussian_x() {
float g = 0.0;
float gn = 0.0;
for (int i=0; i<KERNELSIZE; i++) {
float di = float(i - KERNELHALFSIZE);
float gf = gaussian(di, SPATIAL_SIGMA, 0.0);
g = g + LINEKERNEL_texOff(vec2(di, 0.0)).x * gf;
gn = gn + gf;
}
return g / gn;
}
vec4 hook() {
return vec4(comp_gaussian_x(), 0.0, 0.0, 0.0);
}
//!DESC Anime4K-v3.2-Darken-DoG-(VeryFast)-Gaussian-Y
//!HOOK MAIN
//!BIND HOOKED
//!BIND LINEKERNEL
//!SAVE LINEKERNEL
//!WIDTH HOOKED.w 4 /
//!HEIGHT HOOKED.h 4 /
//!COMPONENTS 1
#define SPATIAL_SIGMA (0.25 * float(HOOKED_size.y) / 1080.0) //Spatial window size, must be a positive real number.
#define KERNELSIZE (max(int(ceil(SPATIAL_SIGMA * 2.0)), 1) * 2 + 1) //Kernel size, must be an positive odd integer.
#define KERNELHALFSIZE (int(KERNELSIZE/2)) //Half of the kernel size without remainder. Must be equal to trunc(KERNELSIZE/2).
#define KERNELLEN (KERNELSIZE * KERNELSIZE) //Total area of kernel. Must be equal to KERNELSIZE * KERNELSIZE.
float gaussian(float x, float s, float m) {
float scaled = (x - m) / s;
return exp(-0.5 * scaled * scaled);
}
float comp_gaussian_y() {
float g = 0.0;
float gn = 0.0;
for (int i=0; i<KERNELSIZE; i++) {
float di = float(i - KERNELHALFSIZE);
float gf = gaussian(di, SPATIAL_SIGMA, 0.0);
g = g + LINEKERNEL_texOff(vec2(0.0, di)).x * gf;
gn = gn + gf;
}
return g / gn;
}
vec4 hook() {
return vec4(comp_gaussian_y(), 0.0, 0.0, 0.0);
}
//!DESC Anime4K-v3.2-Darken-DoG-(VeryFast)-Upsample
//!HOOK MAIN
//!BIND HOOKED
//!BIND LINEKERNEL
#define STRENGTH 1.5 //Line darken proportional strength, higher is darker.
vec4 hook() {
//This trick is only possible if the inverse Y->RGB matrix has 1 for every row... (which is the case for BT.709)
//Otherwise we would need to convert RGB to YUV, modify Y then convert back to RGB.
return HOOKED_tex(HOOKED_pos) + (LINEKERNEL_tex(HOOKED_pos).x * STRENGTH);
}
// MIT License// Copyright (c) 2019-2021 bloc97// All rights reserved.// Permission is hereby granted, free of charge, to any person obtaining a copy// of this software and associated documentation files (the "Software"), to deal// in the Software without restriction, including without limitation the rights// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell// copies of the Software, and to permit persons to whom the Software is// furnished to do so, subject to the following conditions:// The above copyright notice and this permission notice shall be included in all// copies or substantial portions of the Software.// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE// SOFTWARE.//!DESC Anime4K-v3.2-Darken-DoG-(HQ)-Luma//!HOOK MAIN//!BIND HOOKED//!SAVE LINELUMA//!WIDTH HOOKED.w 2 ///!HEIGHT HOOKED.h 2 ///!COMPONENTS 1float get_luma(vec4 rgba) { return dot(vec4(0.299, 0.587, 0.114, 0.0), rgba);}vec4 hook() { return vec4(get_luma(HOOKED_tex(HOOKED_pos)), 0.0, 0.0, 0.0);}//!DESC Anime4K-v3.2-Darken-DoG-(VeryFast)-Gaussian-X//!HOOK MAIN//!BIND HOOKED//!BIND LINELUMA//!SAVE LINEKERNEL//!WIDTH HOOKED.w 4 ///!HEIGHT HOOKED.h 4 ///!COMPONENTS 1#define SPATIAL_SIGMA (0.5 * float(HOOKED_size.y) / 1080.0) //Spatial window size, must be a positive real number.#define KERNELSIZE (max(int(ceil(SPATIAL_SIGMA * 2.0)), 1) * 2 + 1) //Kernel size, must be an positive odd integer.#define KERNELHALFSIZE (int(KERNELSIZE/2)) //Half of the kernel size without remainder. Must be equal to trunc(KERNELSIZE/2).#define KERNELLEN (KERNELSIZE * KERNELSIZE) //Total area of kernel. Must be equal to KERNELSIZE * KERNELSIZE.float gaussian(float x, float s, float m) { float scaled = (x - m) / s; return exp(-0.5 * scaled * scaled);}float comp_gaussian_x() { float g = 0.0; float gn = 0.0; for (int i=0; i<KERNELSIZE; i++) { float di = float(i - KERNELHALFSIZE); float gf = gaussian(di, SPATIAL_SIGMA, 0.0); g = g + LINELUMA_texOff(vec2(di, 0.0)).x * gf; gn = gn + gf; } return g / gn;}vec4 hook() { return vec4(comp_gaussian_x(), 0.0, 0.0, 0.0);}//!DESC Anime4K-v3.2-Darken-DoG-(VeryFast)-Gaussian-Y//!HOOK MAIN//!BIND HOOKED//!BIND LINELUMA//!BIND LINEKERNEL//!SAVE LINEKERNEL//!WIDTH HOOKED.w 4 ///!HEIGHT HOOKED.h 4 ///!COMPONENTS 1#define SPATIAL_SIGMA (0.25 * float(HOOKED_size.y) / 1080.0) //Spatial window size, must be a positive real number.#define KERNELSIZE (max(int(ceil(SPATIAL_SIGMA * 2.0)), 1) * 2 + 1) //Kernel size, must be an positive odd integer.#define KERNELHALFSIZE (int(KERNELSIZE/2)) //Half of the kernel size without remainder. Must be equal to trunc(KERNELSIZE/2).#define KERNELLEN (KERNELSIZE * KERNELSIZE) //Total area of kernel. Must be equal to KERNELSIZE * KERNELSIZE.float gaussian(float x, float s, float m) { float scaled = (x - m) / s; return exp(-0.5 * scaled * scaled);}float comp_gaussian_y() { float g = 0.0; float gn = 0.0; for (int i=0; i<KERNELSIZE; i++) { float di = float(i - KERNELHALFSIZE); float gf = gaussian(di, SPATIAL_SIGMA, 0.0); g = g + LINEKERNEL_texOff(vec2(0.0, di)).x * gf; gn = gn + gf; } return g / gn;}vec4 hook() { return vec4(min(LINELUMA_tex(HOOKED_pos).x - comp_gaussian_y(), 0.0), 0.0, 0.0, 0.0);}//!DESC Anime4K-v3.2-Darken-DoG-(VeryFast)-Gaussian-X//!HOOK MAIN//!BIND HOOKED//!BIND LINEKERNEL//!SAVE LINEKERNEL//!WIDTH HOOKED.w 4 ///!HEIGHT HOOKED.h 4 ///!COMPONENTS 1#define SPATIAL_SIGMA (0.25 * float(HOOKED_size.y) / 1080.0) //Spatial window size, must be a positive real number.#define KERNELSIZE (max(int(ceil(SPATIAL_SIGMA * 2.0)), 1) * 2 + 1) //Kernel size, must be an positive odd integer.#define KERNELHALFSIZE (int(KERNELSIZE/2)) //Half of the kernel size without remainder. Must be equal to trunc(KERNELSIZE/2).#define KERNELLEN (KERNELSIZE * KERNELSIZE) //Total area of kernel. Must be equal to KERNELSIZE * KERNELSIZE.float gaussian(float x, float s, float m) { float scaled = (x - m) / s; return exp(-0.5 * scaled * scaled);}float comp_gaussian_x() { float g = 0.0; float gn = 0.0; for (int i=0; i<KERNELSIZE; i++) { float di = float(i - KERNELHALFSIZE); float gf = gaussian(di, SPATIAL_SIGMA, 0.0); g = g + LINEKERNEL_texOff(vec2(di, 0.0)).x * gf; gn = gn + gf; } return g / gn;}vec4 hook() { return vec4(comp_gaussian_x(), 0.0, 0.0, 0.0);}//!DESC Anime4K-v3.2-Darken-DoG-(VeryFast)-Gaussian-Y//!HOOK MAIN//!BIND HOOKED//!BIND LINEKERNEL//!SAVE LINEKERNEL//!WIDTH HOOKED.w 4 ///!HEIGHT HOOKED.h 4 ///!COMPONENTS 1#define SPATIAL_SIGMA (0.25 * float(HOOKED_size.y) / 1080.0) //Spatial window size, must be a positive real number.#define KERNELSIZE (max(int(ceil(SPATIAL_SIGMA * 2.0)), 1) * 2 + 1) //Kernel size, must be an positive odd integer.#define KERNELHALFSIZE (int(KERNELSIZE/2)) //Half of the kernel size without remainder. Must be equal to trunc(KERNELSIZE/2).#define KERNELLEN (KERNELSIZE * KERNELSIZE) //Total area of kernel. Must be equal to KERNELSIZE * KERNELSIZE.float gaussian(float x, float s, float m) { float scaled = (x - m) / s; return exp(-0.5 * scaled * scaled);}float comp_gaussian_y() { float g = 0.0; float gn = 0.0; for (int i=0; i<KERNELSIZE; i++) { float di = float(i - KERNELHALFSIZE); float gf = gaussian(di, SPATIAL_SIGMA, 0.0); g = g + LINEKERNEL_texOff(vec2(0.0, di)).x * gf; gn = gn + gf; } return g / gn;}vec4 hook() { return vec4(comp_gaussian_y(), 0.0, 0.0, 0.0);}//!DESC Anime4K-v3.2-Darken-DoG-(VeryFast)-Upsample//!HOOK MAIN//!BIND HOOKED//!BIND LINEKERNEL#define STRENGTH 1.5 //Line darken proportional strength, higher is darker.vec4 hook() { //This trick is only possible if the inverse Y->RGB matrix has 1 for every row... (which is the case for BT.709) //Otherwise we would need to convert RGB to YUV, modify Y then convert back to RGB. return HOOKED_tex(HOOKED_pos) + (LINEKERNEL_tex(HOOKED_pos).x * STRENGTH);}mpv/shaders/Anime4K_Deblur_DoG.glsl
Modified+153 / −153 text lines
// MIT License
// Copyright (c) 2019-2021 bloc97
// All rights reserved.
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//!DESC Anime4K-v3.2-Deblur-DoG-(HQ)-Luma
//!HOOK MAIN
//!BIND HOOKED
//!SAVE LINELUMA
//!COMPONENTS 1
float get_luma(vec4 rgba) {
return dot(vec4(0.299, 0.587, 0.114, 0.0), rgba);
}
vec4 hook() {
return vec4(get_luma(HOOKED_tex(HOOKED_pos)), 0.0, 0.0, 0.0);
}
//!DESC Anime4K-v3.2-Deblur-DoG-Kernel-X
//!HOOK MAIN
//!BIND HOOKED
//!BIND LINELUMA
//!SAVE MMKERNEL
//!COMPONENTS 3
#define L_tex LINELUMA_tex
float max3v(float a, float b, float c) {
return max(max(a, b), c);
}
float min3v(float a, float b, float c) {
return min(min(a, b), c);
}
vec2 minmax3(vec2 pos, vec2 d) {
float a = L_tex(pos - d).x;
float b = L_tex(pos).x;
float c = L_tex(pos + d).x;
return vec2(min3v(a, b, c), max3v(a, b, c));
}
float lumGaussian7(vec2 pos, vec2 d) {
float g = (L_tex(pos - (d + d)).x + L_tex(pos + (d + d)).x) * 0.06136;
g = g + (L_tex(pos - d).x + L_tex(pos + d).x) * 0.24477;
g = g + (L_tex(pos).x) * 0.38774;
return g;
}
vec4 hook() {
return vec4(lumGaussian7(HOOKED_pos, vec2(HOOKED_pt.x, 0.0)), minmax3(HOOKED_pos, vec2(HOOKED_pt.x, 0.0)), 0.0);
}
//!DESC Anime4K-v3.2-Deblur-DoG-Kernel-Y
//!HOOK MAIN
//!BIND HOOKED
//!BIND MMKERNEL
//!SAVE MMKERNEL
//!COMPONENTS 3
#define L_tex MMKERNEL_tex
float max3v(float a, float b, float c) {
return max(max(a, b), c);
}
float min3v(float a, float b, float c) {
return min(min(a, b), c);
}
vec2 minmax3(vec2 pos, vec2 d) {
float a0 = L_tex(pos - d).y;
float b0 = L_tex(pos).y;
float c0 = L_tex(pos + d).y;
float a1 = L_tex(pos - d).z;
float b1 = L_tex(pos).z;
float c1 = L_tex(pos + d).z;
return vec2(min3v(a0, b0, c0), max3v(a1, b1, c1));
}
float lumGaussian7(vec2 pos, vec2 d) {
float g = (L_tex(pos - (d + d)).x + L_tex(pos + (d + d)).x) * 0.06136;
g = g + (L_tex(pos - d).x + L_tex(pos + d).x) * 0.24477;
g = g + (L_tex(pos).x) * 0.38774;
return g;
}
vec4 hook() {
return vec4(lumGaussian7(HOOKED_pos, vec2(0.0, HOOKED_pt.y)), minmax3(HOOKED_pos, vec2(0.0, HOOKED_pt.y)), 0.0);
}
//!DESC Anime4K-v3.2-Deblur-DoG-Apply
//!HOOK MAIN
//!BIND HOOKED
//!BIND LINELUMA
//!BIND MMKERNEL
#define STRENGTH 0.6 //De-blur proportional strength, higher is sharper. However, it is better to tweak BLUR_CURVE instead to avoid ringing.
#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;
#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.
#define NOISE_THRESHOLD 0.001 //Value where curve stops, used to not sharpen noise. Only de-blur values that fall above this threshold.
#define L_tex LINELUMA_tex
vec4 hook() {
float c = (L_tex(HOOKED_pos).x - MMKERNEL_tex(HOOKED_pos).x) * STRENGTH;
float t_range = BLUR_THRESHOLD - NOISE_THRESHOLD;
float c_t = abs(c);
if (c_t > NOISE_THRESHOLD) {
c_t = (c_t - NOISE_THRESHOLD) / t_range;
c_t = pow(c_t, BLUR_CURVE);
c_t = c_t * t_range + NOISE_THRESHOLD;
c_t = c_t * sign(c);
} else {
c_t = c;
}
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;
//This trick is only possible if the inverse Y->RGB matrix has 1 for every row... (which is the case for BT.709)
//Otherwise we would need to convert RGB to YUV, modify Y then convert back to RGB.
return HOOKED_tex(HOOKED_pos) + cc;
}
// MIT License// Copyright (c) 2019-2021 bloc97// All rights reserved.// Permission is hereby granted, free of charge, to any person obtaining a copy// of this software and associated documentation files (the "Software"), to deal// in the Software without restriction, including without limitation the rights// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell// copies of the Software, and to permit persons to whom the Software is// furnished to do so, subject to the following conditions:// The above copyright notice and this permission notice shall be included in all// copies or substantial portions of the Software.// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE// SOFTWARE.//!DESC Anime4K-v3.2-Deblur-DoG-(HQ)-Luma//!HOOK MAIN//!BIND HOOKED//!SAVE LINELUMA//!COMPONENTS 1float get_luma(vec4 rgba) { return dot(vec4(0.299, 0.587, 0.114, 0.0), rgba);}vec4 hook() { return vec4(get_luma(HOOKED_tex(HOOKED_pos)), 0.0, 0.0, 0.0);}//!DESC Anime4K-v3.2-Deblur-DoG-Kernel-X//!HOOK MAIN//!BIND HOOKED//!BIND LINELUMA//!SAVE MMKERNEL//!COMPONENTS 3#define L_tex LINELUMA_texfloat max3v(float a, float b, float c) { return max(max(a, b), c);}float min3v(float a, float b, float c) { return min(min(a, b), c);}vec2 minmax3(vec2 pos, vec2 d) { float a = L_tex(pos - d).x; float b = L_tex(pos).x; float c = L_tex(pos + d).x; return vec2(min3v(a, b, c), max3v(a, b, c));}float lumGaussian7(vec2 pos, vec2 d) { float g = (L_tex(pos - (d + d)).x + L_tex(pos + (d + d)).x) * 0.06136; g = g + (L_tex(pos - d).x + L_tex(pos + d).x) * 0.24477; g = g + (L_tex(pos).x) * 0.38774; return g;}vec4 hook() { return vec4(lumGaussian7(HOOKED_pos, vec2(HOOKED_pt.x, 0.0)), minmax3(HOOKED_pos, vec2(HOOKED_pt.x, 0.0)), 0.0);}//!DESC Anime4K-v3.2-Deblur-DoG-Kernel-Y//!HOOK MAIN//!BIND HOOKED//!BIND MMKERNEL//!SAVE MMKERNEL//!COMPONENTS 3#define L_tex MMKERNEL_texfloat max3v(float a, float b, float c) { return max(max(a, b), c);}float min3v(float a, float b, float c) { return min(min(a, b), c);}vec2 minmax3(vec2 pos, vec2 d) { float a0 = L_tex(pos - d).y; float b0 = L_tex(pos).y; float c0 = L_tex(pos + d).y; float a1 = L_tex(pos - d).z; float b1 = L_tex(pos).z; float c1 = L_tex(pos + d).z; return vec2(min3v(a0, b0, c0), max3v(a1, b1, c1));}float lumGaussian7(vec2 pos, vec2 d) { float g = (L_tex(pos - (d + d)).x + L_tex(pos + (d + d)).x) * 0.06136; g = g + (L_tex(pos - d).x + L_tex(pos + d).x) * 0.24477; g = g + (L_tex(pos).x) * 0.38774; return g;}vec4 hook() { return vec4(lumGaussian7(HOOKED_pos, vec2(0.0, HOOKED_pt.y)), minmax3(HOOKED_pos, vec2(0.0, HOOKED_pt.y)), 0.0);}//!DESC Anime4K-v3.2-Deblur-DoG-Apply//!HOOK MAIN//!BIND HOOKED//!BIND LINELUMA//!BIND MMKERNEL#define STRENGTH 0.6 //De-blur proportional strength, higher is sharper. However, it is better to tweak BLUR_CURVE instead to avoid ringing.#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;#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.#define NOISE_THRESHOLD 0.001 //Value where curve stops, used to not sharpen noise. Only de-blur values that fall above this threshold.#define L_tex LINELUMA_texvec4 hook() { float c = (L_tex(HOOKED_pos).x - MMKERNEL_tex(HOOKED_pos).x) * STRENGTH; float t_range = BLUR_THRESHOLD - NOISE_THRESHOLD; float c_t = abs(c); if (c_t > NOISE_THRESHOLD) { c_t = (c_t - NOISE_THRESHOLD) / t_range; c_t = pow(c_t, BLUR_CURVE); c_t = c_t * t_range + NOISE_THRESHOLD; c_t = c_t * sign(c); } else { c_t = c; } 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; //This trick is only possible if the inverse Y->RGB matrix has 1 for every row... (which is the case for BT.709) //Otherwise we would need to convert RGB to YUV, modify Y then convert back to RGB. return HOOKED_tex(HOOKED_pos) + cc;}mpv/shaders/Anime4K_Deblur_Original.glsl
Modified+286 / −286 text lines
// MIT License
// Copyright (c) 2019-2021 bloc97
// All rights reserved.
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//!DESC Anime4K-v3.2-Deblur-Original-Luma
//!HOOK MAIN
//!BIND HOOKED
//!SAVE LINELUMA
//!COMPONENTS 1
float get_luma(vec4 rgba) {
return dot(vec4(0.299, 0.587, 0.114, 0.0), rgba);
}
vec4 hook() {
return vec4(get_luma(HOOKED_tex(HOOKED_pos)), 0.0, 0.0, 0.0);
}
//!DESC Anime4K-v3.2-Deblur-Original-Kernel-X
//!HOOK MAIN
//!BIND HOOKED
//!BIND LINELUMA
//!SAVE LUMAD
//!WIDTH MAIN.w 2 *
//!HEIGHT MAIN.h 2 *
//!COMPONENTS 2
vec4 hook() {
vec2 d = HOOKED_pt;
//[tl t tr]
//[ l c r]
//[bl b br]
float l = LINELUMA_tex(HOOKED_pos + vec2(-d.x, 0.0)).x;
float c = LINELUMA_tex(HOOKED_pos).x;
float r = LINELUMA_tex(HOOKED_pos + vec2(d.x, 0.0)).x;
//Horizontal Gradient
//[-1 0 1]
//[-2 0 2]
//[-1 0 1]
float xgrad = (-l + r);
//Vertical Gradient
//[-1 -2 -1]
//[ 0 0 0]
//[ 1 2 1]
float ygrad = (l + c + c + r);
//Computes the luminance's gradient
return vec4(xgrad, ygrad, 0.0, 0.0);
}
//!DESC Anime4K-v3.2-Deblur-Original-Kernel-Y
//!HOOK MAIN
//!BIND HOOKED
//!BIND LUMAD
//!SAVE LUMAD
//!WIDTH MAIN.w 2 *
//!HEIGHT MAIN.h 2 *
//!COMPONENTS 2
/* --------------------- SETTINGS --------------------- */
//Strength of edge refinement, good values are between 0.2 and 4
#define REFINE_STRENGTH 1.0
/* --- MODIFY THESE SETTINGS BELOW AT YOUR OWN RISK --- */
//Bias of the refinement function, good values are between 0 and 1
#define REFINE_BIAS 0.0
//Polynomial fit obtained by minimizing MSE error on image
#define P5 ( 11.68129591)
#define P4 (-42.46906057)
#define P3 ( 60.28286266)
#define P2 (-41.84451327)
#define P1 ( 14.05517353)
#define P0 (-1.081521930)
/* ----------------- END OF SETTINGS ----------------- */
float power_function(float x) {
float x2 = x * x;
float x3 = x2 * x;
float x4 = x2 * x2;
float x5 = x2 * x3;
return P5*x5 + P4*x4 + P3*x3 + P2*x2 + P1*x + P0;
}
vec4 hook() {
vec2 d = HOOKED_pt;
//[tl t tr]
//[ l cc r]
//[bl b br]
float tx = LUMAD_tex(HOOKED_pos + vec2(0.0, -d.y)).x;
float cx = LUMAD_tex(HOOKED_pos).x;
float bx = LUMAD_tex(HOOKED_pos + vec2(0.0, d.y)).x;
float ty = LUMAD_tex(HOOKED_pos + vec2(0.0, -d.y)).y;
//float cy = LUMAD_tex(HOOKED_pos).y;
float by = LUMAD_tex(HOOKED_pos + vec2(0.0, d.y)).y;
//Horizontal Gradient
//[-1 0 1]
//[-2 0 2]
//[-1 0 1]
float xgrad = (tx + cx + cx + bx);
//Vertical Gradient
//[-1 -2 -1]
//[ 0 0 0]
//[ 1 2 1]
float ygrad = (-ty + by);
//Computes the luminance's gradient
float sobel_norm = clamp(sqrt(xgrad * xgrad + ygrad * ygrad), 0.0, 1.0);
float dval = clamp(power_function(clamp(sobel_norm, 0.0, 1.0)) * REFINE_STRENGTH + REFINE_BIAS, 0.0, 1.0);
return vec4(sobel_norm, dval, 0.0, 0.0);
}
//!DESC Anime4K-v3.2-Deblur-Original-Kernel-X
//!HOOK MAIN
//!BIND HOOKED
//!BIND LUMAD
//!SAVE LUMAMM
//!WIDTH MAIN.w 2 *
//!HEIGHT MAIN.h 2 *
//!COMPONENTS 2
vec4 hook() {
vec2 d = HOOKED_pt;
if (LUMAD_tex(HOOKED_pos).y < 0.1) {
return vec4(0.0);
}
//[tl t tr]
//[ l c r]
//[bl b br]
float l = LUMAD_tex(HOOKED_pos + vec2(-d.x, 0.0)).x;
float c = LUMAD_tex(HOOKED_pos).x;
float r = LUMAD_tex(HOOKED_pos + vec2(d.x, 0.0)).x;
//Horizontal Gradient
//[-1 0 1]
//[-2 0 2]
//[-1 0 1]
float xgrad = (-l + r);
//Vertical Gradient
//[-1 -2 -1]
//[ 0 0 0]
//[ 1 2 1]
float ygrad = (l + c + c + r);
return vec4(xgrad, ygrad, 0.0, 0.0);
}
//!DESC Anime4K-v3.2-Deblur-Original-Kernel-Y
//!HOOK MAIN
//!BIND HOOKED
//!BIND LUMAD
//!BIND LUMAMM
//!SAVE LUMAMM
//!WIDTH MAIN.w 2 *
//!HEIGHT MAIN.h 2 *
//!COMPONENTS 2
vec4 hook() {
vec2 d = HOOKED_pt;
if (LUMAD_tex(HOOKED_pos).y < 0.1) {
return vec4(0.0);
}
//[tl t tr]
//[ l cc r]
//[bl b br]
float tx = LUMAMM_tex(HOOKED_pos + vec2(0.0, -d.y)).x;
float cx = LUMAMM_tex(HOOKED_pos).x;
float bx = LUMAMM_tex(HOOKED_pos + vec2(0.0, d.y)).x;
float ty = LUMAMM_tex(HOOKED_pos + vec2(0.0, -d.y)).y;
//float cy = LUMAMM_tex(HOOKED_pos).y;
float by = LUMAMM_tex(HOOKED_pos + vec2(0.0, d.y)).y;
//Horizontal Gradient
//[-1 0 1]
//[-2 0 2]
//[-1 0 1]
float xgrad = (tx + cx + cx + bx);
//Vertical Gradient
//[-1 -2 -1]
//[ 0 0 0]
//[ 1 2 1]
float ygrad = (-ty + by);
float norm = sqrt(xgrad * xgrad + ygrad * ygrad);
if (norm <= 0.001) {
xgrad = 0.0;
ygrad = 0.0;
norm = 1.0;
}
return vec4(xgrad/norm, ygrad/norm, 0.0, 0.0);
}
//!DESC Anime4K-v3.2-Deblur-Original-Apply
//!HOOK MAIN
//!BIND HOOKED
//!BIND LUMAD
//!BIND LUMAMM
//!WIDTH MAIN.w 2 *
//!HEIGHT MAIN.h 2 *
//!SAVE RESAMPLED
vec4 hook() {
vec2 d = HOOKED_pt;
float dval = LUMAD_tex(HOOKED_pos).y;
if (dval < 0.1) {
return HOOKED_tex(HOOKED_pos);
}
vec4 dc = LUMAMM_tex(HOOKED_pos);
if (abs(dc.x + dc.y) <= 0.0001) {
return HOOKED_tex(HOOKED_pos);
}
float xpos = -sign(dc.x);
float ypos = -sign(dc.y);
vec4 xval = HOOKED_tex(HOOKED_pos + vec2(d.x * xpos, 0.0));
vec4 yval = HOOKED_tex(HOOKED_pos + vec2(0.0, d.y * ypos));
float xyratio = abs(dc.x) / (abs(dc.x) + abs(dc.y));
vec4 avg = xyratio * xval + (1.0 - xyratio) * yval;
return avg * dval + HOOKED_tex(HOOKED_pos) * (1.0 - dval);
}
//!DESC Anime4K-v3.2-Deblur-Original-Resample
//!HOOK MAIN
//!BIND HOOKED
//!BIND RESAMPLED
vec4 hook() {
return RESAMPLED_tex(HOOKED_pos);
// MIT License// Copyright (c) 2019-2021 bloc97// All rights reserved.// Permission is hereby granted, free of charge, to any person obtaining a copy// of this software and associated documentation files (the "Software"), to deal// in the Software without restriction, including without limitation the rights// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell// copies of the Software, and to permit persons to whom the Software is// furnished to do so, subject to the following conditions:// The above copyright notice and this permission notice shall be included in all// copies or substantial portions of the Software.// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE// SOFTWARE.//!DESC Anime4K-v3.2-Deblur-Original-Luma//!HOOK MAIN//!BIND HOOKED//!SAVE LINELUMA//!COMPONENTS 1float get_luma(vec4 rgba) { return dot(vec4(0.299, 0.587, 0.114, 0.0), rgba);}vec4 hook() { return vec4(get_luma(HOOKED_tex(HOOKED_pos)), 0.0, 0.0, 0.0);}//!DESC Anime4K-v3.2-Deblur-Original-Kernel-X//!HOOK MAIN//!BIND HOOKED//!BIND LINELUMA//!SAVE LUMAD//!WIDTH MAIN.w 2 *//!HEIGHT MAIN.h 2 *//!COMPONENTS 2vec4 hook() { vec2 d = HOOKED_pt; //[tl t tr] //[ l c r] //[bl b br] float l = LINELUMA_tex(HOOKED_pos + vec2(-d.x, 0.0)).x; float c = LINELUMA_tex(HOOKED_pos).x; float r = LINELUMA_tex(HOOKED_pos + vec2(d.x, 0.0)).x; //Horizontal Gradient //[-1 0 1] //[-2 0 2] //[-1 0 1] float xgrad = (-l + r); //Vertical Gradient //[-1 -2 -1] //[ 0 0 0] //[ 1 2 1] float ygrad = (l + c + c + r); //Computes the luminance's gradient return vec4(xgrad, ygrad, 0.0, 0.0);}//!DESC Anime4K-v3.2-Deblur-Original-Kernel-Y//!HOOK MAIN//!BIND HOOKED//!BIND LUMAD//!SAVE LUMAD//!WIDTH MAIN.w 2 *//!HEIGHT MAIN.h 2 *//!COMPONENTS 2/* --------------------- SETTINGS --------------------- *///Strength of edge refinement, good values are between 0.2 and 4#define REFINE_STRENGTH 1.0/* --- MODIFY THESE SETTINGS BELOW AT YOUR OWN RISK --- *///Bias of the refinement function, good values are between 0 and 1#define REFINE_BIAS 0.0//Polynomial fit obtained by minimizing MSE error on image#define P5 ( 11.68129591)#define P4 (-42.46906057)#define P3 ( 60.28286266)#define P2 (-41.84451327)#define P1 ( 14.05517353)#define P0 (-1.081521930)/* ----------------- END OF SETTINGS ----------------- */float power_function(float x) { float x2 = x * x; float x3 = x2 * x; float x4 = x2 * x2; float x5 = x2 * x3; return P5*x5 + P4*x4 + P3*x3 + P2*x2 + P1*x + P0;}vec4 hook() { vec2 d = HOOKED_pt; //[tl t tr] //[ l cc r] //[bl b br] float tx = LUMAD_tex(HOOKED_pos + vec2(0.0, -d.y)).x; float cx = LUMAD_tex(HOOKED_pos).x; float bx = LUMAD_tex(HOOKED_pos + vec2(0.0, d.y)).x; float ty = LUMAD_tex(HOOKED_pos + vec2(0.0, -d.y)).y; //float cy = LUMAD_tex(HOOKED_pos).y; float by = LUMAD_tex(HOOKED_pos + vec2(0.0, d.y)).y; //Horizontal Gradient //[-1 0 1] //[-2 0 2] //[-1 0 1] float xgrad = (tx + cx + cx + bx); //Vertical Gradient //[-1 -2 -1] //[ 0 0 0] //[ 1 2 1] float ygrad = (-ty + by); //Computes the luminance's gradient float sobel_norm = clamp(sqrt(xgrad * xgrad + ygrad * ygrad), 0.0, 1.0); float dval = clamp(power_function(clamp(sobel_norm, 0.0, 1.0)) * REFINE_STRENGTH + REFINE_BIAS, 0.0, 1.0); return vec4(sobel_norm, dval, 0.0, 0.0);}//!DESC Anime4K-v3.2-Deblur-Original-Kernel-X//!HOOK MAIN//!BIND HOOKED//!BIND LUMAD//!SAVE LUMAMM//!WIDTH MAIN.w 2 *//!HEIGHT MAIN.h 2 *//!COMPONENTS 2vec4 hook() { vec2 d = HOOKED_pt; if (LUMAD_tex(HOOKED_pos).y < 0.1) { return vec4(0.0); } //[tl t tr] //[ l c r] //[bl b br] float l = LUMAD_tex(HOOKED_pos + vec2(-d.x, 0.0)).x; float c = LUMAD_tex(HOOKED_pos).x; float r = LUMAD_tex(HOOKED_pos + vec2(d.x, 0.0)).x; //Horizontal Gradient //[-1 0 1] //[-2 0 2] //[-1 0 1] float xgrad = (-l + r); //Vertical Gradient //[-1 -2 -1] //[ 0 0 0] //[ 1 2 1] float ygrad = (l + c + c + r); return vec4(xgrad, ygrad, 0.0, 0.0);}//!DESC Anime4K-v3.2-Deblur-Original-Kernel-Y//!HOOK MAIN//!BIND HOOKED//!BIND LUMAD//!BIND LUMAMM//!SAVE LUMAMM//!WIDTH MAIN.w 2 *//!HEIGHT MAIN.h 2 *//!COMPONENTS 2vec4 hook() { vec2 d = HOOKED_pt; if (LUMAD_tex(HOOKED_pos).y < 0.1) { return vec4(0.0); } //[tl t tr] //[ l cc r] //[bl b br] float tx = LUMAMM_tex(HOOKED_pos + vec2(0.0, -d.y)).x; float cx = LUMAMM_tex(HOOKED_pos).x; float bx = LUMAMM_tex(HOOKED_pos + vec2(0.0, d.y)).x; float ty = LUMAMM_tex(HOOKED_pos + vec2(0.0, -d.y)).y; //float cy = LUMAMM_tex(HOOKED_pos).y; float by = LUMAMM_tex(HOOKED_pos + vec2(0.0, d.y)).y; //Horizontal Gradient //[-1 0 1] //[-2 0 2] //[-1 0 1] float xgrad = (tx + cx + cx + bx); //Vertical Gradient //[-1 -2 -1] //[ 0 0 0] //[ 1 2 1] float ygrad = (-ty + by); float norm = sqrt(xgrad * xgrad + ygrad * ygrad); if (norm <= 0.001) { xgrad = 0.0; ygrad = 0.0; norm = 1.0; } return vec4(xgrad/norm, ygrad/norm, 0.0, 0.0);}//!DESC Anime4K-v3.2-Deblur-Original-Apply//!HOOK MAIN//!BIND HOOKED//!BIND LUMAD//!BIND LUMAMM//!WIDTH MAIN.w 2 *//!HEIGHT MAIN.h 2 *//!SAVE RESAMPLEDvec4 hook() { vec2 d = HOOKED_pt; float dval = LUMAD_tex(HOOKED_pos).y; if (dval < 0.1) { return HOOKED_tex(HOOKED_pos); } vec4 dc = LUMAMM_tex(HOOKED_pos); if (abs(dc.x + dc.y) <= 0.0001) { return HOOKED_tex(HOOKED_pos); } float xpos = -sign(dc.x); float ypos = -sign(dc.y); vec4 xval = HOOKED_tex(HOOKED_pos + vec2(d.x * xpos, 0.0)); vec4 yval = HOOKED_tex(HOOKED_pos + vec2(0.0, d.y * ypos)); float xyratio = abs(dc.x) / (abs(dc.x) + abs(dc.y)); vec4 avg = xyratio * xval + (1.0 - xyratio) * yval; return avg * dval + HOOKED_tex(HOOKED_pos) * (1.0 - dval);}//!DESC Anime4K-v3.2-Deblur-Original-Resample//!HOOK MAIN//!BIND HOOKED//!BIND RESAMPLEDvec4 hook() { return RESAMPLED_tex(HOOKED_pos);mpv/shaders/Anime4K_Denoise_Bilateral_Mean.glsl
Modified+66 / −66 text lines
// MIT License
// Copyright (c) 2019-2021 bloc97
// All rights reserved.
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//!DESC Anime4K-v3.2-Denoise-Bilateral-Mean
//!HOOK MAIN
//!BIND HOOKED
#define INTENSITY_SIGMA 0.1 //Intensity window size, higher is stronger denoise, must be a positive real number
#define SPATIAL_SIGMA 1.0 //Spatial window size, higher is stronger denoise, must be a positive real number.
#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.
#define KERNELSIZE (max(int(ceil(SPATIAL_SIGMA * 2.0)), 1) * 2 + 1) //Kernel size, must be an positive odd integer.
#define KERNELHALFSIZE (int(KERNELSIZE/2)) //Half of the kernel size without remainder. Must be equal to trunc(KERNELSIZE/2).
#define KERNELLEN (KERNELSIZE * KERNELSIZE) //Total area of kernel. Must be equal to KERNELSIZE * KERNELSIZE.
#define GETOFFSET(i) vec2((i % KERNELSIZE) - KERNELHALFSIZE, (i / KERNELSIZE) - KERNELHALFSIZE)
vec4 gaussian_vec(vec4 x, vec4 s, vec4 m) {
vec4 scaled = (x - m) / s;
return exp(-0.5 * scaled * scaled);
}
float gaussian(float x, float s, float m) {
float scaled = (x - m) / s;
return exp(-0.5 * scaled * scaled);
}
vec4 hook() {
vec4 sum = vec4(0.0);
vec4 n = vec4(0.0);
vec4 vc = HOOKED_tex(HOOKED_pos);
vec4 is = pow(vc + 0.0001, vec4(INTENSITY_POWER_CURVE)) * INTENSITY_SIGMA;
float ss = SPATIAL_SIGMA;
for (int i=0; i<KERNELLEN; i++) {
vec2 ipos = GETOFFSET(i);
vec4 v = HOOKED_texOff(ipos);
vec4 d = gaussian_vec(v, is, vc) * gaussian(length(ipos), ss, 0.0);
sum += d * v;
n += d;
}
return sum / n;
// MIT License// Copyright (c) 2019-2021 bloc97// All rights reserved.// Permission is hereby granted, free of charge, to any person obtaining a copy// of this software and associated documentation files (the "Software"), to deal// in the Software without restriction, including without limitation the rights// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell// copies of the Software, and to permit persons to whom the Software is// furnished to do so, subject to the following conditions:// The above copyright notice and this permission notice shall be included in all// copies or substantial portions of the Software.// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE// SOFTWARE.//!DESC Anime4K-v3.2-Denoise-Bilateral-Mean//!HOOK MAIN//!BIND HOOKED#define INTENSITY_SIGMA 0.1 //Intensity window size, higher is stronger denoise, must be a positive real number#define SPATIAL_SIGMA 1.0 //Spatial window size, higher is stronger denoise, must be a positive real number.#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.#define KERNELSIZE (max(int(ceil(SPATIAL_SIGMA * 2.0)), 1) * 2 + 1) //Kernel size, must be an positive odd integer.#define KERNELHALFSIZE (int(KERNELSIZE/2)) //Half of the kernel size without remainder. Must be equal to trunc(KERNELSIZE/2).#define KERNELLEN (KERNELSIZE * KERNELSIZE) //Total area of kernel. Must be equal to KERNELSIZE * KERNELSIZE.#define GETOFFSET(i) vec2((i % KERNELSIZE) - KERNELHALFSIZE, (i / KERNELSIZE) - KERNELHALFSIZE)vec4 gaussian_vec(vec4 x, vec4 s, vec4 m) { vec4 scaled = (x - m) / s; return exp(-0.5 * scaled * scaled);}float gaussian(float x, float s, float m) { float scaled = (x - m) / s; return exp(-0.5 * scaled * scaled);}vec4 hook() { vec4 sum = vec4(0.0); vec4 n = vec4(0.0); vec4 vc = HOOKED_tex(HOOKED_pos); vec4 is = pow(vc + 0.0001, vec4(INTENSITY_POWER_CURVE)) * INTENSITY_SIGMA; float ss = SPATIAL_SIGMA; for (int i=0; i<KERNELLEN; i++) { vec2 ipos = GETOFFSET(i); vec4 v = HOOKED_texOff(ipos); vec4 d = gaussian_vec(v, is, vc) * gaussian(length(ipos), ss, 0.0); sum += d * v; n += d; } return sum / n;mpv/shaders/Anime4K_Denoise_Bilateral_Median.glsl
Modified+119 / −119 text lines
// MIT License
// Copyright (c) 2019-2021 bloc97
// All rights reserved.
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//!DESC Anime4K-v3.2-Denoise-Bilateral-Median-Luma
//!HOOK MAIN
//!BIND HOOKED
//!SAVE LINELUMA
//!COMPONENTS 1
float get_luma(vec4 rgba) {
return dot(vec4(0.299, 0.587, 0.114, 0.0), rgba);
}
vec4 hook() {
return vec4(get_luma(HOOKED_tex(HOOKED_pos)), 0.0, 0.0, 0.0);
}
//!DESC Anime4K-v3.2-Denoise-Bilateral-Median-Apply
//!HOOK MAIN
//!BIND HOOKED
//!BIND LINELUMA
#define INTENSITY_SIGMA 0.1 //Intensity window size, higher is stronger denoise, must be a positive real number
#define SPATIAL_SIGMA 1.0 //Spatial window size, higher is stronger denoise, must be a positive real number.
#define HISTOGRAM_REGULARIZATION 0.0 //Histogram regularization window size, higher values approximate a bilateral "closest-to-mean" filter.
#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.
#define KERNELSIZE int(max(int(SPATIAL_SIGMA), 1) * 2 + 1) //Kernel size, must be an positive odd integer.
#define KERNELHALFSIZE (int(KERNELSIZE/2)) //Half of the kernel size without remainder. Must be equal to trunc(KERNELSIZE/2).
#define KERNELLEN (KERNELSIZE * KERNELSIZE) //Total area of kernel. Must be equal to KERNELSIZE * KERNELSIZE.
#define GETOFFSET(i) vec2((i % KERNELSIZE) - KERNELHALFSIZE, (i / KERNELSIZE) - KERNELHALFSIZE)
float gaussian(float x, float s, float m) {
float scaled = (x - m) / s;
return exp(-0.5 * scaled * scaled);
}
vec4 getMedian(vec4 v[KERNELLEN], float w[KERNELLEN], float n) {
for (int i=0; i<KERNELLEN; i++) {
float w_above = 0.0;
float w_below = 0.0;
for (int j=0; j<KERNELLEN; j++) {
if (v[j].x > v[i].x) {
w_above += w[j];
} else if (v[j].x < v[i].x) {
w_below += w[j];
}
}
if ((n - w_above) / n >= 0.5 && w_below / n <= 0.5) {
return v[i];
}
}
}
vec4 hook() {
vec4 histogram_v[KERNELLEN];
float histogram_l[KERNELLEN];
float histogram_w[KERNELLEN];
float n = 0.0;
float vc = LINELUMA_tex(HOOKED_pos).x;
float is = pow(vc + 0.0001, INTENSITY_POWER_CURVE) * INTENSITY_SIGMA;
float ss = SPATIAL_SIGMA;
for (int i=0; i<KERNELLEN; i++) {
vec2 ipos = GETOFFSET(i);
histogram_v[i] = HOOKED_texOff(ipos);
histogram_l[i] = LINELUMA_texOff(ipos).x;
histogram_w[i] = gaussian(histogram_l[i], is, vc) * gaussian(length(ipos), ss, 0.0);
n += histogram_w[i];
}
if (HISTOGRAM_REGULARIZATION > 0.0) {
float histogram_wn[KERNELLEN];
n = 0.0;
for (int i=0; i<KERNELLEN; i++) {
histogram_wn[i] = 0.0;
}
for (int i=0; i<KERNELLEN; i++) {
histogram_wn[i] += gaussian(0.0, HISTOGRAM_REGULARIZATION, 0.0) * histogram_w[i];
for (int j=(i+1); j<KERNELLEN; j++) {
float d = gaussian(histogram_l[j], HISTOGRAM_REGULARIZATION, histogram_l[i]);
histogram_wn[j] += d * histogram_w[i];
histogram_wn[i] += d * histogram_w[j];
}
n += histogram_wn[i];
}
return getMedian(histogram_v, histogram_wn, n);
}
return getMedian(histogram_v, histogram_w, n);
// MIT License// Copyright (c) 2019-2021 bloc97// All rights reserved.// Permission is hereby granted, free of charge, to any person obtaining a copy// of this software and associated documentation files (the "Software"), to deal// in the Software without restriction, including without limitation the rights// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell// copies of the Software, and to permit persons to whom the Software is// furnished to do so, subject to the following conditions:// The above copyright notice and this permission notice shall be included in all// copies or substantial portions of the Software.// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE// SOFTWARE.//!DESC Anime4K-v3.2-Denoise-Bilateral-Median-Luma//!HOOK MAIN//!BIND HOOKED//!SAVE LINELUMA//!COMPONENTS 1float get_luma(vec4 rgba) { return dot(vec4(0.299, 0.587, 0.114, 0.0), rgba);}vec4 hook() { return vec4(get_luma(HOOKED_tex(HOOKED_pos)), 0.0, 0.0, 0.0);}//!DESC Anime4K-v3.2-Denoise-Bilateral-Median-Apply//!HOOK MAIN//!BIND HOOKED//!BIND LINELUMA#define INTENSITY_SIGMA 0.1 //Intensity window size, higher is stronger denoise, must be a positive real number#define SPATIAL_SIGMA 1.0 //Spatial window size, higher is stronger denoise, must be a positive real number.#define HISTOGRAM_REGULARIZATION 0.0 //Histogram regularization window size, higher values approximate a bilateral "closest-to-mean" filter.#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.#define KERNELSIZE int(max(int(SPATIAL_SIGMA), 1) * 2 + 1) //Kernel size, must be an positive odd integer.#define KERNELHALFSIZE (int(KERNELSIZE/2)) //Half of the kernel size without remainder. Must be equal to trunc(KERNELSIZE/2).#define KERNELLEN (KERNELSIZE * KERNELSIZE) //Total area of kernel. Must be equal to KERNELSIZE * KERNELSIZE.#define GETOFFSET(i) vec2((i % KERNELSIZE) - KERNELHALFSIZE, (i / KERNELSIZE) - KERNELHALFSIZE)float gaussian(float x, float s, float m) { float scaled = (x - m) / s; return exp(-0.5 * scaled * scaled);}vec4 getMedian(vec4 v[KERNELLEN], float w[KERNELLEN], float n) { for (int i=0; i<KERNELLEN; i++) { float w_above = 0.0; float w_below = 0.0; for (int j=0; j<KERNELLEN; j++) { if (v[j].x > v[i].x) { w_above += w[j]; } else if (v[j].x < v[i].x) { w_below += w[j]; } } if ((n - w_above) / n >= 0.5 && w_below / n <= 0.5) { return v[i]; } }}vec4 hook() { vec4 histogram_v[KERNELLEN]; float histogram_l[KERNELLEN]; float histogram_w[KERNELLEN]; float n = 0.0; float vc = LINELUMA_tex(HOOKED_pos).x; float is = pow(vc + 0.0001, INTENSITY_POWER_CURVE) * INTENSITY_SIGMA; float ss = SPATIAL_SIGMA; for (int i=0; i<KERNELLEN; i++) { vec2 ipos = GETOFFSET(i); histogram_v[i] = HOOKED_texOff(ipos); histogram_l[i] = LINELUMA_texOff(ipos).x; histogram_w[i] = gaussian(histogram_l[i], is, vc) * gaussian(length(ipos), ss, 0.0); n += histogram_w[i]; } if (HISTOGRAM_REGULARIZATION > 0.0) { float histogram_wn[KERNELLEN]; n = 0.0; for (int i=0; i<KERNELLEN; i++) { histogram_wn[i] = 0.0; } for (int i=0; i<KERNELLEN; i++) { histogram_wn[i] += gaussian(0.0, HISTOGRAM_REGULARIZATION, 0.0) * histogram_w[i]; for (int j=(i+1); j<KERNELLEN; j++) { float d = gaussian(histogram_l[j], HISTOGRAM_REGULARIZATION, histogram_l[i]); histogram_wn[j] += d * histogram_w[i]; histogram_wn[i] += d * histogram_w[j]; } n += histogram_wn[i]; } return getMedian(histogram_v, histogram_wn, n); } return getMedian(histogram_v, histogram_w, n);mpv/shaders/Anime4K_Denoise_Bilateral_Mode.glsl
Modified+102 / −102 text lines
// MIT License
// Copyright (c) 2019-2021 bloc97
// All rights reserved.
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//!DESC Anime4K-v3.2-Denoise-Bilateral-Mode-Luma
//!HOOK MAIN
//!BIND HOOKED
//!SAVE LINELUMA
//!COMPONENTS 1
float get_luma(vec4 rgba) {
return dot(vec4(0.299, 0.587, 0.114, 0.0), rgba);
}
vec4 hook() {
return vec4(get_luma(HOOKED_tex(HOOKED_pos)), 0.0, 0.0, 0.0);
}
//!DESC Anime4K-v3.1-Denoise-Bilateral-Mode-Apply
//!HOOK MAIN
//!BIND HOOKED
//!BIND LINELUMA
#define INTENSITY_SIGMA 0.1 //Intensity window size, higher is stronger denoise, must be a positive real number
#define SPATIAL_SIGMA 1.0 //Spatial window size, higher is stronger denoise, must be a positive real number.
#define HISTOGRAM_REGULARIZATION 0.2 //Histogram regularization window size, higher values approximate a bilateral "closest-to-mean" filter.
#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.
#define KERNELSIZE int(max(int(SPATIAL_SIGMA), 1) * 2 + 1) //Kernel size, must be an positive odd integer.
#define KERNELHALFSIZE (int(KERNELSIZE/2)) //Half of the kernel size without remainder. Must be equal to trunc(KERNELSIZE/2).
#define KERNELLEN (KERNELSIZE * KERNELSIZE) //Total area of kernel. Must be equal to KERNELSIZE * KERNELSIZE.
#define GETOFFSET(i) vec2((i % KERNELSIZE) - KERNELHALFSIZE, (i / KERNELSIZE) - KERNELHALFSIZE)
float gaussian(float x, float s, float m) {
float scaled = (x - m) / s;
return exp(-0.5 * scaled * scaled);
}
vec4 getMode(vec4 v[KERNELLEN], float w[KERNELLEN]) {
vec4 maxv = vec4(0);
float maxw = 0.0;
for (int i=0; i<KERNELLEN; i++) {
if (w[i] >= maxw) {
maxw = w[i];
maxv = v[i];
}
}
return maxv;
}
vec4 hook() {
vec4 histogram_v[KERNELLEN];
float histogram_l[KERNELLEN];
float histogram_w[KERNELLEN];
float histogram_wn[KERNELLEN];
float vc = LINELUMA_tex(HOOKED_pos).x;
float is = pow(vc + 0.0001, INTENSITY_POWER_CURVE) * INTENSITY_SIGMA;
float ss = SPATIAL_SIGMA;
for (int i=0; i<KERNELLEN; i++) {
vec2 ipos = GETOFFSET(i);
histogram_v[i] = HOOKED_texOff(ipos);
histogram_l[i] = LINELUMA_texOff(ipos).x;
histogram_w[i] = gaussian(histogram_l[i], is, vc) * gaussian(length(ipos), ss, 0.0);
histogram_wn[i] = 0.0;
}
for (int i=0; i<KERNELLEN; i++) {
histogram_wn[i] += gaussian(0.0, HISTOGRAM_REGULARIZATION, 0.0) * histogram_w[i];
for (int j=(i+1); j<KERNELLEN; j++) {
float d = gaussian(histogram_l[j], HISTOGRAM_REGULARIZATION, histogram_l[i]);
histogram_wn[j] += d * histogram_w[i];
histogram_wn[i] += d * histogram_w[j];
}
}
return getMode(histogram_v, histogram_wn);
// MIT License// Copyright (c) 2019-2021 bloc97// All rights reserved.// Permission is hereby granted, free of charge, to any person obtaining a copy// of this software and associated documentation files (the "Software"), to deal// in the Software without restriction, including without limitation the rights// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell// copies of the Software, and to permit persons to whom the Software is// furnished to do so, subject to the following conditions:// The above copyright notice and this permission notice shall be included in all// copies or substantial portions of the Software.// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE// SOFTWARE.//!DESC Anime4K-v3.2-Denoise-Bilateral-Mode-Luma//!HOOK MAIN//!BIND HOOKED//!SAVE LINELUMA//!COMPONENTS 1float get_luma(vec4 rgba) { return dot(vec4(0.299, 0.587, 0.114, 0.0), rgba);}vec4 hook() { return vec4(get_luma(HOOKED_tex(HOOKED_pos)), 0.0, 0.0, 0.0);}//!DESC Anime4K-v3.1-Denoise-Bilateral-Mode-Apply//!HOOK MAIN//!BIND HOOKED//!BIND LINELUMA#define INTENSITY_SIGMA 0.1 //Intensity window size, higher is stronger denoise, must be a positive real number#define SPATIAL_SIGMA 1.0 //Spatial window size, higher is stronger denoise, must be a positive real number.#define HISTOGRAM_REGULARIZATION 0.2 //Histogram regularization window size, higher values approximate a bilateral "closest-to-mean" filter.#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.#define KERNELSIZE int(max(int(SPATIAL_SIGMA), 1) * 2 + 1) //Kernel size, must be an positive odd integer.#define KERNELHALFSIZE (int(KERNELSIZE/2)) //Half of the kernel size without remainder. Must be equal to trunc(KERNELSIZE/2).#define KERNELLEN (KERNELSIZE * KERNELSIZE) //Total area of kernel. Must be equal to KERNELSIZE * KERNELSIZE.#define GETOFFSET(i) vec2((i % KERNELSIZE) - KERNELHALFSIZE, (i / KERNELSIZE) - KERNELHALFSIZE)float gaussian(float x, float s, float m) { float scaled = (x - m) / s; return exp(-0.5 * scaled * scaled);}vec4 getMode(vec4 v[KERNELLEN], float w[KERNELLEN]) { vec4 maxv = vec4(0); float maxw = 0.0; for (int i=0; i<KERNELLEN; i++) { if (w[i] >= maxw) { maxw = w[i]; maxv = v[i]; } } return maxv;}vec4 hook() { vec4 histogram_v[KERNELLEN]; float histogram_l[KERNELLEN]; float histogram_w[KERNELLEN]; float histogram_wn[KERNELLEN]; float vc = LINELUMA_tex(HOOKED_pos).x; float is = pow(vc + 0.0001, INTENSITY_POWER_CURVE) * INTENSITY_SIGMA; float ss = SPATIAL_SIGMA; for (int i=0; i<KERNELLEN; i++) { vec2 ipos = GETOFFSET(i); histogram_v[i] = HOOKED_texOff(ipos); histogram_l[i] = LINELUMA_texOff(ipos).x; histogram_w[i] = gaussian(histogram_l[i], is, vc) * gaussian(length(ipos), ss, 0.0); histogram_wn[i] = 0.0; } for (int i=0; i<KERNELLEN; i++) { histogram_wn[i] += gaussian(0.0, HISTOGRAM_REGULARIZATION, 0.0) * histogram_w[i]; for (int j=(i+1); j<KERNELLEN; j++) { float d = gaussian(histogram_l[j], HISTOGRAM_REGULARIZATION, histogram_l[i]); histogram_wn[j] += d * histogram_w[i]; histogram_wn[i] += d * histogram_w[j]; } } return getMode(histogram_v, histogram_wn);mpv/shaders/Anime4K_Thin_Fast.glsl
Modified+234 / −234 text lines
// MIT License
// Copyright (c) 2019-2021 bloc97
// All rights reserved.
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//!DESC Anime4K-v3.2-Thin-(Fast)-Luma
//!HOOK MAIN
//!BIND HOOKED
//!SAVE LINELUMA
//!COMPONENTS 1
float get_luma(vec4 rgba) {
return dot(vec4(0.299, 0.587, 0.114, 0.0), rgba);
}
vec4 hook() {
return vec4(get_luma(HOOKED_tex(HOOKED_pos)), 0.0, 0.0, 0.0);
}
//!DESC Anime4K-v3.2-Thin-(Fast)-Sobel-X
//!HOOK MAIN
//!BIND LINELUMA
//!SAVE LINESOBEL
//!WIDTH HOOKED.w 2 /
//!HEIGHT HOOKED.h 2 /
//!COMPONENTS 2
vec4 hook() {
float l = LINELUMA_texOff(vec2(-1.0, 0.0)).x;
float c = LINELUMA_tex(LINELUMA_pos).x;
float r = LINELUMA_texOff(vec2(1.0, 0.0)).x;
float xgrad = (-l + r);
float ygrad = (l + c + c + r);
return vec4(xgrad, ygrad, 0.0, 0.0);
}
//!DESC Anime4K-v3.2-Thin-(Fast)-Sobel-Y
//!HOOK MAIN
//!BIND LINESOBEL
//!SAVE LINESOBEL
//!WIDTH HOOKED.w 2 /
//!HEIGHT HOOKED.h 2 /
//!COMPONENTS 1
vec4 hook() {
float tx = LINESOBEL_texOff(vec2(0.0, -0.5)).x;
float cx = LINESOBEL_tex(LINESOBEL_pos).x;
float bx = LINESOBEL_texOff(vec2(0.0, 0.5)).x;
float ty = LINESOBEL_texOff(vec2(0.0, -0.5)).y;
float by = LINESOBEL_texOff(vec2(0.0, 0.5)).y;
float xgrad = (tx + cx + cx + bx) / 8.0;
float ygrad = (-ty + by) / 8.0;
//Computes the luminance's gradient
float norm = sqrt(xgrad * xgrad + ygrad * ygrad);
return vec4(pow(norm, 0.7));
}
//!DESC Anime4K-v3.2-Thin-(Fast)-Gaussian-X
//!HOOK MAIN
//!BIND HOOKED
//!BIND LINESOBEL
//!SAVE LINESOBEL
//!WIDTH HOOKED.w 2 /
//!HEIGHT HOOKED.h 2 /
//!COMPONENTS 1
#define SPATIAL_SIGMA (1.0 * float(HOOKED_size.y) / 1080.0) //Spatial window size, must be a positive real number.
#define KERNELSIZE (max(int(ceil(SPATIAL_SIGMA * 2.0)), 1) * 2 + 1) //Kernel size, must be an positive odd integer.
#define KERNELHALFSIZE (int(KERNELSIZE/2)) //Half of the kernel size without remainder. Must be equal to trunc(KERNELSIZE/2).
#define KERNELLEN (KERNELSIZE * KERNELSIZE) //Total area of kernel. Must be equal to KERNELSIZE * KERNELSIZE.
float gaussian(float x, float s, float m) {
float scaled = (x - m) / s;
return exp(-0.5 * scaled * scaled);
}
float comp_gaussian_x() {
float g = 0.0;
float gn = 0.0;
for (int i=0; i<KERNELSIZE; i++) {
float di = float(i - KERNELHALFSIZE);
float gf = gaussian(di, SPATIAL_SIGMA, 0.0);
g = g + LINESOBEL_texOff(vec2(di, 0.0)).x * gf;
gn = gn + gf;
}
return g / gn;
}
vec4 hook() {
return vec4(comp_gaussian_x(), 0.0, 0.0, 0.0);
}
//!DESC Anime4K-v3.2-Thin-(Fast)-Gaussian-Y
//!HOOK MAIN
//!BIND HOOKED
//!BIND LINESOBEL
//!SAVE LINESOBEL
//!WIDTH HOOKED.w 2 /
//!HEIGHT HOOKED.h 2 /
//!COMPONENTS 1
#define SPATIAL_SIGMA (1.0 * float(HOOKED_size.y) / 1080.0) //Spatial window size, must be a positive real number.
#define KERNELSIZE (max(int(ceil(SPATIAL_SIGMA * 2.0)), 1) * 2 + 1) //Kernel size, must be an positive odd integer.
#define KERNELHALFSIZE (int(KERNELSIZE/2)) //Half of the kernel size without remainder. Must be equal to trunc(KERNELSIZE/2).
#define KERNELLEN (KERNELSIZE * KERNELSIZE) //Total area of kernel. Must be equal to KERNELSIZE * KERNELSIZE.
float gaussian(float x, float s, float m) {
float scaled = (x - m) / s;
return exp(-0.5 * scaled * scaled);
}
float comp_gaussian_y() {
float g = 0.0;
float gn = 0.0;
for (int i=0; i<KERNELSIZE; i++) {
float di = float(i - KERNELHALFSIZE);
float gf = gaussian(di, SPATIAL_SIGMA, 0.0);
g = g + LINESOBEL_texOff(vec2(0.0, di)).x * gf;
gn = gn + gf;
}
return g / gn;
}
vec4 hook() {
return vec4(comp_gaussian_y(), 0.0, 0.0, 0.0);
}
//!DESC Anime4K-v3.2-Thin-(Fast)-Kernel-X
//!HOOK MAIN
//!BIND LINESOBEL
//!SAVE LINESOBEL
//!WIDTH HOOKED.w 2 /
//!HEIGHT HOOKED.h 2 /
//!COMPONENTS 2
vec4 hook() {
float l = LINESOBEL_texOff(vec2(-0.5, 0.0)).x;
float c = LINESOBEL_tex(LINESOBEL_pos).x;
float r = LINESOBEL_texOff(vec2(0.5, 0.0)).x;
float xgrad = (-l + r);
float ygrad = (l + c + c + r);
return vec4(xgrad, ygrad, 0.0, 0.0);
}
//!DESC Anime4K-v3.2-Thin-(Fast)-Kernel-Y
//!HOOK MAIN
//!BIND LINESOBEL
//!SAVE LINESOBEL
//!WIDTH HOOKED.w 2 /
//!HEIGHT HOOKED.h 2 /
//!COMPONENTS 2
vec4 hook() {
float tx = LINESOBEL_texOff(vec2(0.0, -0.5)).x;
float cx = LINESOBEL_tex(LINESOBEL_pos).x;
float bx = LINESOBEL_texOff(vec2(0.0, 0.5)).x;
float ty = LINESOBEL_texOff(vec2(0.0, -0.5)).y;
float by = LINESOBEL_texOff(vec2(0.0, 0.5)).y;
float xgrad = (tx + cx + cx + bx) / 8.0;
float ygrad = (-ty + by) / 8.0;
//Computes the luminance's gradient
return vec4(xgrad, ygrad, 0.0, 0.0);
}
//!DESC Anime4K-v3.2-Thin-(Fast)-Warp
//!HOOK MAIN
//!BIND HOOKED
//!BIND LINESOBEL
#define STRENGTH 0.6 //Strength of warping for each iteration
#define ITERATIONS 1 //Number of iterations for the forwards solver, decreasing strength and increasing iterations improves quality at the cost of speed.
vec4 hook() {
vec2 d = HOOKED_pt;
float relstr = HOOKED_size.y / 1080.0 * STRENGTH;
vec2 pos = HOOKED_pos;
for (int i=0; i<ITERATIONS; i++) {
vec2 dn = LINESOBEL_tex(pos).xy;
vec2 dd = (dn / (length(dn) + 0.01)) * d * relstr; //Quasi-normalization for large vectors, avoids divide by zero
pos -= dd;
}
return HOOKED_tex(pos);
}
// MIT License// Copyright (c) 2019-2021 bloc97// All rights reserved.// Permission is hereby granted, free of charge, to any person obtaining a copy// of this software and associated documentation files (the "Software"), to deal// in the Software without restriction, including without limitation the rights// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell// copies of the Software, and to permit persons to whom the Software is// furnished to do so, subject to the following conditions:// The above copyright notice and this permission notice shall be included in all// copies or substantial portions of the Software.// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE// SOFTWARE.//!DESC Anime4K-v3.2-Thin-(Fast)-Luma//!HOOK MAIN//!BIND HOOKED//!SAVE LINELUMA//!COMPONENTS 1float get_luma(vec4 rgba) { return dot(vec4(0.299, 0.587, 0.114, 0.0), rgba);}vec4 hook() { return vec4(get_luma(HOOKED_tex(HOOKED_pos)), 0.0, 0.0, 0.0);}//!DESC Anime4K-v3.2-Thin-(Fast)-Sobel-X//!HOOK MAIN//!BIND LINELUMA//!SAVE LINESOBEL//!WIDTH HOOKED.w 2 ///!HEIGHT HOOKED.h 2 ///!COMPONENTS 2vec4 hook() { float l = LINELUMA_texOff(vec2(-1.0, 0.0)).x; float c = LINELUMA_tex(LINELUMA_pos).x; float r = LINELUMA_texOff(vec2(1.0, 0.0)).x; float xgrad = (-l + r); float ygrad = (l + c + c + r); return vec4(xgrad, ygrad, 0.0, 0.0);}//!DESC Anime4K-v3.2-Thin-(Fast)-Sobel-Y//!HOOK MAIN//!BIND LINESOBEL//!SAVE LINESOBEL//!WIDTH HOOKED.w 2 ///!HEIGHT HOOKED.h 2 ///!COMPONENTS 1vec4 hook() { float tx = LINESOBEL_texOff(vec2(0.0, -0.5)).x; float cx = LINESOBEL_tex(LINESOBEL_pos).x; float bx = LINESOBEL_texOff(vec2(0.0, 0.5)).x; float ty = LINESOBEL_texOff(vec2(0.0, -0.5)).y; float by = LINESOBEL_texOff(vec2(0.0, 0.5)).y; float xgrad = (tx + cx + cx + bx) / 8.0; float ygrad = (-ty + by) / 8.0; //Computes the luminance's gradient float norm = sqrt(xgrad * xgrad + ygrad * ygrad); return vec4(pow(norm, 0.7));}//!DESC Anime4K-v3.2-Thin-(Fast)-Gaussian-X//!HOOK MAIN//!BIND HOOKED//!BIND LINESOBEL//!SAVE LINESOBEL//!WIDTH HOOKED.w 2 ///!HEIGHT HOOKED.h 2 ///!COMPONENTS 1#define SPATIAL_SIGMA (1.0 * float(HOOKED_size.y) / 1080.0) //Spatial window size, must be a positive real number.#define KERNELSIZE (max(int(ceil(SPATIAL_SIGMA * 2.0)), 1) * 2 + 1) //Kernel size, must be an positive odd integer.#define KERNELHALFSIZE (int(KERNELSIZE/2)) //Half of the kernel size without remainder. Must be equal to trunc(KERNELSIZE/2).#define KERNELLEN (KERNELSIZE * KERNELSIZE) //Total area of kernel. Must be equal to KERNELSIZE * KERNELSIZE.float gaussian(float x, float s, float m) { float scaled = (x - m) / s; return exp(-0.5 * scaled * scaled);}float comp_gaussian_x() { float g = 0.0; float gn = 0.0; for (int i=0; i<KERNELSIZE; i++) { float di = float(i - KERNELHALFSIZE); float gf = gaussian(di, SPATIAL_SIGMA, 0.0); g = g + LINESOBEL_texOff(vec2(di, 0.0)).x * gf; gn = gn + gf; } return g / gn;}vec4 hook() { return vec4(comp_gaussian_x(), 0.0, 0.0, 0.0);}//!DESC Anime4K-v3.2-Thin-(Fast)-Gaussian-Y//!HOOK MAIN//!BIND HOOKED//!BIND LINESOBEL//!SAVE LINESOBEL//!WIDTH HOOKED.w 2 ///!HEIGHT HOOKED.h 2 ///!COMPONENTS 1#define SPATIAL_SIGMA (1.0 * float(HOOKED_size.y) / 1080.0) //Spatial window size, must be a positive real number.#define KERNELSIZE (max(int(ceil(SPATIAL_SIGMA * 2.0)), 1) * 2 + 1) //Kernel size, must be an positive odd integer.#define KERNELHALFSIZE (int(KERNELSIZE/2)) //Half of the kernel size without remainder. Must be equal to trunc(KERNELSIZE/2).#define KERNELLEN (KERNELSIZE * KERNELSIZE) //Total area of kernel. Must be equal to KERNELSIZE * KERNELSIZE.float gaussian(float x, float s, float m) { float scaled = (x - m) / s; return exp(-0.5 * scaled * scaled);}float comp_gaussian_y() { float g = 0.0; float gn = 0.0; for (int i=0; i<KERNELSIZE; i++) { float di = float(i - KERNELHALFSIZE); float gf = gaussian(di, SPATIAL_SIGMA, 0.0); g = g + LINESOBEL_texOff(vec2(0.0, di)).x * gf; gn = gn + gf; } return g / gn;}vec4 hook() { return vec4(comp_gaussian_y(), 0.0, 0.0, 0.0);}//!DESC Anime4K-v3.2-Thin-(Fast)-Kernel-X//!HOOK MAIN//!BIND LINESOBEL//!SAVE LINESOBEL//!WIDTH HOOKED.w 2 ///!HEIGHT HOOKED.h 2 ///!COMPONENTS 2vec4 hook() { float l = LINESOBEL_texOff(vec2(-0.5, 0.0)).x; float c = LINESOBEL_tex(LINESOBEL_pos).x; float r = LINESOBEL_texOff(vec2(0.5, 0.0)).x; float xgrad = (-l + r); float ygrad = (l + c + c + r); return vec4(xgrad, ygrad, 0.0, 0.0);}//!DESC Anime4K-v3.2-Thin-(Fast)-Kernel-Y//!HOOK MAIN//!BIND LINESOBEL//!SAVE LINESOBEL//!WIDTH HOOKED.w 2 ///!HEIGHT HOOKED.h 2 ///!COMPONENTS 2vec4 hook() { float tx = LINESOBEL_texOff(vec2(0.0, -0.5)).x; float cx = LINESOBEL_tex(LINESOBEL_pos).x; float bx = LINESOBEL_texOff(vec2(0.0, 0.5)).x; float ty = LINESOBEL_texOff(vec2(0.0, -0.5)).y; float by = LINESOBEL_texOff(vec2(0.0, 0.5)).y; float xgrad = (tx + cx + cx + bx) / 8.0; float ygrad = (-ty + by) / 8.0; //Computes the luminance's gradient return vec4(xgrad, ygrad, 0.0, 0.0);}//!DESC Anime4K-v3.2-Thin-(Fast)-Warp//!HOOK MAIN//!BIND HOOKED//!BIND LINESOBEL#define STRENGTH 0.6 //Strength of warping for each iteration#define ITERATIONS 1 //Number of iterations for the forwards solver, decreasing strength and increasing iterations improves quality at the cost of speed.vec4 hook() { vec2 d = HOOKED_pt; float relstr = HOOKED_size.y / 1080.0 * STRENGTH; vec2 pos = HOOKED_pos; for (int i=0; i<ITERATIONS; i++) { vec2 dn = LINESOBEL_tex(pos).xy; vec2 dd = (dn / (length(dn) + 0.01)) * d * relstr; //Quasi-normalization for large vectors, avoids divide by zero pos -= dd; } return HOOKED_tex(pos);}mpv/shaders/Anime4K_Thin_HQ.glsl
Modified+222 / −222 text lines
// MIT License
// Copyright (c) 2019-2021 bloc97
// All rights reserved.
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//!DESC Anime4K-v3.2-Thin-(HQ)-Luma
//!HOOK MAIN
//!BIND HOOKED
//!SAVE LINELUMA
//!COMPONENTS 1
float get_luma(vec4 rgba) {
return dot(vec4(0.299, 0.587, 0.114, 0.0), rgba);
}
vec4 hook() {
return vec4(get_luma(HOOKED_tex(HOOKED_pos)), 0.0, 0.0, 0.0);
}
//!DESC Anime4K-v3.2-Thin-(HQ)-Sobel-X
//!HOOK MAIN
//!BIND LINELUMA
//!SAVE LINESOBEL
//!COMPONENTS 2
vec4 hook() {
float l = LINELUMA_texOff(vec2(-1.0, 0.0)).x;
float c = LINELUMA_tex(LINELUMA_pos).x;
float r = LINELUMA_texOff(vec2(1.0, 0.0)).x;
float xgrad = (-l + r);
float ygrad = (l + c + c + r);
return vec4(xgrad, ygrad, 0.0, 0.0);
}
//!DESC Anime4K-v3.2-Thin-(HQ)-Sobel-Y
//!HOOK MAIN
//!BIND LINESOBEL
//!SAVE LINESOBEL
//!COMPONENTS 1
vec4 hook() {
float tx = LINESOBEL_texOff(vec2(0.0, -1.0)).x;
float cx = LINESOBEL_tex(LINESOBEL_pos).x;
float bx = LINESOBEL_texOff(vec2(0.0, 1.0)).x;
float ty = LINESOBEL_texOff(vec2(0.0, -1.0)).y;
float by = LINESOBEL_texOff(vec2(0.0, 1.0)).y;
float xgrad = (tx + cx + cx + bx) / 8.0;
float ygrad = (-ty + by) / 8.0;
//Computes the luminance's gradient
float norm = sqrt(xgrad * xgrad + ygrad * ygrad);
return vec4(pow(norm, 0.7));
}
//!DESC Anime4K-v3.2-Thin-(HQ)-Gaussian-X
//!HOOK MAIN
//!BIND HOOKED
//!BIND LINESOBEL
//!SAVE LINESOBEL
//!COMPONENTS 1
#define SPATIAL_SIGMA (2.0 * float(HOOKED_size.y) / 1080.0) //Spatial window size, must be a positive real number.
#define KERNELSIZE (max(int(ceil(SPATIAL_SIGMA * 2.0)), 1) * 2 + 1) //Kernel size, must be an positive odd integer.
#define KERNELHALFSIZE (int(KERNELSIZE/2)) //Half of the kernel size without remainder. Must be equal to trunc(KERNELSIZE/2).
#define KERNELLEN (KERNELSIZE * KERNELSIZE) //Total area of kernel. Must be equal to KERNELSIZE * KERNELSIZE.
float gaussian(float x, float s, float m) {
float scaled = (x - m) / s;
return exp(-0.5 * scaled * scaled);
}
float comp_gaussian_x() {
float g = 0.0;
float gn = 0.0;
for (int i=0; i<KERNELSIZE; i++) {
float di = float(i - KERNELHALFSIZE);
float gf = gaussian(di, SPATIAL_SIGMA, 0.0);
g = g + LINESOBEL_texOff(vec2(di, 0.0)).x * gf;
gn = gn + gf;
}
return g / gn;
}
vec4 hook() {
return vec4(comp_gaussian_x(), 0.0, 0.0, 0.0);
}
//!DESC Anime4K-v3.2-Thin-(HQ)-Gaussian-Y
//!HOOK MAIN
//!BIND HOOKED
//!BIND LINESOBEL
//!SAVE LINESOBEL
//!COMPONENTS 1
#define SPATIAL_SIGMA (2.0 * float(HOOKED_size.y) / 1080.0) //Spatial window size, must be a positive real number.
#define KERNELSIZE (max(int(ceil(SPATIAL_SIGMA * 2.0)), 1) * 2 + 1) //Kernel size, must be an positive odd integer.
#define KERNELHALFSIZE (int(KERNELSIZE/2)) //Half of the kernel size without remainder. Must be equal to trunc(KERNELSIZE/2).
#define KERNELLEN (KERNELSIZE * KERNELSIZE) //Total area of kernel. Must be equal to KERNELSIZE * KERNELSIZE.
float gaussian(float x, float s, float m) {
float scaled = (x - m) / s;
return exp(-0.5 * scaled * scaled);
}
float comp_gaussian_y() {
float g = 0.0;
float gn = 0.0;
for (int i=0; i<KERNELSIZE; i++) {
float di = float(i - KERNELHALFSIZE);
float gf = gaussian(di, SPATIAL_SIGMA, 0.0);
g = g + LINESOBEL_texOff(vec2(0.0, di)).x * gf;
gn = gn + gf;
}
return g / gn;
}
vec4 hook() {
return vec4(comp_gaussian_y(), 0.0, 0.0, 0.0);
}
//!DESC Anime4K-v3.2-Thin-(HQ)-Kernel-X
//!HOOK MAIN
//!BIND LINESOBEL
//!SAVE LINESOBEL
//!COMPONENTS 2
vec4 hook() {
float l = LINESOBEL_texOff(vec2(-1.0, 0.0)).x;
float c = LINESOBEL_tex(LINESOBEL_pos).x;
float r = LINESOBEL_texOff(vec2(1.0, 0.0)).x;
float xgrad = (-l + r);
float ygrad = (l + c + c + r);
return vec4(xgrad, ygrad, 0.0, 0.0);
}
//!DESC Anime4K-v3.2-Thin-(HQ)-Kernel-Y
//!HOOK MAIN
//!BIND LINESOBEL
//!SAVE LINESOBEL
//!COMPONENTS 2
vec4 hook() {
float tx = LINESOBEL_texOff(vec2(0.0, -1.0)).x;
float cx = LINESOBEL_tex(LINESOBEL_pos).x;
float bx = LINESOBEL_texOff(vec2(0.0, 1.0)).x;
float ty = LINESOBEL_texOff(vec2(0.0, -1.0)).y;
float by = LINESOBEL_texOff(vec2(0.0, 1.0)).y;
float xgrad = (tx + cx + cx + bx) / 8.0;
float ygrad = (-ty + by) / 8.0;
//Computes the luminance's gradient
return vec4(xgrad, ygrad, 0.0, 0.0);
}
//!DESC Anime4K-v3.2-Thin-(HQ)-Warp
//!HOOK MAIN
//!BIND HOOKED
//!BIND LINESOBEL
#define STRENGTH 0.6 //Strength of warping for each iteration
#define ITERATIONS 1 //Number of iterations for the forwards solver, decreasing strength and increasing iterations improves quality at the cost of speed.
vec4 hook() {
vec2 d = HOOKED_pt;
float relstr = HOOKED_size.y / 1080.0 * STRENGTH;
vec2 pos = HOOKED_pos;
for (int i=0; i<ITERATIONS; i++) {
vec2 dn = LINESOBEL_tex(pos).xy;
vec2 dd = (dn / (length(dn) + 0.01)) * d * relstr; //Quasi-normalization for large vectors, avoids divide by zero
pos -= dd;
}
return HOOKED_tex(pos);
}
// MIT License// Copyright (c) 2019-2021 bloc97// All rights reserved.// Permission is hereby granted, free of charge, to any person obtaining a copy// of this software and associated documentation files (the "Software"), to deal// in the Software without restriction, including without limitation the rights// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell// copies of the Software, and to permit persons to whom the Software is// furnished to do so, subject to the following conditions:// The above copyright notice and this permission notice shall be included in all// copies or substantial portions of the Software.// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE// SOFTWARE.//!DESC Anime4K-v3.2-Thin-(HQ)-Luma//!HOOK MAIN//!BIND HOOKED//!SAVE LINELUMA//!COMPONENTS 1float get_luma(vec4 rgba) { return dot(vec4(0.299, 0.587, 0.114, 0.0), rgba);}vec4 hook() { return vec4(get_luma(HOOKED_tex(HOOKED_pos)), 0.0, 0.0, 0.0);}//!DESC Anime4K-v3.2-Thin-(HQ)-Sobel-X//!HOOK MAIN//!BIND LINELUMA//!SAVE LINESOBEL//!COMPONENTS 2vec4 hook() { float l = LINELUMA_texOff(vec2(-1.0, 0.0)).x; float c = LINELUMA_tex(LINELUMA_pos).x; float r = LINELUMA_texOff(vec2(1.0, 0.0)).x; float xgrad = (-l + r); float ygrad = (l + c + c + r); return vec4(xgrad, ygrad, 0.0, 0.0);}//!DESC Anime4K-v3.2-Thin-(HQ)-Sobel-Y//!HOOK MAIN//!BIND LINESOBEL//!SAVE LINESOBEL//!COMPONENTS 1vec4 hook() { float tx = LINESOBEL_texOff(vec2(0.0, -1.0)).x; float cx = LINESOBEL_tex(LINESOBEL_pos).x; float bx = LINESOBEL_texOff(vec2(0.0, 1.0)).x; float ty = LINESOBEL_texOff(vec2(0.0, -1.0)).y; float by = LINESOBEL_texOff(vec2(0.0, 1.0)).y; float xgrad = (tx + cx + cx + bx) / 8.0; float ygrad = (-ty + by) / 8.0; //Computes the luminance's gradient float norm = sqrt(xgrad * xgrad + ygrad * ygrad); return vec4(pow(norm, 0.7));}//!DESC Anime4K-v3.2-Thin-(HQ)-Gaussian-X//!HOOK MAIN//!BIND HOOKED//!BIND LINESOBEL//!SAVE LINESOBEL//!COMPONENTS 1#define SPATIAL_SIGMA (2.0 * float(HOOKED_size.y) / 1080.0) //Spatial window size, must be a positive real number.#define KERNELSIZE (max(int(ceil(SPATIAL_SIGMA * 2.0)), 1) * 2 + 1) //Kernel size, must be an positive odd integer.#define KERNELHALFSIZE (int(KERNELSIZE/2)) //Half of the kernel size without remainder. Must be equal to trunc(KERNELSIZE/2).#define KERNELLEN (KERNELSIZE * KERNELSIZE) //Total area of kernel. Must be equal to KERNELSIZE * KERNELSIZE.float gaussian(float x, float s, float m) { float scaled = (x - m) / s; return exp(-0.5 * scaled * scaled);}float comp_gaussian_x() { float g = 0.0; float gn = 0.0; for (int i=0; i<KERNELSIZE; i++) { float di = float(i - KERNELHALFSIZE); float gf = gaussian(di, SPATIAL_SIGMA, 0.0); g = g + LINESOBEL_texOff(vec2(di, 0.0)).x * gf; gn = gn + gf; } return g / gn;}vec4 hook() { return vec4(comp_gaussian_x(), 0.0, 0.0, 0.0);}//!DESC Anime4K-v3.2-Thin-(HQ)-Gaussian-Y//!HOOK MAIN//!BIND HOOKED//!BIND LINESOBEL//!SAVE LINESOBEL//!COMPONENTS 1#define SPATIAL_SIGMA (2.0 * float(HOOKED_size.y) / 1080.0) //Spatial window size, must be a positive real number.#define KERNELSIZE (max(int(ceil(SPATIAL_SIGMA * 2.0)), 1) * 2 + 1) //Kernel size, must be an positive odd integer.#define KERNELHALFSIZE (int(KERNELSIZE/2)) //Half of the kernel size without remainder. Must be equal to trunc(KERNELSIZE/2).#define KERNELLEN (KERNELSIZE * KERNELSIZE) //Total area of kernel. Must be equal to KERNELSIZE * KERNELSIZE.float gaussian(float x, float s, float m) { float scaled = (x - m) / s; return exp(-0.5 * scaled * scaled);}float comp_gaussian_y() { float g = 0.0; float gn = 0.0; for (int i=0; i<KERNELSIZE; i++) { float di = float(i - KERNELHALFSIZE); float gf = gaussian(di, SPATIAL_SIGMA, 0.0); g = g + LINESOBEL_texOff(vec2(0.0, di)).x * gf; gn = gn + gf; } return g / gn;}vec4 hook() { return vec4(comp_gaussian_y(), 0.0, 0.0, 0.0);}//!DESC Anime4K-v3.2-Thin-(HQ)-Kernel-X//!HOOK MAIN//!BIND LINESOBEL//!SAVE LINESOBEL//!COMPONENTS 2vec4 hook() { float l = LINESOBEL_texOff(vec2(-1.0, 0.0)).x; float c = LINESOBEL_tex(LINESOBEL_pos).x; float r = LINESOBEL_texOff(vec2(1.0, 0.0)).x; float xgrad = (-l + r); float ygrad = (l + c + c + r); return vec4(xgrad, ygrad, 0.0, 0.0);}//!DESC Anime4K-v3.2-Thin-(HQ)-Kernel-Y//!HOOK MAIN//!BIND LINESOBEL//!SAVE LINESOBEL//!COMPONENTS 2vec4 hook() { float tx = LINESOBEL_texOff(vec2(0.0, -1.0)).x; float cx = LINESOBEL_tex(LINESOBEL_pos).x; float bx = LINESOBEL_texOff(vec2(0.0, 1.0)).x; float ty = LINESOBEL_texOff(vec2(0.0, -1.0)).y; float by = LINESOBEL_texOff(vec2(0.0, 1.0)).y; float xgrad = (tx + cx + cx + bx) / 8.0; float ygrad = (-ty + by) / 8.0; //Computes the luminance's gradient return vec4(xgrad, ygrad, 0.0, 0.0);}//!DESC Anime4K-v3.2-Thin-(HQ)-Warp//!HOOK MAIN//!BIND HOOKED//!BIND LINESOBEL#define STRENGTH 0.6 //Strength of warping for each iteration#define ITERATIONS 1 //Number of iterations for the forwards solver, decreasing strength and increasing iterations improves quality at the cost of speed.vec4 hook() { vec2 d = HOOKED_pt; float relstr = HOOKED_size.y / 1080.0 * STRENGTH; vec2 pos = HOOKED_pos; for (int i=0; i<ITERATIONS; i++) { vec2 dn = LINESOBEL_tex(pos).xy; vec2 dd = (dn / (length(dn) + 0.01)) * d * relstr; //Quasi-normalization for large vectors, avoids divide by zero pos -= dd; } return HOOKED_tex(pos);}mpv/shaders/Anime4K_Thin_VeryFast.glsl
Modified+236 / −236 text lines
// MIT License
// Copyright (c) 2019-2021 bloc97
// All rights reserved.
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//!DESC Anime4K-v3.2-Thin-(VeryFast)-Luma
//!HOOK MAIN
//!BIND HOOKED
//!SAVE LINELUMA
//!WIDTH HOOKED.w 2 /
//!HEIGHT HOOKED.h 2 /
//!COMPONENTS 1
float get_luma(vec4 rgba) {
return dot(vec4(0.299, 0.587, 0.114, 0.0), rgba);
}
vec4 hook() {
return vec4(get_luma(HOOKED_tex(HOOKED_pos)), 0.0, 0.0, 0.0);
}
//!DESC Anime4K-v3.2-Thin-(VeryFast)-Sobel-X
//!HOOK MAIN
//!BIND LINELUMA
//!SAVE LINESOBEL
//!WIDTH HOOKED.w 4 /
//!HEIGHT HOOKED.h 4 /
//!COMPONENTS 2
vec4 hook() {
float l = LINELUMA_texOff(vec2(-0.5, 0.0)).x;
float c = LINELUMA_tex(LINELUMA_pos).x;
float r = LINELUMA_texOff(vec2(0.5, 0.0)).x;
float xgrad = (-l + r);
float ygrad = (l + c + c + r);
return vec4(xgrad, ygrad, 0.0, 0.0);
}
//!DESC Anime4K-v3.2-Thin-(VeryFast)-Sobel-Y
//!HOOK MAIN
//!BIND LINESOBEL
//!SAVE LINESOBEL
//!WIDTH HOOKED.w 4 /
//!HEIGHT HOOKED.h 4 /
//!COMPONENTS 1
vec4 hook() {
float tx = LINESOBEL_texOff(vec2(0.0, -0.25)).x;
float cx = LINESOBEL_tex(LINESOBEL_pos).x;
float bx = LINESOBEL_texOff(vec2(0.0, 0.25)).x;
float ty = LINESOBEL_texOff(vec2(0.0, -0.25)).y;
float by = LINESOBEL_texOff(vec2(0.0, 0.25)).y;
float xgrad = (tx + cx + cx + bx) / 8.0;
float ygrad = (-ty + by) / 8.0;
//Computes the luminance's gradient
float norm = sqrt(xgrad * xgrad + ygrad * ygrad);
return vec4(pow(norm, 0.7));
}
//!DESC Anime4K-v3.2-Thin-(VeryFast)-Gaussian-X
//!HOOK MAIN
//!BIND HOOKED
//!BIND LINESOBEL
//!SAVE LINESOBEL
//!WIDTH HOOKED.w 4 /
//!HEIGHT HOOKED.h 4 /
//!COMPONENTS 1
#define SPATIAL_SIGMA (0.5 * float(HOOKED_size.y) / 1080.0) //Spatial window size, must be a positive real number.
#define KERNELSIZE (max(int(ceil(SPATIAL_SIGMA * 2.0)), 1) * 2 + 1) //Kernel size, must be an positive odd integer.
#define KERNELHALFSIZE (int(KERNELSIZE/2)) //Half of the kernel size without remainder. Must be equal to trunc(KERNELSIZE/2).
#define KERNELLEN (KERNELSIZE * KERNELSIZE) //Total area of kernel. Must be equal to KERNELSIZE * KERNELSIZE.
float gaussian(float x, float s, float m) {
float scaled = (x - m) / s;
return exp(-0.5 * scaled * scaled);
}
float comp_gaussian_x() {
float g = 0.0;
float gn = 0.0;
for (int i=0; i<KERNELSIZE; i++) {
float di = float(i - KERNELHALFSIZE);
float gf = gaussian(di, SPATIAL_SIGMA, 0.0);
g = g + LINESOBEL_texOff(vec2(di, 0.0)).x * gf;
gn = gn + gf;
}
return g / gn;
}
vec4 hook() {
return vec4(comp_gaussian_x(), 0.0, 0.0, 0.0);
}
//!DESC Anime4K-v3.2-Thin-(VeryFast)-Gaussian-Y
//!HOOK MAIN
//!BIND HOOKED
//!BIND LINESOBEL
//!SAVE LINESOBEL
//!WIDTH HOOKED.w 4 /
//!HEIGHT HOOKED.h 4 /
//!COMPONENTS 1
#define SPATIAL_SIGMA (0.5 * float(HOOKED_size.y) / 1080.0) //Spatial window size, must be a positive real number.
#define KERNELSIZE (max(int(ceil(SPATIAL_SIGMA * 2.0)), 1) * 2 + 1) //Kernel size, must be an positive odd integer.
#define KERNELHALFSIZE (int(KERNELSIZE/2)) //Half of the kernel size without remainder. Must be equal to trunc(KERNELSIZE/2).
#define KERNELLEN (KERNELSIZE * KERNELSIZE) //Total area of kernel. Must be equal to KERNELSIZE * KERNELSIZE.
float gaussian(float x, float s, float m) {
float scaled = (x - m) / s;
return exp(-0.5 * scaled * scaled);
}
float comp_gaussian_y() {
float g = 0.0;
float gn = 0.0;
for (int i=0; i<KERNELSIZE; i++) {
float di = float(i - KERNELHALFSIZE);
float gf = gaussian(di, SPATIAL_SIGMA, 0.0);
g = g + LINESOBEL_texOff(vec2(0.0, di)).x * gf;
gn = gn + gf;
}
return g / gn;
}
vec4 hook() {
return vec4(comp_gaussian_y(), 0.0, 0.0, 0.0);
}
//!DESC Anime4K-v3.2-Thin-(VeryFast)-Kernel-X
//!HOOK MAIN
//!BIND LINESOBEL
//!SAVE LINESOBEL
//!WIDTH HOOKED.w 4 /
//!HEIGHT HOOKED.h 4 /
//!COMPONENTS 2
vec4 hook() {
float l = LINESOBEL_texOff(vec2(-0.25, 0.0)).x;
float c = LINESOBEL_tex(LINESOBEL_pos).x;
float r = LINESOBEL_texOff(vec2(0.25, 0.0)).x;
float xgrad = (-l + r);
float ygrad = (l + c + c + r);
return vec4(xgrad, ygrad, 0.0, 0.0);
}
//!DESC Anime4K-v3.2-Thin-(VeryFast)-Kernel-Y
//!HOOK MAIN
//!BIND LINESOBEL
//!SAVE LINESOBEL
//!WIDTH HOOKED.w 4 /
//!HEIGHT HOOKED.h 4 /
//!COMPONENTS 2
vec4 hook() {
float tx = LINESOBEL_texOff(vec2(0.0, -0.25)).x;
float cx = LINESOBEL_tex(LINESOBEL_pos).x;
float bx = LINESOBEL_texOff(vec2(0.0, 0.25)).x;
float ty = LINESOBEL_texOff(vec2(0.0, -0.25)).y;
float by = LINESOBEL_texOff(vec2(0.0, 0.25)).y;
float xgrad = (tx + cx + cx + bx) / 8.0;
float ygrad = (-ty + by) / 8.0;
//Computes the luminance's gradient
return vec4(xgrad, ygrad, 0.0, 0.0);
}
//!DESC Anime4K-v3.2-Thin-(VeryFast)-Warp
//!HOOK MAIN
//!BIND HOOKED
//!BIND LINESOBEL
#define STRENGTH 0.6 //Strength of warping for each iteration
#define ITERATIONS 1 //Number of iterations for the forwards solver, decreasing strength and increasing iterations improves quality at the cost of speed.
vec4 hook() {
vec2 d = HOOKED_pt;
float relstr = HOOKED_size.y / 1080.0 * STRENGTH;
vec2 pos = HOOKED_pos;
for (int i=0; i<ITERATIONS; i++) {
vec2 dn = LINESOBEL_tex(pos).xy;
vec2 dd = (dn / (length(dn) + 0.01)) * d * relstr; //Quasi-normalization for large vectors, avoids divide by zero
pos -= dd;
}
return HOOKED_tex(pos);
}
// MIT License// Copyright (c) 2019-2021 bloc97// All rights reserved.// Permission is hereby granted, free of charge, to any person obtaining a copy// of this software and associated documentation files (the "Software"), to deal// in the Software without restriction, including without limitation the rights// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell// copies of the Software, and to permit persons to whom the Software is// furnished to do so, subject to the following conditions:// The above copyright notice and this permission notice shall be included in all// copies or substantial portions of the Software.// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE// SOFTWARE.//!DESC Anime4K-v3.2-Thin-(VeryFast)-Luma//!HOOK MAIN//!BIND HOOKED//!SAVE LINELUMA//!WIDTH HOOKED.w 2 ///!HEIGHT HOOKED.h 2 ///!COMPONENTS 1float get_luma(vec4 rgba) { return dot(vec4(0.299, 0.587, 0.114, 0.0), rgba);}vec4 hook() { return vec4(get_luma(HOOKED_tex(HOOKED_pos)), 0.0, 0.0, 0.0);}//!DESC Anime4K-v3.2-Thin-(VeryFast)-Sobel-X//!HOOK MAIN//!BIND LINELUMA//!SAVE LINESOBEL//!WIDTH HOOKED.w 4 ///!HEIGHT HOOKED.h 4 ///!COMPONENTS 2vec4 hook() { float l = LINELUMA_texOff(vec2(-0.5, 0.0)).x; float c = LINELUMA_tex(LINELUMA_pos).x; float r = LINELUMA_texOff(vec2(0.5, 0.0)).x; float xgrad = (-l + r); float ygrad = (l + c + c + r); return vec4(xgrad, ygrad, 0.0, 0.0);}//!DESC Anime4K-v3.2-Thin-(VeryFast)-Sobel-Y//!HOOK MAIN//!BIND LINESOBEL//!SAVE LINESOBEL//!WIDTH HOOKED.w 4 ///!HEIGHT HOOKED.h 4 ///!COMPONENTS 1vec4 hook() { float tx = LINESOBEL_texOff(vec2(0.0, -0.25)).x; float cx = LINESOBEL_tex(LINESOBEL_pos).x; float bx = LINESOBEL_texOff(vec2(0.0, 0.25)).x; float ty = LINESOBEL_texOff(vec2(0.0, -0.25)).y; float by = LINESOBEL_texOff(vec2(0.0, 0.25)).y; float xgrad = (tx + cx + cx + bx) / 8.0; float ygrad = (-ty + by) / 8.0; //Computes the luminance's gradient float norm = sqrt(xgrad * xgrad + ygrad * ygrad); return vec4(pow(norm, 0.7));}//!DESC Anime4K-v3.2-Thin-(VeryFast)-Gaussian-X//!HOOK MAIN//!BIND HOOKED//!BIND LINESOBEL//!SAVE LINESOBEL//!WIDTH HOOKED.w 4 ///!HEIGHT HOOKED.h 4 ///!COMPONENTS 1#define SPATIAL_SIGMA (0.5 * float(HOOKED_size.y) / 1080.0) //Spatial window size, must be a positive real number.#define KERNELSIZE (max(int(ceil(SPATIAL_SIGMA * 2.0)), 1) * 2 + 1) //Kernel size, must be an positive odd integer.#define KERNELHALFSIZE (int(KERNELSIZE/2)) //Half of the kernel size without remainder. Must be equal to trunc(KERNELSIZE/2).#define KERNELLEN (KERNELSIZE * KERNELSIZE) //Total area of kernel. Must be equal to KERNELSIZE * KERNELSIZE.float gaussian(float x, float s, float m) { float scaled = (x - m) / s; return exp(-0.5 * scaled * scaled);}float comp_gaussian_x() { float g = 0.0; float gn = 0.0; for (int i=0; i<KERNELSIZE; i++) { float di = float(i - KERNELHALFSIZE); float gf = gaussian(di, SPATIAL_SIGMA, 0.0); g = g + LINESOBEL_texOff(vec2(di, 0.0)).x * gf; gn = gn + gf; } return g / gn;}vec4 hook() { return vec4(comp_gaussian_x(), 0.0, 0.0, 0.0);}//!DESC Anime4K-v3.2-Thin-(VeryFast)-Gaussian-Y//!HOOK MAIN//!BIND HOOKED//!BIND LINESOBEL//!SAVE LINESOBEL//!WIDTH HOOKED.w 4 ///!HEIGHT HOOKED.h 4 ///!COMPONENTS 1#define SPATIAL_SIGMA (0.5 * float(HOOKED_size.y) / 1080.0) //Spatial window size, must be a positive real number.#define KERNELSIZE (max(int(ceil(SPATIAL_SIGMA * 2.0)), 1) * 2 + 1) //Kernel size, must be an positive odd integer.#define KERNELHALFSIZE (int(KERNELSIZE/2)) //Half of the kernel size without remainder. Must be equal to trunc(KERNELSIZE/2).#define KERNELLEN (KERNELSIZE * KERNELSIZE) //Total area of kernel. Must be equal to KERNELSIZE * KERNELSIZE.float gaussian(float x, float s, float m) { float scaled = (x - m) / s; return exp(-0.5 * scaled * scaled);}float comp_gaussian_y() { float g = 0.0; float gn = 0.0; for (int i=0; i<KERNELSIZE; i++) { float di = float(i - KERNELHALFSIZE); float gf = gaussian(di, SPATIAL_SIGMA, 0.0); g = g + LINESOBEL_texOff(vec2(0.0, di)).x * gf; gn = gn + gf; } return g / gn;}vec4 hook() { return vec4(comp_gaussian_y(), 0.0, 0.0, 0.0);}//!DESC Anime4K-v3.2-Thin-(VeryFast)-Kernel-X//!HOOK MAIN//!BIND LINESOBEL//!SAVE LINESOBEL//!WIDTH HOOKED.w 4 ///!HEIGHT HOOKED.h 4 ///!COMPONENTS 2vec4 hook() { float l = LINESOBEL_texOff(vec2(-0.25, 0.0)).x; float c = LINESOBEL_tex(LINESOBEL_pos).x; float r = LINESOBEL_texOff(vec2(0.25, 0.0)).x; float xgrad = (-l + r); float ygrad = (l + c + c + r); return vec4(xgrad, ygrad, 0.0, 0.0);}//!DESC Anime4K-v3.2-Thin-(VeryFast)-Kernel-Y//!HOOK MAIN//!BIND LINESOBEL//!SAVE LINESOBEL//!WIDTH HOOKED.w 4 ///!HEIGHT HOOKED.h 4 ///!COMPONENTS 2vec4 hook() { float tx = LINESOBEL_texOff(vec2(0.0, -0.25)).x; float cx = LINESOBEL_tex(LINESOBEL_pos).x; float bx = LINESOBEL_texOff(vec2(0.0, 0.25)).x; float ty = LINESOBEL_texOff(vec2(0.0, -0.25)).y; float by = LINESOBEL_texOff(vec2(0.0, 0.25)).y; float xgrad = (tx + cx + cx + bx) / 8.0; float ygrad = (-ty + by) / 8.0; //Computes the luminance's gradient return vec4(xgrad, ygrad, 0.0, 0.0);}//!DESC Anime4K-v3.2-Thin-(VeryFast)-Warp//!HOOK MAIN//!BIND HOOKED//!BIND LINESOBEL#define STRENGTH 0.6 //Strength of warping for each iteration#define ITERATIONS 1 //Number of iterations for the forwards solver, decreasing strength and increasing iterations improves quality at the cost of speed.vec4 hook() { vec2 d = HOOKED_pt; float relstr = HOOKED_size.y / 1080.0 * STRENGTH; vec2 pos = HOOKED_pos; for (int i=0; i<ITERATIONS; i++) { vec2 dn = LINESOBEL_tex(pos).xy; vec2 dd = (dn / (length(dn) + 0.01)) * d * relstr; //Quasi-normalization for large vectors, avoids divide by zero pos -= dd; } return HOOKED_tex(pos);}mpv/shaders/Anime4K_Upscale_DTD_x2.glsl
Modified+613 / −613 text lines
// MIT License
// Copyright (c) 2019-2021 bloc97
// All rights reserved.
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//!DESC Anime4K-v3.2-Upscale-DTD-x2-Luma
//!HOOK MAIN
//!BIND HOOKED
//!SAVE LINELUMA
//!COMPONENTS 1
float get_luma(vec4 rgba) {
return dot(vec4(0.299, 0.587, 0.114, 0.0), rgba);
}
vec4 hook() {
return vec4(get_luma(HOOKED_tex(HOOKED_pos)), 0.0, 0.0, 0.0);
}
//!DESC Anime4K-v3.2-Upscale-DTD-x2-Kernel-X
//!WHEN OUTPUT.w MAIN.w / 1.200 > OUTPUT.h MAIN.h / 1.200 > *
//!HOOK MAIN
//!BIND HOOKED
//!BIND LINELUMA
//!SAVE MMKERNEL
//!COMPONENTS 1
#define L_tex LINELUMA_tex
#define SIGMA 1.0
float gaussian(float x, float s, float m) {
return (1.0 / (s * sqrt(2.0 * 3.14159))) * exp(-0.5 * pow(abs(x - m) / s, 2.0));
}
float lumGaussian(vec2 pos, vec2 d) {
float s = SIGMA * HOOKED_size.y / 1080.0;
float kernel_size = s * 2.0 + 1.0;
float g = (L_tex(pos).x) * gaussian(0.0, s, 0.0);
float gn = gaussian(0.0, s, 0.0);
g += (L_tex(pos - d).x + L_tex(pos + d).x) * gaussian(1.0, s, 0.0);
gn += gaussian(1.0, s, 0.0) * 2.0;
for (int i=2; float(i)<kernel_size; i++) {
g += (L_tex(pos - (d * float(i))).x + L_tex(pos + (d * float(i))).x) * gaussian(float(i), s, 0.0);
gn += gaussian(float(i), s, 0.0) * 2.0;
}
return g / gn;
}
vec4 hook() {
return vec4(lumGaussian(HOOKED_pos, vec2(HOOKED_pt.x, 0)));
}
//!DESC Anime4K-v3.2-Upscale-DTD-x2-Kernel-Y
//!WHEN OUTPUT.w MAIN.w / 1.200 > OUTPUT.h MAIN.h / 1.200 > *
//!HOOK MAIN
//!BIND HOOKED
//!BIND LINELUMA
//!BIND MMKERNEL
//!SAVE MMKERNEL
//!COMPONENTS 1
#define L_tex MMKERNEL_tex
#define SIGMA 1.0
float gaussian(float x, float s, float m) {
return (1.0 / (s * sqrt(2.0 * 3.14159))) * exp(-0.5 * pow(abs(x - m) / s, 2.0));
}
float lumGaussian(vec2 pos, vec2 d) {
float s = SIGMA * HOOKED_size.y / 1080.0;
float kernel_size = s * 2.0 + 1.0;
float g = (L_tex(pos).x) * gaussian(0.0, s, 0.0);
float gn = gaussian(0.0, s, 0.0);
g += (L_tex(pos - d).x + L_tex(pos + d).x) * gaussian(1.0, s, 0.0);
gn += gaussian(1.0, s, 0.0) * 2.0;
for (int i=2; float(i)<kernel_size; i++) {
g += (L_tex(pos - (d * float(i))).x + L_tex(pos + (d * float(i))).x) * gaussian(float(i), s, 0.0);
gn += gaussian(float(i), s, 0.0) * 2.0;
}
return g / gn;
}
vec4 hook() {
return vec4(min(LINELUMA_tex(HOOKED_pos).x - lumGaussian(HOOKED_pos, vec2(0, HOOKED_pt.y)), 0.0));
}
//!DESC Anime4K-v3.2-Upscale-DTD-x2-Kernel-X
//!WHEN OUTPUT.w MAIN.w / 1.200 > OUTPUT.h MAIN.h / 1.200 > *
//!HOOK MAIN
//!BIND HOOKED
//!BIND MMKERNEL
//!SAVE MMKERNEL
//!COMPONENTS 1
#define L_tex MMKERNEL_tex
#define SIGMA 0.4
float gaussian(float x, float s, float m) {
return (1.0 / (s * sqrt(2.0 * 3.14159))) * exp(-0.5 * pow(abs(x - m) / s, 2.0));
}
float lumGaussian(vec2 pos, vec2 d) {
float s = SIGMA * HOOKED_size.y / 1080.0;
float kernel_size = s * 2.0 + 1.0;
float g = (L_tex(pos).x) * gaussian(0.0, s, 0.0);
float gn = gaussian(0.0, s, 0.0);
g += (L_tex(pos - d).x + L_tex(pos + d).x) * gaussian(1.0, s, 0.0);
gn += gaussian(1.0, s, 0.0) * 2.0;
for (int i=2; float(i)<kernel_size; i++) {
g += (L_tex(pos - (d * float(i))).x + L_tex(pos + (d * float(i))).x) * gaussian(float(i), s, 0.0);
gn += gaussian(float(i), s, 0.0) * 2.0;
}
return g / gn;
}
vec4 hook() {
return vec4(lumGaussian(HOOKED_pos, vec2(HOOKED_pt.x, 0)));
}
//!DESC Anime4K-v3.2-Upscale-DTD-x2-Kernel-Y
//!WHEN OUTPUT.w MAIN.w / 1.200 > OUTPUT.h MAIN.h / 1.200 > *
//!HOOK MAIN
//!BIND HOOKED
//!BIND MMKERNEL
//!SAVE MMKERNEL
//!COMPONENTS 1
#define L_tex MMKERNEL_tex
#define SIGMA 0.4
float gaussian(float x, float s, float m) {
return (1.0 / (s * sqrt(2.0 * 3.14159))) * exp(-0.5 * pow(abs(x - m) / s, 2.0));
}
float lumGaussian(vec2 pos, vec2 d) {
float s = SIGMA * HOOKED_size.y / 1080.0;
float kernel_size = s * 2.0 + 1.0;
float g = (L_tex(pos).x) * gaussian(0.0, s, 0.0);
float gn = gaussian(0.0, s, 0.0);
g += (L_tex(pos - d).x + L_tex(pos + d).x) * gaussian(1.0, s, 0.0);
gn += gaussian(1.0, s, 0.0) * 2.0;
for (int i=2; float(i)<kernel_size; i++) {
g += (L_tex(pos - (d * float(i))).x + L_tex(pos + (d * float(i))).x) * gaussian(float(i), s, 0.0);
gn += gaussian(float(i), s, 0.0) * 2.0;
}
return g / gn;
}
vec4 hook() {
return vec4(lumGaussian(HOOKED_pos, vec2(0, HOOKED_pt.y)));
}
//!DESC Anime4K-v3.2-Upscale-DTD-x2
//!WHEN OUTPUT.w MAIN.w / 1.200 > OUTPUT.h MAIN.h / 1.200 > *
//!HOOK MAIN
//!BIND HOOKED
//!BIND MMKERNEL
#define STRENGTH 1.8 //Line darken proportional strength, higher is darker.
vec4 hook() {
float c = (MMKERNEL_tex(HOOKED_pos).x) * STRENGTH;
//This trick is only possible if the inverse Y->RGB matrix has 1 for every row... (which is the case for BT.709)
//Otherwise we would need to convert RGB to YUV, modify Y then convert back to RGB.
return HOOKED_tex(HOOKED_pos) + c;
}
//!DESC Anime4K-v3.2-Upscale-DTD-x2-Luma
//!HOOK MAIN
//!BIND HOOKED
//!SAVE LINELUMA
//!COMPONENTS 1
float get_luma(vec4 rgba) {
return dot(vec4(0.299, 0.587, 0.114, 0.0), rgba);
}
vec4 hook() {
return vec4(get_luma(HOOKED_tex(HOOKED_pos)), 0.0, 0.0, 0.0);
}
//!DESC Anime4K-v3.2-Upscale-DTD-x2-Kernel-X
//!WHEN OUTPUT.w MAIN.w / 1.200 > OUTPUT.h MAIN.h / 1.200 > *
//!HOOK MAIN
//!BIND HOOKED
//!BIND LINELUMA
//!SAVE LUMAD
//!COMPONENTS 2
#define L_tex LINELUMA_tex
vec4 hook() {
vec2 d = HOOKED_pt;
//[tl t tr]
//[ l c r]
//[bl b br]
float l = L_tex(HOOKED_pos + vec2(-d.x, 0)).x;
float c = L_tex(HOOKED_pos).x;
float r = L_tex(HOOKED_pos + vec2(d.x, 0)).x;
//Horizontal Gradient
//[-1 0 1]
//[-2 0 2]
//[-1 0 1]
float xgrad = (-l + r);
//Vertical Gradient
//[-1 -2 -1]
//[ 0 0 0]
//[ 1 2 1]
float ygrad = (l + c + c + r);
//Computes the luminance's gradient
return vec4(xgrad, ygrad, 0, 0);
}
//!DESC Anime4K-v3.2-Upscale-DTD-x2-Kernel-Y
//!WHEN OUTPUT.w MAIN.w / 1.200 > OUTPUT.h MAIN.h / 1.200 > *
//!HOOK MAIN
//!BIND HOOKED
//!BIND LUMAD
//!SAVE LUMAD
//!COMPONENTS 1
vec4 hook() {
vec2 d = HOOKED_pt;
//[tl t tr]
//[ l cc r]
//[bl b br]
float tx = LUMAD_tex(HOOKED_pos + vec2(0, -d.y)).x;
float cx = LUMAD_tex(HOOKED_pos).x;
float bx = LUMAD_tex(HOOKED_pos + vec2(0, d.y)).x;
float ty = LUMAD_tex(HOOKED_pos + vec2(0, -d.y)).y;
//float cy = LUMAD_tex(HOOKED_pos).y;
float by = LUMAD_tex(HOOKED_pos + vec2(0, d.y)).y;
//Horizontal Gradient
//[-1 0 1]
//[-2 0 2]
//[-1 0 1]
float xgrad = (tx + cx + cx + bx) / 8.0;
//Vertical Gradient
//[-1 -2 -1]
//[ 0 0 0]
//[ 1 2 1]
float ygrad = (-ty + by) / 8.0;
//Computes the luminance's gradient
float norm = sqrt(xgrad * xgrad + ygrad * ygrad);
return vec4(pow(norm, 0.7));
}
//!DESC Anime4K-v3.2-Upscale-DTD-x2-Kernel-X
//!WHEN OUTPUT.w MAIN.w / 1.200 > OUTPUT.h MAIN.h / 1.200 > *
//!HOOK MAIN
//!BIND HOOKED
//!BIND LUMAD
//!SAVE LUMADG
//!COMPONENTS 1
#define L_tex LUMAD_tex
#define SIGMA (HOOKED_size.y / 1080.0) * 2.0
#define KERNELSIZE (SIGMA * 2.0 + 1.0)
float gaussian(float x, float s, float m) {
return (1.0 / (s * sqrt(2.0 * 3.14159))) * exp(-0.5 * pow(abs(x - m) / s, 2.0));
}
float lumGaussian(vec2 pos, vec2 d) {
float g = (L_tex(pos).x) * gaussian(0.0, SIGMA, 0.0);
g = g + (L_tex(pos - d).x + L_tex(pos + d).x) * gaussian(1.0, SIGMA, 0.0);
for (int i=2; float(i)<KERNELSIZE; i++) {
g = g + (L_tex(pos - (d * float(i))).x + L_tex(pos + (d * float(i))).x) * gaussian(float(i), SIGMA, 0.0);
}
return g;
}
vec4 hook() {
return vec4(lumGaussian(HOOKED_pos, vec2(HOOKED_pt.x, 0)));
}
//!DESC Anime4K-v3.2-Upscale-DTD-x2-Kernel-Y
//!WHEN OUTPUT.w MAIN.w / 1.200 > OUTPUT.h MAIN.h / 1.200 > *
//!HOOK MAIN
//!BIND HOOKED
//!BIND LUMAD
//!BIND LUMADG
//!SAVE LUMAD
//!COMPONENTS 1
#define L_tex LUMADG_tex
#define SIGMA (HOOKED_size.y / 1080.0) * 2.0
#define KERNELSIZE (SIGMA * 2.0 + 1.0)
float gaussian(float x, float s, float m) {
return (1.0 / (s * sqrt(2.0 * 3.14159))) * exp(-0.5 * pow(abs(x - m) / s, 2.0));
}
float lumGaussian(vec2 pos, vec2 d) {
float g = (L_tex(pos).x) * gaussian(0.0, SIGMA, 0.0);
g = g + (L_tex(pos - d).x + L_tex(pos + d).x) * gaussian(1.0, SIGMA, 0.0);
for (int i=2; float(i)<KERNELSIZE; i++) {
g = g + (L_tex(pos - (d * float(i))).x + L_tex(pos + (d * float(i))).x) * gaussian(float(i), SIGMA, 0.0);
}
return g;
}
vec4 hook() {
float g = lumGaussian(HOOKED_pos, vec2(0, HOOKED_pt.y));
return vec4(g);
}
//!DESC Anime4K-v3.2-Upscale-DTD-x2-Kernel-X
//!WHEN OUTPUT.w MAIN.w / 1.200 > OUTPUT.h MAIN.h / 1.200 > *
//!HOOK MAIN
//!BIND HOOKED
//!BIND LUMAD
//!SAVE LUMAD2
//!COMPONENTS 2
vec4 hook() {
vec2 d = HOOKED_pt;
//[tl t tr]
//[ l c r]
//[bl b br]
float l = LUMAD_tex(HOOKED_pos + vec2(-d.x, 0)).x;
float c = LUMAD_tex(HOOKED_pos).x;
float r = LUMAD_tex(HOOKED_pos + vec2(d.x, 0)).x;
//Horizontal Gradient
//[-1 0 1]
//[-2 0 2]
//[-1 0 1]
float xgrad = (-l + r);
//Vertical Gradient
//[-1 -2 -1]
//[ 0 0 0]
//[ 1 2 1]
float ygrad = (l + c + c + r);
//Computes the luminance's gradient
return vec4(xgrad, ygrad, 0, 0);
}
//!DESC Anime4K-v3.2-Upscale-DTD-x2-Kernel-Y
//!WHEN OUTPUT.w MAIN.w / 1.200 > OUTPUT.h MAIN.h / 1.200 > *
//!HOOK MAIN
//!BIND HOOKED
//!BIND LUMAD2
//!SAVE LUMAD2
//!COMPONENTS 2
vec4 hook() {
vec2 d = HOOKED_pt;
//[tl t tr]
//[ l cc r]
//[bl b br]
float tx = LUMAD2_tex(HOOKED_pos + vec2(0, -d.y)).x;
float cx = LUMAD2_tex(HOOKED_pos).x;
float bx = LUMAD2_tex(HOOKED_pos + vec2(0, d.y)).x;
float ty = LUMAD2_tex(HOOKED_pos + vec2(0, -d.y)).y;
//float cy = LUMAD2_tex(HOOKED_pos).y;
float by = LUMAD2_tex(HOOKED_pos + vec2(0, d.y)).y;
//Horizontal Gradient
//[-1 0 1]
//[-2 0 2]
//[-1 0 1]
float xgrad = (tx + cx + cx + bx) / 8.0;
//Vertical Gradient
//[-1 -2 -1]
//[ 0 0 0]
//[ 1 2 1]
float ygrad = (-ty + by) / 8.0;
//Computes the luminance's gradient
return vec4(xgrad, ygrad, 0, 0);
}
//!DESC Anime4K-v3.2-Upscale-DTD-x2
//!WHEN OUTPUT.w MAIN.w / 1.200 > OUTPUT.h MAIN.h / 1.200 > *
//!HOOK MAIN
//!BIND HOOKED
//!BIND LUMAD
//!BIND LUMAD2
//!SAVE MAINTEMPTHIN
//!WIDTH MAIN.w 2 *
//!HEIGHT MAIN.h 2 *
#define STRENGTH 0.4 //Strength of warping for each iteration
#define ITERATIONS 1 //Number of iterations for the forwards solver, decreasing strength and increasing iterations improves quality at the cost of speed.
#define L_tex HOOKED_tex
vec4 hook() {
vec2 d = HOOKED_pt;
float relstr = HOOKED_size.y / 1080.0 * STRENGTH;
vec2 pos = HOOKED_pos;
for (int i=0; i<ITERATIONS; i++) {
vec2 dn = LUMAD2_tex(pos).xy;
vec2 dd = (dn / (length(dn) + 0.01)) * d * relstr; //Quasi-normalization for large vectors, avoids divide by zero
pos -= dd;
}
return L_tex(pos);
}
//!DESC Anime4K-v3.2-Upscale-DTD-x2-Luma
//!HOOK MAIN
//!BIND HOOKED
//!BIND MAINTEMPTHIN
//!COMPONENTS 1
//!SAVE MAINTEMP
//!WIDTH MAIN.w 2 *
//!HEIGHT MAIN.h 2 *
float get_luma(vec4 rgba) {
return dot(vec4(0.299, 0.587, 0.114, 0.0), rgba);
}
vec4 hook() {
return vec4(get_luma(MAINTEMPTHIN_tex(HOOKED_pos)), 0.0, 0.0, 0.0);
}
//!DESC Anime4K-v3.2-Upscale-DTD-x2-Kernel-X
//!WHEN OUTPUT.w MAIN.w / 1.200 > OUTPUT.h MAIN.h / 1.200 > *
//!HOOK MAIN
//!BIND HOOKED
//!BIND MAINTEMP
//!SAVE MMKERNEL
//!COMPONENTS 3
#define L_tex MAINTEMP_tex
float max3v(float a, float b, float c) {
return max(max(a, b), c);
}
float min3v(float a, float b, float c) {
return min(min(a, b), c);
}
vec2 minmax3(vec2 pos, vec2 d) {
float a = L_tex(pos - d).x;
float b = L_tex(pos).x;
float c = L_tex(pos + d).x;
return vec2(min3v(a, b, c), max3v(a, b, c));
}
float lumGaussian7(vec2 pos, vec2 d) {
float g = (L_tex(pos - (d + d)).x + L_tex(pos + (d + d)).x) * 0.06136;
g = g + (L_tex(pos - d).x + L_tex(pos + d).x) * 0.24477;
g = g + (L_tex(pos).x) * 0.38774;
return g;
}
vec4 hook() {
return vec4(lumGaussian7(HOOKED_pos, vec2(HOOKED_pt.x, 0)), minmax3(HOOKED_pos, vec2(HOOKED_pt.x, 0)), 0);
}
//!DESC Anime4K-v3.2-Upscale-DTD-x2-Kernel-Y
//!WHEN OUTPUT.w MAIN.w / 1.200 > OUTPUT.h MAIN.h / 1.200 > *
//!HOOK MAIN
//!BIND HOOKED
//!BIND MMKERNEL
//!SAVE MMKERNEL
//!COMPONENTS 3
#define L_tex MMKERNEL_tex
float max3v(float a, float b, float c) {
return max(max(a, b), c);
}
float min3v(float a, float b, float c) {
return min(min(a, b), c);
}
vec2 minmax3(vec2 pos, vec2 d) {
float a0 = L_tex(pos - d).y;
float b0 = L_tex(pos).y;
float c0 = L_tex(pos + d).y;
float a1 = L_tex(pos - d).z;
float b1 = L_tex(pos).z;
float c1 = L_tex(pos + d).z;
return vec2(min3v(a0, b0, c0), max3v(a1, b1, c1));
}
float lumGaussian7(vec2 pos, vec2 d) {
float g = (L_tex(pos - (d + d)).x + L_tex(pos + (d + d)).x) * 0.06136;
g = g + (L_tex(pos - d).x + L_tex(pos + d).x) * 0.24477;
g = g + (L_tex(pos).x) * 0.38774;
return g;
}
vec4 hook() {
return vec4(lumGaussian7(HOOKED_pos, vec2(0, HOOKED_pt.y)), minmax3(HOOKED_pos, vec2(0, HOOKED_pt.y)), 0);
}
//!DESC Anime4K-v3.2-Upscale-DTD-x2
//!WHEN OUTPUT.w MAIN.w / 1.200 > OUTPUT.h MAIN.h / 1.200 > *
//!HOOK MAIN
//!BIND HOOKED
//!BIND MAINTEMPTHIN
//!BIND MAINTEMP
//!BIND MMKERNEL
//!WIDTH MAIN.w 2 *
//!HEIGHT MAIN.h 2 *
#define STRENGTH 0.5 //De-blur proportional strength, higher is sharper. However, it is better to tweak BLUR_CURVE instead to avoid ringing.
#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;
#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.
#define NOISE_THRESHOLD 0.004 //Value where curve stops, used to not sharpen noise. Only de-blur values that fall above this threshold.
#define L_tex MAINTEMP_tex
vec4 hook() {
float c = (L_tex(HOOKED_pos).x - MMKERNEL_tex(HOOKED_pos).x) * STRENGTH;
float t_range = BLUR_THRESHOLD - NOISE_THRESHOLD;
float c_t = abs(c);
if (c_t > NOISE_THRESHOLD) {
c_t = (c_t - NOISE_THRESHOLD) / t_range;
c_t = pow(c_t, BLUR_CURVE);
c_t = c_t * t_range + NOISE_THRESHOLD;
c_t = c_t * sign(c);
} else {
c_t = c;
}
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;
//This trick is only possible if the inverse Y->RGB matrix has 1 for every row... (which is the case for BT.709)
//Otherwise we would need to convert RGB to YUV, modify Y then convert back to RGB.
return MAINTEMPTHIN_tex(HOOKED_pos) + cc;
}
// MIT License// Copyright (c) 2019-2021 bloc97// All rights reserved.// Permission is hereby granted, free of charge, to any person obtaining a copy// of this software and associated documentation files (the "Software"), to deal// in the Software without restriction, including without limitation the rights// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell// copies of the Software, and to permit persons to whom the Software is// furnished to do so, subject to the following conditions:// The above copyright notice and this permission notice shall be included in all// copies or substantial portions of the Software.// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE// SOFTWARE.//!DESC Anime4K-v3.2-Upscale-DTD-x2-Luma//!HOOK MAIN//!BIND HOOKED//!SAVE LINELUMA//!COMPONENTS 1float get_luma(vec4 rgba) { return dot(vec4(0.299, 0.587, 0.114, 0.0), rgba);}vec4 hook() { return vec4(get_luma(HOOKED_tex(HOOKED_pos)), 0.0, 0.0, 0.0);}//!DESC Anime4K-v3.2-Upscale-DTD-x2-Kernel-X//!WHEN OUTPUT.w MAIN.w / 1.200 > OUTPUT.h MAIN.h / 1.200 > *//!HOOK MAIN//!BIND HOOKED//!BIND LINELUMA//!SAVE MMKERNEL//!COMPONENTS 1#define L_tex LINELUMA_tex#define SIGMA 1.0float gaussian(float x, float s, float m) { return (1.0 / (s * sqrt(2.0 * 3.14159))) * exp(-0.5 * pow(abs(x - m) / s, 2.0));}float lumGaussian(vec2 pos, vec2 d) { float s = SIGMA * HOOKED_size.y / 1080.0; float kernel_size = s * 2.0 + 1.0; float g = (L_tex(pos).x) * gaussian(0.0, s, 0.0); float gn = gaussian(0.0, s, 0.0); g += (L_tex(pos - d).x + L_tex(pos + d).x) * gaussian(1.0, s, 0.0); gn += gaussian(1.0, s, 0.0) * 2.0; for (int i=2; float(i)<kernel_size; i++) { g += (L_tex(pos - (d * float(i))).x + L_tex(pos + (d * float(i))).x) * gaussian(float(i), s, 0.0); gn += gaussian(float(i), s, 0.0) * 2.0; } return g / gn;}vec4 hook() { return vec4(lumGaussian(HOOKED_pos, vec2(HOOKED_pt.x, 0)));}//!DESC Anime4K-v3.2-Upscale-DTD-x2-Kernel-Y//!WHEN OUTPUT.w MAIN.w / 1.200 > OUTPUT.h MAIN.h / 1.200 > *//!HOOK MAIN//!BIND HOOKED//!BIND LINELUMA//!BIND MMKERNEL//!SAVE MMKERNEL//!COMPONENTS 1#define L_tex MMKERNEL_tex#define SIGMA 1.0float gaussian(float x, float s, float m) { return (1.0 / (s * sqrt(2.0 * 3.14159))) * exp(-0.5 * pow(abs(x - m) / s, 2.0));}float lumGaussian(vec2 pos, vec2 d) { float s = SIGMA * HOOKED_size.y / 1080.0; float kernel_size = s * 2.0 + 1.0; float g = (L_tex(pos).x) * gaussian(0.0, s, 0.0); float gn = gaussian(0.0, s, 0.0); g += (L_tex(pos - d).x + L_tex(pos + d).x) * gaussian(1.0, s, 0.0); gn += gaussian(1.0, s, 0.0) * 2.0; for (int i=2; float(i)<kernel_size; i++) { g += (L_tex(pos - (d * float(i))).x + L_tex(pos + (d * float(i))).x) * gaussian(float(i), s, 0.0); gn += gaussian(float(i), s, 0.0) * 2.0; } return g / gn;}vec4 hook() { return vec4(min(LINELUMA_tex(HOOKED_pos).x - lumGaussian(HOOKED_pos, vec2(0, HOOKED_pt.y)), 0.0));}//!DESC Anime4K-v3.2-Upscale-DTD-x2-Kernel-X//!WHEN OUTPUT.w MAIN.w / 1.200 > OUTPUT.h MAIN.h / 1.200 > *//!HOOK MAIN//!BIND HOOKED//!BIND MMKERNEL//!SAVE MMKERNEL//!COMPONENTS 1#define L_tex MMKERNEL_tex#define SIGMA 0.4float gaussian(float x, float s, float m) { return (1.0 / (s * sqrt(2.0 * 3.14159))) * exp(-0.5 * pow(abs(x - m) / s, 2.0));}float lumGaussian(vec2 pos, vec2 d) { float s = SIGMA * HOOKED_size.y / 1080.0; float kernel_size = s * 2.0 + 1.0; float g = (L_tex(pos).x) * gaussian(0.0, s, 0.0); float gn = gaussian(0.0, s, 0.0); g += (L_tex(pos - d).x + L_tex(pos + d).x) * gaussian(1.0, s, 0.0); gn += gaussian(1.0, s, 0.0) * 2.0; for (int i=2; float(i)<kernel_size; i++) { g += (L_tex(pos - (d * float(i))).x + L_tex(pos + (d * float(i))).x) * gaussian(float(i), s, 0.0); gn += gaussian(float(i), s, 0.0) * 2.0; } return g / gn;}vec4 hook() { return vec4(lumGaussian(HOOKED_pos, vec2(HOOKED_pt.x, 0)));}//!DESC Anime4K-v3.2-Upscale-DTD-x2-Kernel-Y//!WHEN OUTPUT.w MAIN.w / 1.200 > OUTPUT.h MAIN.h / 1.200 > *//!HOOK MAIN//!BIND HOOKED//!BIND MMKERNEL//!SAVE MMKERNEL//!COMPONENTS 1#define L_tex MMKERNEL_tex#define SIGMA 0.4float gaussian(float x, float s, float m) { return (1.0 / (s * sqrt(2.0 * 3.14159))) * exp(-0.5 * pow(abs(x - m) / s, 2.0));}float lumGaussian(vec2 pos, vec2 d) { float s = SIGMA * HOOKED_size.y / 1080.0; float kernel_size = s * 2.0 + 1.0; float g = (L_tex(pos).x) * gaussian(0.0, s, 0.0); float gn = gaussian(0.0, s, 0.0); g += (L_tex(pos - d).x + L_tex(pos + d).x) * gaussian(1.0, s, 0.0); gn += gaussian(1.0, s, 0.0) * 2.0; for (int i=2; float(i)<kernel_size; i++) { g += (L_tex(pos - (d * float(i))).x + L_tex(pos + (d * float(i))).x) * gaussian(float(i), s, 0.0); gn += gaussian(float(i), s, 0.0) * 2.0; } return g / gn;}vec4 hook() { return vec4(lumGaussian(HOOKED_pos, vec2(0, HOOKED_pt.y)));}//!DESC Anime4K-v3.2-Upscale-DTD-x2//!WHEN OUTPUT.w MAIN.w / 1.200 > OUTPUT.h MAIN.h / 1.200 > *//!HOOK MAIN//!BIND HOOKED//!BIND MMKERNEL#define STRENGTH 1.8 //Line darken proportional strength, higher is darker.vec4 hook() { float c = (MMKERNEL_tex(HOOKED_pos).x) * STRENGTH; //This trick is only possible if the inverse Y->RGB matrix has 1 for every row... (which is the case for BT.709) //Otherwise we would need to convert RGB to YUV, modify Y then convert back to RGB. return HOOKED_tex(HOOKED_pos) + c;}//!DESC Anime4K-v3.2-Upscale-DTD-x2-Luma//!HOOK MAIN//!BIND HOOKED//!SAVE LINELUMA//!COMPONENTS 1float get_luma(vec4 rgba) { return dot(vec4(0.299, 0.587, 0.114, 0.0), rgba);}vec4 hook() { return vec4(get_luma(HOOKED_tex(HOOKED_pos)), 0.0, 0.0, 0.0);}//!DESC Anime4K-v3.2-Upscale-DTD-x2-Kernel-X//!WHEN OUTPUT.w MAIN.w / 1.200 > OUTPUT.h MAIN.h / 1.200 > *//!HOOK MAIN//!BIND HOOKED//!BIND LINELUMA//!SAVE LUMAD//!COMPONENTS 2#define L_tex LINELUMA_texvec4 hook() { vec2 d = HOOKED_pt; //[tl t tr] //[ l c r] //[bl b br] float l = L_tex(HOOKED_pos + vec2(-d.x, 0)).x; float c = L_tex(HOOKED_pos).x; float r = L_tex(HOOKED_pos + vec2(d.x, 0)).x; //Horizontal Gradient //[-1 0 1] //[-2 0 2] //[-1 0 1] float xgrad = (-l + r); //Vertical Gradient //[-1 -2 -1] //[ 0 0 0] //[ 1 2 1] float ygrad = (l + c + c + r); //Computes the luminance's gradient return vec4(xgrad, ygrad, 0, 0);}//!DESC Anime4K-v3.2-Upscale-DTD-x2-Kernel-Y//!WHEN OUTPUT.w MAIN.w / 1.200 > OUTPUT.h MAIN.h / 1.200 > *//!HOOK MAIN//!BIND HOOKED//!BIND LUMAD//!SAVE LUMAD//!COMPONENTS 1vec4 hook() { vec2 d = HOOKED_pt; //[tl t tr] //[ l cc r] //[bl b br] float tx = LUMAD_tex(HOOKED_pos + vec2(0, -d.y)).x; float cx = LUMAD_tex(HOOKED_pos).x; float bx = LUMAD_tex(HOOKED_pos + vec2(0, d.y)).x; float ty = LUMAD_tex(HOOKED_pos + vec2(0, -d.y)).y; //float cy = LUMAD_tex(HOOKED_pos).y; float by = LUMAD_tex(HOOKED_pos + vec2(0, d.y)).y; //Horizontal Gradient //[-1 0 1] //[-2 0 2] //[-1 0 1] float xgrad = (tx + cx + cx + bx) / 8.0; //Vertical Gradient //[-1 -2 -1] //[ 0 0 0] //[ 1 2 1] float ygrad = (-ty + by) / 8.0; //Computes the luminance's gradient float norm = sqrt(xgrad * xgrad + ygrad * ygrad); return vec4(pow(norm, 0.7));}//!DESC Anime4K-v3.2-Upscale-DTD-x2-Kernel-X//!WHEN OUTPUT.w MAIN.w / 1.200 > OUTPUT.h MAIN.h / 1.200 > *//!HOOK MAIN//!BIND HOOKED//!BIND LUMAD//!SAVE LUMADG//!COMPONENTS 1#define L_tex LUMAD_tex#define SIGMA (HOOKED_size.y / 1080.0) * 2.0#define KERNELSIZE (SIGMA * 2.0 + 1.0)float gaussian(float x, float s, float m) { return (1.0 / (s * sqrt(2.0 * 3.14159))) * exp(-0.5 * pow(abs(x - m) / s, 2.0));}float lumGaussian(vec2 pos, vec2 d) { float g = (L_tex(pos).x) * gaussian(0.0, SIGMA, 0.0); g = g + (L_tex(pos - d).x + L_tex(pos + d).x) * gaussian(1.0, SIGMA, 0.0); for (int i=2; float(i)<KERNELSIZE; i++) { g = g + (L_tex(pos - (d * float(i))).x + L_tex(pos + (d * float(i))).x) * gaussian(float(i), SIGMA, 0.0); } return g;}vec4 hook() { return vec4(lumGaussian(HOOKED_pos, vec2(HOOKED_pt.x, 0)));}//!DESC Anime4K-v3.2-Upscale-DTD-x2-Kernel-Y//!WHEN OUTPUT.w MAIN.w / 1.200 > OUTPUT.h MAIN.h / 1.200 > *//!HOOK MAIN//!BIND HOOKED//!BIND LUMAD//!BIND LUMADG//!SAVE LUMAD//!COMPONENTS 1#define L_tex LUMADG_tex#define SIGMA (HOOKED_size.y / 1080.0) * 2.0#define KERNELSIZE (SIGMA * 2.0 + 1.0)float gaussian(float x, float s, float m) { return (1.0 / (s * sqrt(2.0 * 3.14159))) * exp(-0.5 * pow(abs(x - m) / s, 2.0));}float lumGaussian(vec2 pos, vec2 d) { float g = (L_tex(pos).x) * gaussian(0.0, SIGMA, 0.0); g = g + (L_tex(pos - d).x + L_tex(pos + d).x) * gaussian(1.0, SIGMA, 0.0); for (int i=2; float(i)<KERNELSIZE; i++) { g = g + (L_tex(pos - (d * float(i))).x + L_tex(pos + (d * float(i))).x) * gaussian(float(i), SIGMA, 0.0); } return g;}vec4 hook() { float g = lumGaussian(HOOKED_pos, vec2(0, HOOKED_pt.y)); return vec4(g);}//!DESC Anime4K-v3.2-Upscale-DTD-x2-Kernel-X//!WHEN OUTPUT.w MAIN.w / 1.200 > OUTPUT.h MAIN.h / 1.200 > *//!HOOK MAIN//!BIND HOOKED//!BIND LUMAD//!SAVE LUMAD2//!COMPONENTS 2vec4 hook() { vec2 d = HOOKED_pt; //[tl t tr] //[ l c r] //[bl b br] float l = LUMAD_tex(HOOKED_pos + vec2(-d.x, 0)).x; float c = LUMAD_tex(HOOKED_pos).x; float r = LUMAD_tex(HOOKED_pos + vec2(d.x, 0)).x; //Horizontal Gradient //[-1 0 1] //[-2 0 2] //[-1 0 1] float xgrad = (-l + r); //Vertical Gradient //[-1 -2 -1] //[ 0 0 0] //[ 1 2 1] float ygrad = (l + c + c + r); //Computes the luminance's gradient return vec4(xgrad, ygrad, 0, 0);}//!DESC Anime4K-v3.2-Upscale-DTD-x2-Kernel-Y//!WHEN OUTPUT.w MAIN.w / 1.200 > OUTPUT.h MAIN.h / 1.200 > *//!HOOK MAIN//!BIND HOOKED//!BIND LUMAD2//!SAVE LUMAD2//!COMPONENTS 2vec4 hook() { vec2 d = HOOKED_pt; //[tl t tr] //[ l cc r] //[bl b br] float tx = LUMAD2_tex(HOOKED_pos + vec2(0, -d.y)).x; float cx = LUMAD2_tex(HOOKED_pos).x; float bx = LUMAD2_tex(HOOKED_pos + vec2(0, d.y)).x; float ty = LUMAD2_tex(HOOKED_pos + vec2(0, -d.y)).y; //float cy = LUMAD2_tex(HOOKED_pos).y; float by = LUMAD2_tex(HOOKED_pos + vec2(0, d.y)).y; //Horizontal Gradient //[-1 0 1] //[-2 0 2] //[-1 0 1] float xgrad = (tx + cx + cx + bx) / 8.0; //Vertical Gradient //[-1 -2 -1] //[ 0 0 0] //[ 1 2 1] float ygrad = (-ty + by) / 8.0; //Computes the luminance's gradient return vec4(xgrad, ygrad, 0, 0);}//!DESC Anime4K-v3.2-Upscale-DTD-x2//!WHEN OUTPUT.w MAIN.w / 1.200 > OUTPUT.h MAIN.h / 1.200 > *//!HOOK MAIN//!BIND HOOKED//!BIND LUMAD//!BIND LUMAD2//!SAVE MAINTEMPTHIN//!WIDTH MAIN.w 2 *//!HEIGHT MAIN.h 2 *#define STRENGTH 0.4 //Strength of warping for each iteration#define ITERATIONS 1 //Number of iterations for the forwards solver, decreasing strength and increasing iterations improves quality at the cost of speed.#define L_tex HOOKED_texvec4 hook() { vec2 d = HOOKED_pt; float relstr = HOOKED_size.y / 1080.0 * STRENGTH; vec2 pos = HOOKED_pos; for (int i=0; i<ITERATIONS; i++) { vec2 dn = LUMAD2_tex(pos).xy; vec2 dd = (dn / (length(dn) + 0.01)) * d * relstr; //Quasi-normalization for large vectors, avoids divide by zero pos -= dd; } return L_tex(pos);}//!DESC Anime4K-v3.2-Upscale-DTD-x2-Luma//!HOOK MAIN//!BIND HOOKED//!BIND MAINTEMPTHIN//!COMPONENTS 1//!SAVE MAINTEMP//!WIDTH MAIN.w 2 *//!HEIGHT MAIN.h 2 *float get_luma(vec4 rgba) { return dot(vec4(0.299, 0.587, 0.114, 0.0), rgba);}vec4 hook() { return vec4(get_luma(MAINTEMPTHIN_tex(HOOKED_pos)), 0.0, 0.0, 0.0);}//!DESC Anime4K-v3.2-Upscale-DTD-x2-Kernel-X//!WHEN OUTPUT.w MAIN.w / 1.200 > OUTPUT.h MAIN.h / 1.200 > *//!HOOK MAIN//!BIND HOOKED//!BIND MAINTEMP//!SAVE MMKERNEL//!COMPONENTS 3#define L_tex MAINTEMP_texfloat max3v(float a, float b, float c) { return max(max(a, b), c);}float min3v(float a, float b, float c) { return min(min(a, b), c);}vec2 minmax3(vec2 pos, vec2 d) { float a = L_tex(pos - d).x; float b = L_tex(pos).x; float c = L_tex(pos + d).x; return vec2(min3v(a, b, c), max3v(a, b, c));}float lumGaussian7(vec2 pos, vec2 d) { float g = (L_tex(pos - (d + d)).x + L_tex(pos + (d + d)).x) * 0.06136; g = g + (L_tex(pos - d).x + L_tex(pos + d).x) * 0.24477; g = g + (L_tex(pos).x) * 0.38774; return g;}vec4 hook() { return vec4(lumGaussian7(HOOKED_pos, vec2(HOOKED_pt.x, 0)), minmax3(HOOKED_pos, vec2(HOOKED_pt.x, 0)), 0);}//!DESC Anime4K-v3.2-Upscale-DTD-x2-Kernel-Y//!WHEN OUTPUT.w MAIN.w / 1.200 > OUTPUT.h MAIN.h / 1.200 > *//!HOOK MAIN//!BIND HOOKED//!BIND MMKERNEL//!SAVE MMKERNEL//!COMPONENTS 3#define L_tex MMKERNEL_texfloat max3v(float a, float b, float c) { return max(max(a, b), c);}float min3v(float a, float b, float c) { return min(min(a, b), c);}vec2 minmax3(vec2 pos, vec2 d) { float a0 = L_tex(pos - d).y; float b0 = L_tex(pos).y; float c0 = L_tex(pos + d).y; float a1 = L_tex(pos - d).z; float b1 = L_tex(pos).z; float c1 = L_tex(pos + d).z; return vec2(min3v(a0, b0, c0), max3v(a1, b1, c1));}float lumGaussian7(vec2 pos, vec2 d) { float g = (L_tex(pos - (d + d)).x + L_tex(pos + (d + d)).x) * 0.06136; g = g + (L_tex(pos - d).x + L_tex(pos + d).x) * 0.24477; g = g + (L_tex(pos).x) * 0.38774; return g;}vec4 hook() { return vec4(lumGaussian7(HOOKED_pos, vec2(0, HOOKED_pt.y)), minmax3(HOOKED_pos, vec2(0, HOOKED_pt.y)), 0);}//!DESC Anime4K-v3.2-Upscale-DTD-x2//!WHEN OUTPUT.w MAIN.w / 1.200 > OUTPUT.h MAIN.h / 1.200 > *//!HOOK MAIN//!BIND HOOKED//!BIND MAINTEMPTHIN//!BIND MAINTEMP//!BIND MMKERNEL//!WIDTH MAIN.w 2 *//!HEIGHT MAIN.h 2 *#define STRENGTH 0.5 //De-blur proportional strength, higher is sharper. However, it is better to tweak BLUR_CURVE instead to avoid ringing.#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;#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.#define NOISE_THRESHOLD 0.004 //Value where curve stops, used to not sharpen noise. Only de-blur values that fall above this threshold.#define L_tex MAINTEMP_texvec4 hook() { float c = (L_tex(HOOKED_pos).x - MMKERNEL_tex(HOOKED_pos).x) * STRENGTH; float t_range = BLUR_THRESHOLD - NOISE_THRESHOLD; float c_t = abs(c); if (c_t > NOISE_THRESHOLD) { c_t = (c_t - NOISE_THRESHOLD) / t_range; c_t = pow(c_t, BLUR_CURVE); c_t = c_t * t_range + NOISE_THRESHOLD; c_t = c_t * sign(c); } else { c_t = c; } 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; //This trick is only possible if the inverse Y->RGB matrix has 1 for every row... (which is the case for BT.709) //Otherwise we would need to convert RGB to YUV, modify Y then convert back to RGB. return MAINTEMPTHIN_tex(HOOKED_pos) + cc;}mpv/shaders/Anime4K_Upscale_Deblur_DoG_x2.glsl
Modified+158 / −158 text lines
// MIT License
// Copyright (c) 2019-2021 bloc97
// All rights reserved.
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//!DESC Anime4K-v3.2-Upscale-Deblur-DoG-x2-Luma
//!HOOK MAIN
//!BIND HOOKED
//!SAVE LINELUMA
//!COMPONENTS 1
float get_luma(vec4 rgba) {
return dot(vec4(0.299, 0.587, 0.114, 0.0), rgba);
}
vec4 hook() {
return vec4(get_luma(HOOKED_tex(HOOKED_pos)), 0.0, 0.0, 0.0);
}
//!DESC Anime4K-v3.2-Upscale-Deblur-DoG-x2-Kernel-X
//!WHEN OUTPUT.w MAIN.w / 1.200 > OUTPUT.h MAIN.h / 1.200 > *
//!HOOK MAIN
//!BIND HOOKED
//!BIND LINELUMA
//!SAVE GAUSS_X2
//!COMPONENTS 3
#define L_tex LINELUMA_tex
float max3v(float a, float b, float c) {
return max(max(a, b), c);
}
float min3v(float a, float b, float c) {
return min(min(a, b), c);
}
vec2 minmax3(vec2 pos, vec2 d) {
float a = L_tex(pos - d).x;
float b = L_tex(pos).x;
float c = L_tex(pos + d).x;
return vec2(min3v(a, b, c), max3v(a, b, c));
}
float lumGaussian7(vec2 pos, vec2 d) {
float g = (L_tex(pos - (d + d)).x + L_tex(pos + (d + d)).x) * 0.06136;
g = g + (L_tex(pos - d).x + L_tex(pos + d).x) * 0.24477;
g = g + (L_tex(pos).x) * 0.38774;
return g;
}
vec4 hook() {
return vec4(lumGaussian7(HOOKED_pos, vec2(HOOKED_pt.x, 0)), minmax3(HOOKED_pos, vec2(HOOKED_pt.x, 0)), 0);
}
//!DESC Anime4K-v3.2-Upscale-Deblur-DoG-x2-Kernel-Y
//!WHEN OUTPUT.w MAIN.w / 1.200 > OUTPUT.h MAIN.h / 1.200 > *
//!HOOK MAIN
//!BIND HOOKED
//!BIND GAUSS_X2
//!SAVE GAUSS_X2
//!COMPONENTS 3
#define L_tex GAUSS_X2_tex
float max3v(float a, float b, float c) {
return max(max(a, b), c);
}
float min3v(float a, float b, float c) {
return min(min(a, b), c);
}
vec2 minmax3(vec2 pos, vec2 d) {
float a0 = L_tex(pos - d).y;
float b0 = L_tex(pos).y;
float c0 = L_tex(pos + d).y;
float a1 = L_tex(pos - d).z;
float b1 = L_tex(pos).z;
float c1 = L_tex(pos + d).z;
return vec2(min3v(a0, b0, c0), max3v(a1, b1, c1));
}
float lumGaussian7(vec2 pos, vec2 d) {
float g = (L_tex(pos - (d + d)).x + L_tex(pos + (d + d)).x) * 0.06136;
g = g + (L_tex(pos - d).x + L_tex(pos + d).x) * 0.24477;
g = g + (L_tex(pos).x) * 0.38774;
return g;
}
vec4 hook() {
return vec4(lumGaussian7(HOOKED_pos, vec2(0, HOOKED_pt.y)), minmax3(HOOKED_pos, vec2(0, HOOKED_pt.y)), 0);
}
//!DESC Anime4K-v3.2-Upscale-Deblur-DoG-x2-Apply
//!WHEN OUTPUT.w MAIN.w / 1.200 > OUTPUT.h MAIN.h / 1.200 > *
//!HOOK MAIN
//!BIND HOOKED
//!BIND LINELUMA
//!BIND GAUSS_X2
//!WIDTH MAIN.w 2 *
//!HEIGHT MAIN.h 2 *
#define STRENGTH 0.6 //De-blur proportional strength, higher is sharper. However, it is better to tweak BLUR_CURVE instead to avoid ringing.
#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;
#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.
#define NOISE_THRESHOLD 0.001 //Value where curve stops, used to not sharpen noise. Only de-blur values that fall above this threshold.
#define L_tex LINELUMA_tex
vec4 hook() {
float c = (L_tex(HOOKED_pos).x - GAUSS_X2_tex(HOOKED_pos).x) * STRENGTH;
float t_range = BLUR_THRESHOLD - NOISE_THRESHOLD;
float c_t = abs(c);
if (c_t > NOISE_THRESHOLD && c_t < BLUR_THRESHOLD) {
c_t = (c_t - NOISE_THRESHOLD) / t_range;
c_t = pow(c_t, BLUR_CURVE);
c_t = c_t * t_range + NOISE_THRESHOLD;
c_t = c_t * sign(c);
} else {
c_t = c;
}
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;
//This trick is only possible if the inverse Y->RGB matrix has 1 for every row... (which is the case for BT.709)
//Otherwise we would need to convert RGB to YUV, modify Y then convert back to RGB.
return HOOKED_tex(HOOKED_pos) + cc;
}
// MIT License// Copyright (c) 2019-2021 bloc97// All rights reserved.// Permission is hereby granted, free of charge, to any person obtaining a copy// of this software and associated documentation files (the "Software"), to deal// in the Software without restriction, including without limitation the rights// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell// copies of the Software, and to permit persons to whom the Software is// furnished to do so, subject to the following conditions:// The above copyright notice and this permission notice shall be included in all// copies or substantial portions of the Software.// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE// SOFTWARE.//!DESC Anime4K-v3.2-Upscale-Deblur-DoG-x2-Luma//!HOOK MAIN//!BIND HOOKED//!SAVE LINELUMA//!COMPONENTS 1float get_luma(vec4 rgba) { return dot(vec4(0.299, 0.587, 0.114, 0.0), rgba);}vec4 hook() { return vec4(get_luma(HOOKED_tex(HOOKED_pos)), 0.0, 0.0, 0.0);}//!DESC Anime4K-v3.2-Upscale-Deblur-DoG-x2-Kernel-X//!WHEN OUTPUT.w MAIN.w / 1.200 > OUTPUT.h MAIN.h / 1.200 > *//!HOOK MAIN//!BIND HOOKED//!BIND LINELUMA//!SAVE GAUSS_X2//!COMPONENTS 3#define L_tex LINELUMA_texfloat max3v(float a, float b, float c) { return max(max(a, b), c);}float min3v(float a, float b, float c) { return min(min(a, b), c);}vec2 minmax3(vec2 pos, vec2 d) { float a = L_tex(pos - d).x; float b = L_tex(pos).x; float c = L_tex(pos + d).x; return vec2(min3v(a, b, c), max3v(a, b, c));}float lumGaussian7(vec2 pos, vec2 d) { float g = (L_tex(pos - (d + d)).x + L_tex(pos + (d + d)).x) * 0.06136; g = g + (L_tex(pos - d).x + L_tex(pos + d).x) * 0.24477; g = g + (L_tex(pos).x) * 0.38774; return g;}vec4 hook() { return vec4(lumGaussian7(HOOKED_pos, vec2(HOOKED_pt.x, 0)), minmax3(HOOKED_pos, vec2(HOOKED_pt.x, 0)), 0);}//!DESC Anime4K-v3.2-Upscale-Deblur-DoG-x2-Kernel-Y//!WHEN OUTPUT.w MAIN.w / 1.200 > OUTPUT.h MAIN.h / 1.200 > *//!HOOK MAIN//!BIND HOOKED//!BIND GAUSS_X2//!SAVE GAUSS_X2//!COMPONENTS 3#define L_tex GAUSS_X2_texfloat max3v(float a, float b, float c) { return max(max(a, b), c);}float min3v(float a, float b, float c) { return min(min(a, b), c);}vec2 minmax3(vec2 pos, vec2 d) { float a0 = L_tex(pos - d).y; float b0 = L_tex(pos).y; float c0 = L_tex(pos + d).y; float a1 = L_tex(pos - d).z; float b1 = L_tex(pos).z; float c1 = L_tex(pos + d).z; return vec2(min3v(a0, b0, c0), max3v(a1, b1, c1));}float lumGaussian7(vec2 pos, vec2 d) { float g = (L_tex(pos - (d + d)).x + L_tex(pos + (d + d)).x) * 0.06136; g = g + (L_tex(pos - d).x + L_tex(pos + d).x) * 0.24477; g = g + (L_tex(pos).x) * 0.38774; return g;}vec4 hook() { return vec4(lumGaussian7(HOOKED_pos, vec2(0, HOOKED_pt.y)), minmax3(HOOKED_pos, vec2(0, HOOKED_pt.y)), 0);}//!DESC Anime4K-v3.2-Upscale-Deblur-DoG-x2-Apply//!WHEN OUTPUT.w MAIN.w / 1.200 > OUTPUT.h MAIN.h / 1.200 > *//!HOOK MAIN//!BIND HOOKED//!BIND LINELUMA//!BIND GAUSS_X2//!WIDTH MAIN.w 2 *//!HEIGHT MAIN.h 2 *#define STRENGTH 0.6 //De-blur proportional strength, higher is sharper. However, it is better to tweak BLUR_CURVE instead to avoid ringing.#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;#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.#define NOISE_THRESHOLD 0.001 //Value where curve stops, used to not sharpen noise. Only de-blur values that fall above this threshold.#define L_tex LINELUMA_texvec4 hook() { float c = (L_tex(HOOKED_pos).x - GAUSS_X2_tex(HOOKED_pos).x) * STRENGTH; float t_range = BLUR_THRESHOLD - NOISE_THRESHOLD; float c_t = abs(c); if (c_t > NOISE_THRESHOLD && c_t < BLUR_THRESHOLD) { c_t = (c_t - NOISE_THRESHOLD) / t_range; c_t = pow(c_t, BLUR_CURVE); c_t = c_t * t_range + NOISE_THRESHOLD; c_t = c_t * sign(c); } else { c_t = c; } 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; //This trick is only possible if the inverse Y->RGB matrix has 1 for every row... (which is the case for BT.709) //Otherwise we would need to convert RGB to YUV, modify Y then convert back to RGB. return HOOKED_tex(HOOKED_pos) + cc;}mpv/shaders/Anime4K_Upscale_Deblur_Original_x2.glsl
Modified+277 / −277 text lines
// MIT License
// Copyright (c) 2019-2021 bloc97
// All rights reserved.
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//!DESC Anime4K-v3.2-Upscale-Deblur-Original-x2-Luma
//!HOOK MAIN
//!BIND HOOKED
//!SAVE LINELUMA
//!COMPONENTS 1
float get_luma(vec4 rgba) {
return dot(vec4(0.299, 0.587, 0.114, 0.0), rgba);
}
vec4 hook() {
return vec4(get_luma(HOOKED_tex(HOOKED_pos)), 0.0, 0.0, 0.0);
}
//!DESC Anime4K-v3.2-Upscale-Deblur-Original-x2-Kernel-X
//!HOOK MAIN
//!BIND HOOKED
//!BIND LINELUMA
//!SAVE LUMAD
//!WIDTH MAIN.w 2 *
//!HEIGHT MAIN.h 2 *
//!COMPONENTS 2
vec4 hook() {
vec2 d = HOOKED_pt;
//[tl t tr]
//[ l c r]
//[bl b br]
float l = LINELUMA_tex(HOOKED_pos + vec2(-d.x, 0.0)).x;
float c = LINELUMA_tex(HOOKED_pos).x;
float r = LINELUMA_tex(HOOKED_pos + vec2(d.x, 0.0)).x;
//Horizontal Gradient
//[-1 0 1]
//[-2 0 2]
//[-1 0 1]
float xgrad = (-l + r);
//Vertical Gradient
//[-1 -2 -1]
//[ 0 0 0]
//[ 1 2 1]
float ygrad = (l + c + c + r);
//Computes the luminance's gradient
return vec4(xgrad, ygrad, 0.0, 0.0);
}
//!DESC Anime4K-v3.2-Upscale-Deblur-Original-x2-Kernel-Y
//!HOOK MAIN
//!BIND HOOKED
//!BIND LUMAD
//!SAVE LUMAD
//!WIDTH MAIN.w 2 *
//!HEIGHT MAIN.h 2 *
//!COMPONENTS 2
/* --------------------- SETTINGS --------------------- */
//Strength of edge refinement, good values are between 0.2 and 4
#define REFINE_STRENGTH 1.0
/* --- MODIFY THESE SETTINGS BELOW AT YOUR OWN RISK --- */
//Bias of the refinement function, good values are between 0 and 1
#define REFINE_BIAS 0.0
//Polynomial fit obtained by minimizing MSE error on image
#define P5 ( 11.68129591)
#define P4 (-42.46906057)
#define P3 ( 60.28286266)
#define P2 (-41.84451327)
#define P1 ( 14.05517353)
#define P0 (-1.081521930)
/* ----------------- END OF SETTINGS ----------------- */
float power_function(float x) {
float x2 = x * x;
float x3 = x2 * x;
float x4 = x2 * x2;
float x5 = x2 * x3;
return P5*x5 + P4*x4 + P3*x3 + P2*x2 + P1*x + P0;
}
vec4 hook() {
vec2 d = HOOKED_pt;
//[tl t tr]
//[ l cc r]
//[bl b br]
float tx = LUMAD_tex(HOOKED_pos + vec2(0.0, -d.y)).x;
float cx = LUMAD_tex(HOOKED_pos).x;
float bx = LUMAD_tex(HOOKED_pos + vec2(0.0, d.y)).x;
float ty = LUMAD_tex(HOOKED_pos + vec2(0.0, -d.y)).y;
//float cy = LUMAD_tex(HOOKED_pos).y;
float by = LUMAD_tex(HOOKED_pos + vec2(0.0, d.y)).y;
//Horizontal Gradient
//[-1 0 1]
//[-2 0 2]
//[-1 0 1]
float xgrad = (tx + cx + cx + bx);
//Vertical Gradient
//[-1 -2 -1]
//[ 0 0 0]
//[ 1 2 1]
float ygrad = (-ty + by);
//Computes the luminance's gradient
float sobel_norm = clamp(sqrt(xgrad * xgrad + ygrad * ygrad), 0.0, 1.0);
float dval = clamp(power_function(clamp(sobel_norm, 0.0, 1.0)) * REFINE_STRENGTH + REFINE_BIAS, 0.0, 1.0);
return vec4(sobel_norm, dval, 0.0, 0.0);
}
//!DESC Anime4K-v3.2-Upscale-Deblur-Original-x2-Kernel-X
//!HOOK MAIN
//!BIND HOOKED
//!BIND LUMAD
//!SAVE LUMAMM
//!WIDTH MAIN.w 2 *
//!HEIGHT MAIN.h 2 *
//!COMPONENTS 2
vec4 hook() {
vec2 d = HOOKED_pt;
if (LUMAD_tex(HOOKED_pos).y < 0.1) {
return vec4(0.0);
}
//[tl t tr]
//[ l c r]
//[bl b br]
float l = LUMAD_tex(HOOKED_pos + vec2(-d.x, 0.0)).x;
float c = LUMAD_tex(HOOKED_pos).x;
float r = LUMAD_tex(HOOKED_pos + vec2(d.x, 0.0)).x;
//Horizontal Gradient
//[-1 0 1]
//[-2 0 2]
//[-1 0 1]
float xgrad = (-l + r);
//Vertical Gradient
//[-1 -2 -1]
//[ 0 0 0]
//[ 1 2 1]
float ygrad = (l + c + c + r);
return vec4(xgrad, ygrad, 0.0, 0.0);
}
//!DESC Anime4K-v3.2-Upscale-Deblur-Original-x2-Kernel-Y
//!HOOK MAIN
//!BIND HOOKED
//!BIND LUMAD
//!BIND LUMAMM
//!SAVE LUMAMM
//!WIDTH MAIN.w 2 *
//!HEIGHT MAIN.h 2 *
//!COMPONENTS 2
vec4 hook() {
vec2 d = HOOKED_pt;
if (LUMAD_tex(HOOKED_pos).y < 0.1) {
return vec4(0.0);
}
//[tl t tr]
//[ l cc r]
//[bl b br]
float tx = LUMAMM_tex(HOOKED_pos + vec2(0.0, -d.y)).x;
float cx = LUMAMM_tex(HOOKED_pos).x;
float bx = LUMAMM_tex(HOOKED_pos + vec2(0.0, d.y)).x;
float ty = LUMAMM_tex(HOOKED_pos + vec2(0.0, -d.y)).y;
//float cy = LUMAMM_tex(HOOKED_pos).y;
float by = LUMAMM_tex(HOOKED_pos + vec2(0.0, d.y)).y;
//Horizontal Gradient
//[-1 0 1]
//[-2 0 2]
//[-1 0 1]
float xgrad = (tx + cx + cx + bx);
//Vertical Gradient
//[-1 -2 -1]
//[ 0 0 0]
//[ 1 2 1]
float ygrad = (-ty + by);
float norm = sqrt(xgrad * xgrad + ygrad * ygrad);
if (norm <= 0.001) {
xgrad = 0.0;
ygrad = 0.0;
norm = 1.0;
}
return vec4(xgrad/norm, ygrad/norm, 0.0, 0.0);
}
//!DESC Anime4K-v3.2-Upscale-Deblur-Original-x2-Apply
//!HOOK MAIN
//!BIND HOOKED
//!BIND LUMAD
//!BIND LUMAMM
//!WIDTH MAIN.w 2 *
//!HEIGHT MAIN.h 2 *
vec4 hook() {
vec2 d = HOOKED_pt;
float dval = LUMAD_tex(HOOKED_pos).y;
if (dval < 0.1) {
return HOOKED_tex(HOOKED_pos);
}
vec4 dc = LUMAMM_tex(HOOKED_pos);
if (abs(dc.x + dc.y) <= 0.0001) {
return HOOKED_tex(HOOKED_pos);
}
float xpos = -sign(dc.x);
float ypos = -sign(dc.y);
vec4 xval = HOOKED_tex(HOOKED_pos + vec2(d.x * xpos, 0.0));
vec4 yval = HOOKED_tex(HOOKED_pos + vec2(0.0, d.y * ypos));
float xyratio = abs(dc.x) / (abs(dc.x) + abs(dc.y));
vec4 avg = xyratio * xval + (1.0 - xyratio) * yval;
return avg * dval + HOOKED_tex(HOOKED_pos) * (1.0 - dval);
}
// MIT License// Copyright (c) 2019-2021 bloc97// All rights reserved.// Permission is hereby granted, free of charge, to any person obtaining a copy// of this software and associated documentation files (the "Software"), to deal// in the Software without restriction, including without limitation the rights// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell// copies of the Software, and to permit persons to whom the Software is// furnished to do so, subject to the following conditions:// The above copyright notice and this permission notice shall be included in all// copies or substantial portions of the Software.// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE// SOFTWARE.//!DESC Anime4K-v3.2-Upscale-Deblur-Original-x2-Luma//!HOOK MAIN//!BIND HOOKED//!SAVE LINELUMA//!COMPONENTS 1float get_luma(vec4 rgba) { return dot(vec4(0.299, 0.587, 0.114, 0.0), rgba);}vec4 hook() { return vec4(get_luma(HOOKED_tex(HOOKED_pos)), 0.0, 0.0, 0.0);}//!DESC Anime4K-v3.2-Upscale-Deblur-Original-x2-Kernel-X//!HOOK MAIN//!BIND HOOKED//!BIND LINELUMA//!SAVE LUMAD//!WIDTH MAIN.w 2 *//!HEIGHT MAIN.h 2 *//!COMPONENTS 2vec4 hook() { vec2 d = HOOKED_pt; //[tl t tr] //[ l c r] //[bl b br] float l = LINELUMA_tex(HOOKED_pos + vec2(-d.x, 0.0)).x; float c = LINELUMA_tex(HOOKED_pos).x; float r = LINELUMA_tex(HOOKED_pos + vec2(d.x, 0.0)).x; //Horizontal Gradient //[-1 0 1] //[-2 0 2] //[-1 0 1] float xgrad = (-l + r); //Vertical Gradient //[-1 -2 -1] //[ 0 0 0] //[ 1 2 1] float ygrad = (l + c + c + r); //Computes the luminance's gradient return vec4(xgrad, ygrad, 0.0, 0.0);}//!DESC Anime4K-v3.2-Upscale-Deblur-Original-x2-Kernel-Y//!HOOK MAIN//!BIND HOOKED//!BIND LUMAD//!SAVE LUMAD//!WIDTH MAIN.w 2 *//!HEIGHT MAIN.h 2 *//!COMPONENTS 2/* --------------------- SETTINGS --------------------- *///Strength of edge refinement, good values are between 0.2 and 4#define REFINE_STRENGTH 1.0/* --- MODIFY THESE SETTINGS BELOW AT YOUR OWN RISK --- *///Bias of the refinement function, good values are between 0 and 1#define REFINE_BIAS 0.0//Polynomial fit obtained by minimizing MSE error on image#define P5 ( 11.68129591)#define P4 (-42.46906057)#define P3 ( 60.28286266)#define P2 (-41.84451327)#define P1 ( 14.05517353)#define P0 (-1.081521930)/* ----------------- END OF SETTINGS ----------------- */float power_function(float x) { float x2 = x * x; float x3 = x2 * x; float x4 = x2 * x2; float x5 = x2 * x3; return P5*x5 + P4*x4 + P3*x3 + P2*x2 + P1*x + P0;}vec4 hook() { vec2 d = HOOKED_pt; //[tl t tr] //[ l cc r] //[bl b br] float tx = LUMAD_tex(HOOKED_pos + vec2(0.0, -d.y)).x; float cx = LUMAD_tex(HOOKED_pos).x; float bx = LUMAD_tex(HOOKED_pos + vec2(0.0, d.y)).x; float ty = LUMAD_tex(HOOKED_pos + vec2(0.0, -d.y)).y; //float cy = LUMAD_tex(HOOKED_pos).y; float by = LUMAD_tex(HOOKED_pos + vec2(0.0, d.y)).y; //Horizontal Gradient //[-1 0 1] //[-2 0 2] //[-1 0 1] float xgrad = (tx + cx + cx + bx); //Vertical Gradient //[-1 -2 -1] //[ 0 0 0] //[ 1 2 1] float ygrad = (-ty + by); //Computes the luminance's gradient float sobel_norm = clamp(sqrt(xgrad * xgrad + ygrad * ygrad), 0.0, 1.0); float dval = clamp(power_function(clamp(sobel_norm, 0.0, 1.0)) * REFINE_STRENGTH + REFINE_BIAS, 0.0, 1.0); return vec4(sobel_norm, dval, 0.0, 0.0);}//!DESC Anime4K-v3.2-Upscale-Deblur-Original-x2-Kernel-X//!HOOK MAIN//!BIND HOOKED//!BIND LUMAD//!SAVE LUMAMM//!WIDTH MAIN.w 2 *//!HEIGHT MAIN.h 2 *//!COMPONENTS 2vec4 hook() { vec2 d = HOOKED_pt; if (LUMAD_tex(HOOKED_pos).y < 0.1) { return vec4(0.0); } //[tl t tr] //[ l c r] //[bl b br] float l = LUMAD_tex(HOOKED_pos + vec2(-d.x, 0.0)).x; float c = LUMAD_tex(HOOKED_pos).x; float r = LUMAD_tex(HOOKED_pos + vec2(d.x, 0.0)).x; //Horizontal Gradient //[-1 0 1] //[-2 0 2] //[-1 0 1] float xgrad = (-l + r); //Vertical Gradient //[-1 -2 -1] //[ 0 0 0] //[ 1 2 1] float ygrad = (l + c + c + r); return vec4(xgrad, ygrad, 0.0, 0.0);}//!DESC Anime4K-v3.2-Upscale-Deblur-Original-x2-Kernel-Y//!HOOK MAIN//!BIND HOOKED//!BIND LUMAD//!BIND LUMAMM//!SAVE LUMAMM//!WIDTH MAIN.w 2 *//!HEIGHT MAIN.h 2 *//!COMPONENTS 2vec4 hook() { vec2 d = HOOKED_pt; if (LUMAD_tex(HOOKED_pos).y < 0.1) { return vec4(0.0); } //[tl t tr] //[ l cc r] //[bl b br] float tx = LUMAMM_tex(HOOKED_pos + vec2(0.0, -d.y)).x; float cx = LUMAMM_tex(HOOKED_pos).x; float bx = LUMAMM_tex(HOOKED_pos + vec2(0.0, d.y)).x; float ty = LUMAMM_tex(HOOKED_pos + vec2(0.0, -d.y)).y; //float cy = LUMAMM_tex(HOOKED_pos).y; float by = LUMAMM_tex(HOOKED_pos + vec2(0.0, d.y)).y; //Horizontal Gradient //[-1 0 1] //[-2 0 2] //[-1 0 1] float xgrad = (tx + cx + cx + bx); //Vertical Gradient //[-1 -2 -1] //[ 0 0 0] //[ 1 2 1] float ygrad = (-ty + by); float norm = sqrt(xgrad * xgrad + ygrad * ygrad); if (norm <= 0.001) { xgrad = 0.0; ygrad = 0.0; norm = 1.0; } return vec4(xgrad/norm, ygrad/norm, 0.0, 0.0);}//!DESC Anime4K-v3.2-Upscale-Deblur-Original-x2-Apply//!HOOK MAIN//!BIND HOOKED//!BIND LUMAD//!BIND LUMAMM//!WIDTH MAIN.w 2 *//!HEIGHT MAIN.h 2 *vec4 hook() { vec2 d = HOOKED_pt; float dval = LUMAD_tex(HOOKED_pos).y; if (dval < 0.1) { return HOOKED_tex(HOOKED_pos); } vec4 dc = LUMAMM_tex(HOOKED_pos); if (abs(dc.x + dc.y) <= 0.0001) { return HOOKED_tex(HOOKED_pos); } float xpos = -sign(dc.x); float ypos = -sign(dc.y); vec4 xval = HOOKED_tex(HOOKED_pos + vec2(d.x * xpos, 0.0)); vec4 yval = HOOKED_tex(HOOKED_pos + vec2(0.0, d.y * ypos)); float xyratio = abs(dc.x) / (abs(dc.x) + abs(dc.y)); vec4 avg = xyratio * xval + (1.0 - xyratio) * yval; return avg * dval + HOOKED_tex(HOOKED_pos) * (1.0 - dval);}mpv/shaders/Anime4K_Upscale_DoG_x2.glsl
Modified+143 / −143 text lines
// MIT License
// Copyright (c) 2019-2021 bloc97
// All rights reserved.
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//!DESC Anime4K-v3.2-Upscale-DoG-x2-Luma
//!HOOK MAIN
//!BIND HOOKED
//!SAVE LINELUMA
//!COMPONENTS 1
float get_luma(vec4 rgba) {
return dot(vec4(0.299, 0.587, 0.114, 0.0), rgba);
}
vec4 hook() {
return vec4(get_luma(HOOKED_tex(HOOKED_pos)), 0.0, 0.0, 0.0);
}
//!DESC Anime4K-v3.2-Upscale-DoG-x2-Kernel-X
//!WHEN OUTPUT.w MAIN.w / 1.200 > OUTPUT.h MAIN.h / 1.200 > *
//!HOOK MAIN
//!BIND HOOKED
//!BIND LINELUMA
//!SAVE GAUSS_X2
//!COMPONENTS 3
#define L_tex LINELUMA_tex
float max3v(float a, float b, float c) {
return max(max(a, b), c);
}
float min3v(float a, float b, float c) {
return min(min(a, b), c);
}
vec2 minmax3(vec2 pos, vec2 d) {
float a = L_tex(pos - d).x;
float b = L_tex(pos).x;
float c = L_tex(pos + d).x;
return vec2(min3v(a, b, c), max3v(a, b, c));
}
float lumGaussian7(vec2 pos, vec2 d) {
float g = (L_tex(pos - (d + d)).x + L_tex(pos + (d + d)).x) * 0.06136;
g = g + (L_tex(pos - d).x + L_tex(pos + d).x) * 0.24477;
g = g + (L_tex(pos).x) * 0.38774;
return g;
}
vec4 hook() {
return vec4(lumGaussian7(HOOKED_pos, vec2(HOOKED_pt.x, 0)), minmax3(HOOKED_pos, vec2(HOOKED_pt.x, 0)), 0);
}
//!DESC Anime4K-v3.2-Upscale-DoG-x2-Kernel-Y
//!WHEN OUTPUT.w MAIN.w / 1.200 > OUTPUT.h MAIN.h / 1.200 > *
//!HOOK MAIN
//!BIND HOOKED
//!BIND GAUSS_X2
//!SAVE GAUSS_X2
//!COMPONENTS 3
#define L_tex GAUSS_X2_tex
float max3v(float a, float b, float c) {
return max(max(a, b), c);
}
float min3v(float a, float b, float c) {
return min(min(a, b), c);
}
vec2 minmax3(vec2 pos, vec2 d) {
float a0 = L_tex(pos - d).y;
float b0 = L_tex(pos).y;
float c0 = L_tex(pos + d).y;
float a1 = L_tex(pos - d).z;
float b1 = L_tex(pos).z;
float c1 = L_tex(pos + d).z;
return vec2(min3v(a0, b0, c0), max3v(a1, b1, c1));
}
float lumGaussian7(vec2 pos, vec2 d) {
float g = (L_tex(pos - (d + d)).x + L_tex(pos + (d + d)).x) * 0.06136;
g = g + (L_tex(pos - d).x + L_tex(pos + d).x) * 0.24477;
g = g + (L_tex(pos).x) * 0.38774;
return g;
}
vec4 hook() {
return vec4(lumGaussian7(HOOKED_pos, vec2(0, HOOKED_pt.y)), minmax3(HOOKED_pos, vec2(0, HOOKED_pt.y)), 0);
}
//!DESC Anime4K-v3.2-Upscale-DoG-x2-Apply
//!WHEN OUTPUT.w MAIN.w / 1.200 > OUTPUT.h MAIN.h / 1.200 > *
//!HOOK MAIN
//!BIND HOOKED
//!BIND LINELUMA
//!BIND GAUSS_X2
//!WIDTH MAIN.w 2 *
//!HEIGHT MAIN.h 2 *
#define STRENGTH 0.8 //De-blur proportional strength, higher is sharper.
#define L_tex LINELUMA_tex
vec4 hook() {
float c = (L_tex(HOOKED_pos).x - GAUSS_X2_tex(HOOKED_pos).x) * STRENGTH;
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;
//This trick is only possible if the inverse Y->RGB matrix has 1 for every row... (which is the case for BT.709)
//Otherwise we would need to convert RGB to YUV, modify Y then convert back to RGB.
return HOOKED_tex(HOOKED_pos) + cc;
}
// MIT License// Copyright (c) 2019-2021 bloc97// All rights reserved.// Permission is hereby granted, free of charge, to any person obtaining a copy// of this software and associated documentation files (the "Software"), to deal// in the Software without restriction, including without limitation the rights// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell// copies of the Software, and to permit persons to whom the Software is// furnished to do so, subject to the following conditions:// The above copyright notice and this permission notice shall be included in all// copies or substantial portions of the Software.// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE// SOFTWARE.//!DESC Anime4K-v3.2-Upscale-DoG-x2-Luma//!HOOK MAIN//!BIND HOOKED//!SAVE LINELUMA//!COMPONENTS 1float get_luma(vec4 rgba) { return dot(vec4(0.299, 0.587, 0.114, 0.0), rgba);}vec4 hook() { return vec4(get_luma(HOOKED_tex(HOOKED_pos)), 0.0, 0.0, 0.0);}//!DESC Anime4K-v3.2-Upscale-DoG-x2-Kernel-X//!WHEN OUTPUT.w MAIN.w / 1.200 > OUTPUT.h MAIN.h / 1.200 > *//!HOOK MAIN//!BIND HOOKED//!BIND LINELUMA//!SAVE GAUSS_X2//!COMPONENTS 3#define L_tex LINELUMA_texfloat max3v(float a, float b, float c) { return max(max(a, b), c);}float min3v(float a, float b, float c) { return min(min(a, b), c);}vec2 minmax3(vec2 pos, vec2 d) { float a = L_tex(pos - d).x; float b = L_tex(pos).x; float c = L_tex(pos + d).x; return vec2(min3v(a, b, c), max3v(a, b, c));}float lumGaussian7(vec2 pos, vec2 d) { float g = (L_tex(pos - (d + d)).x + L_tex(pos + (d + d)).x) * 0.06136; g = g + (L_tex(pos - d).x + L_tex(pos + d).x) * 0.24477; g = g + (L_tex(pos).x) * 0.38774; return g;}vec4 hook() { return vec4(lumGaussian7(HOOKED_pos, vec2(HOOKED_pt.x, 0)), minmax3(HOOKED_pos, vec2(HOOKED_pt.x, 0)), 0);}//!DESC Anime4K-v3.2-Upscale-DoG-x2-Kernel-Y//!WHEN OUTPUT.w MAIN.w / 1.200 > OUTPUT.h MAIN.h / 1.200 > *//!HOOK MAIN//!BIND HOOKED//!BIND GAUSS_X2//!SAVE GAUSS_X2//!COMPONENTS 3#define L_tex GAUSS_X2_texfloat max3v(float a, float b, float c) { return max(max(a, b), c);}float min3v(float a, float b, float c) { return min(min(a, b), c);}vec2 minmax3(vec2 pos, vec2 d) { float a0 = L_tex(pos - d).y; float b0 = L_tex(pos).y; float c0 = L_tex(pos + d).y; float a1 = L_tex(pos - d).z; float b1 = L_tex(pos).z; float c1 = L_tex(pos + d).z; return vec2(min3v(a0, b0, c0), max3v(a1, b1, c1));}float lumGaussian7(vec2 pos, vec2 d) { float g = (L_tex(pos - (d + d)).x + L_tex(pos + (d + d)).x) * 0.06136; g = g + (L_tex(pos - d).x + L_tex(pos + d).x) * 0.24477; g = g + (L_tex(pos).x) * 0.38774; return g;}vec4 hook() { return vec4(lumGaussian7(HOOKED_pos, vec2(0, HOOKED_pt.y)), minmax3(HOOKED_pos, vec2(0, HOOKED_pt.y)), 0);}//!DESC Anime4K-v3.2-Upscale-DoG-x2-Apply//!WHEN OUTPUT.w MAIN.w / 1.200 > OUTPUT.h MAIN.h / 1.200 > *//!HOOK MAIN//!BIND HOOKED//!BIND LINELUMA//!BIND GAUSS_X2//!WIDTH MAIN.w 2 *//!HEIGHT MAIN.h 2 *#define STRENGTH 0.8 //De-blur proportional strength, higher is sharper.#define L_tex LINELUMA_texvec4 hook() { float c = (L_tex(HOOKED_pos).x - GAUSS_X2_tex(HOOKED_pos).x) * STRENGTH; 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; //This trick is only possible if the inverse Y->RGB matrix has 1 for every row... (which is the case for BT.709) //Otherwise we would need to convert RGB to YUV, modify Y then convert back to RGB. return HOOKED_tex(HOOKED_pos) + cc;}mpv/shaders/Anime4K_Upscale_Original_x2.glsl
Modified+277 / −277 text lines
// MIT License
// Copyright (c) 2019-2021 bloc97
// All rights reserved.
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//!DESC Anime4K-v3.2-Upscale-Original-x2-Luma
//!HOOK MAIN
//!BIND HOOKED
//!SAVE LINELUMA
//!COMPONENTS 1
float get_luma(vec4 rgba) {
return dot(vec4(0.299, 0.587, 0.114, 0.0), rgba);
}
vec4 hook() {
return vec4(get_luma(HOOKED_tex(HOOKED_pos)), 0.0, 0.0, 0.0);
}
//!DESC Anime4K-v3.2-Upscale-Original-x2-Kernel-X
//!HOOK MAIN
//!BIND HOOKED
//!BIND LINELUMA
//!SAVE LUMAD
//!WIDTH MAIN.w 2 *
//!HEIGHT MAIN.h 2 *
//!COMPONENTS 2
vec4 hook() {
vec2 d = HOOKED_pt;
//[tl t tr]
//[ l c r]
//[bl b br]
float l = LINELUMA_tex(HOOKED_pos + vec2(-d.x, 0.0)).x;
float c = LINELUMA_tex(HOOKED_pos).x;
float r = LINELUMA_tex(HOOKED_pos + vec2(d.x, 0.0)).x;
//Horizontal Gradient
//[-1 0 1]
//[-2 0 2]
//[-1 0 1]
float xgrad = (-l + r);
//Vertical Gradient
//[-1 -2 -1]
//[ 0 0 0]
//[ 1 2 1]
float ygrad = (l + c + c + r);
//Computes the luminance's gradient
return vec4(xgrad, ygrad, 0.0, 0.0);
}
//!DESC Anime4K-v3.2-Upscale-Original-x2-Kernel-Y
//!HOOK MAIN
//!BIND HOOKED
//!BIND LUMAD
//!SAVE LUMAD
//!WIDTH MAIN.w 2 *
//!HEIGHT MAIN.h 2 *
//!COMPONENTS 2
/* --------------------- SETTINGS --------------------- */
//Strength of edge refinement, good values are between 0.2 and 4
#define REFINE_STRENGTH 0.5
/* --- MODIFY THESE SETTINGS BELOW AT YOUR OWN RISK --- */
//Bias of the refinement function, good values are between 0 and 1
#define REFINE_BIAS 0.0
//Polynomial fit obtained by minimizing MSE error on image
#define P5 ( 11.68129591)
#define P4 (-42.46906057)
#define P3 ( 60.28286266)
#define P2 (-41.84451327)
#define P1 ( 14.05517353)
#define P0 (-1.081521930)
/* ----------------- END OF SETTINGS ----------------- */
float power_function(float x) {
float x2 = x * x;
float x3 = x2 * x;
float x4 = x2 * x2;
float x5 = x2 * x3;
return P5*x5 + P4*x4 + P3*x3 + P2*x2 + P1*x + P0;
}
vec4 hook() {
vec2 d = HOOKED_pt;
//[tl t tr]
//[ l cc r]
//[bl b br]
float tx = LUMAD_tex(HOOKED_pos + vec2(0.0, -d.y)).x;
float cx = LUMAD_tex(HOOKED_pos).x;
float bx = LUMAD_tex(HOOKED_pos + vec2(0.0, d.y)).x;
float ty = LUMAD_tex(HOOKED_pos + vec2(0.0, -d.y)).y;
//float cy = LUMAD_tex(HOOKED_pos).y;
float by = LUMAD_tex(HOOKED_pos + vec2(0.0, d.y)).y;
//Horizontal Gradient
//[-1 0 1]
//[-2 0 2]
//[-1 0 1]
float xgrad = (tx + cx + cx + bx);
//Vertical Gradient
//[-1 -2 -1]
//[ 0 0 0]
//[ 1 2 1]
float ygrad = (-ty + by);
//Computes the luminance's gradient
float sobel_norm = clamp(sqrt(xgrad * xgrad + ygrad * ygrad), 0.0, 1.0);
float dval = clamp(power_function(clamp(sobel_norm, 0.0, 1.0)) * REFINE_STRENGTH + REFINE_BIAS, 0.0, 1.0);
return vec4(sobel_norm, dval, 0.0, 0.0);
}
//!DESC Anime4K-v3.2-Upscale-Original-x2-Kernel-X
//!HOOK MAIN
//!BIND HOOKED
//!BIND LUMAD
//!SAVE LUMAMM
//!WIDTH MAIN.w 2 *
//!HEIGHT MAIN.h 2 *
//!COMPONENTS 2
vec4 hook() {
vec2 d = HOOKED_pt;
if (LUMAD_tex(HOOKED_pos).y < 0.1) {
return vec4(0.0);
}
//[tl t tr]
//[ l c r]
//[bl b br]
float l = LUMAD_tex(HOOKED_pos + vec2(-d.x, 0.0)).x;
float c = LUMAD_tex(HOOKED_pos).x;
float r = LUMAD_tex(HOOKED_pos + vec2(d.x, 0.0)).x;
//Horizontal Gradient
//[-1 0 1]
//[-2 0 2]
//[-1 0 1]
float xgrad = (-l + r);
//Vertical Gradient
//[-1 -2 -1]
//[ 0 0 0]
//[ 1 2 1]
float ygrad = (l + c + c + r);
return vec4(xgrad, ygrad, 0.0, 0.0);
}
//!DESC Anime4K-v3.2-Upscale-Original-x2-Kernel-Y
//!HOOK MAIN
//!BIND HOOKED
//!BIND LUMAD
//!BIND LUMAMM
//!SAVE LUMAMM
//!WIDTH MAIN.w 2 *
//!HEIGHT MAIN.h 2 *
//!COMPONENTS 2
vec4 hook() {
vec2 d = HOOKED_pt;
if (LUMAD_tex(HOOKED_pos).y < 0.1) {
return vec4(0.0);
}
//[tl t tr]
//[ l cc r]
//[bl b br]
float tx = LUMAMM_tex(HOOKED_pos + vec2(0.0, -d.y)).x;
float cx = LUMAMM_tex(HOOKED_pos).x;
float bx = LUMAMM_tex(HOOKED_pos + vec2(0.0, d.y)).x;
float ty = LUMAMM_tex(HOOKED_pos + vec2(0.0, -d.y)).y;
//float cy = LUMAMM_tex(HOOKED_pos).y;
float by = LUMAMM_tex(HOOKED_pos + vec2(0.0, d.y)).y;
//Horizontal Gradient
//[-1 0 1]
//[-2 0 2]
//[-1 0 1]
float xgrad = (tx + cx + cx + bx);
//Vertical Gradient
//[-1 -2 -1]
//[ 0 0 0]
//[ 1 2 1]
float ygrad = (-ty + by);
float norm = sqrt(xgrad * xgrad + ygrad * ygrad);
if (norm <= 0.001) {
xgrad = 0.0;
ygrad = 0.0;
norm = 1.0;
}
return vec4(xgrad/norm, ygrad/norm, 0.0, 0.0);
}
//!DESC Anime4K-v3.2-Upscale-Original-x2-Apply
//!HOOK MAIN
//!BIND HOOKED
//!BIND LUMAD
//!BIND LUMAMM
//!WIDTH MAIN.w 2 *
//!HEIGHT MAIN.h 2 *
vec4 hook() {
vec2 d = HOOKED_pt;
float dval = LUMAD_tex(HOOKED_pos).y;
if (dval < 0.1) {
return HOOKED_tex(HOOKED_pos);
}
vec4 dc = LUMAMM_tex(HOOKED_pos);
if (abs(dc.x + dc.y) <= 0.0001) {
return HOOKED_tex(HOOKED_pos);
}
float xpos = -sign(dc.x);
float ypos = -sign(dc.y);
vec4 xval = HOOKED_tex(HOOKED_pos + vec2(d.x * xpos, 0.0));
vec4 yval = HOOKED_tex(HOOKED_pos + vec2(0.0, d.y * ypos));
float xyratio = abs(dc.x) / (abs(dc.x) + abs(dc.y));
vec4 avg = xyratio * xval + (1.0 - xyratio) * yval;
return avg * dval + HOOKED_tex(HOOKED_pos) * (1.0 - dval);
}
// MIT License// Copyright (c) 2019-2021 bloc97// All rights reserved.// Permission is hereby granted, free of charge, to any person obtaining a copy// of this software and associated documentation files (the "Software"), to deal// in the Software without restriction, including without limitation the rights// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell// copies of the Software, and to permit persons to whom the Software is// furnished to do so, subject to the following conditions:// The above copyright notice and this permission notice shall be included in all// copies or substantial portions of the Software.// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE// SOFTWARE.//!DESC Anime4K-v3.2-Upscale-Original-x2-Luma//!HOOK MAIN//!BIND HOOKED//!SAVE LINELUMA//!COMPONENTS 1float get_luma(vec4 rgba) { return dot(vec4(0.299, 0.587, 0.114, 0.0), rgba);}vec4 hook() { return vec4(get_luma(HOOKED_tex(HOOKED_pos)), 0.0, 0.0, 0.0);}//!DESC Anime4K-v3.2-Upscale-Original-x2-Kernel-X//!HOOK MAIN//!BIND HOOKED//!BIND LINELUMA//!SAVE LUMAD//!WIDTH MAIN.w 2 *//!HEIGHT MAIN.h 2 *//!COMPONENTS 2vec4 hook() { vec2 d = HOOKED_pt; //[tl t tr] //[ l c r] //[bl b br] float l = LINELUMA_tex(HOOKED_pos + vec2(-d.x, 0.0)).x; float c = LINELUMA_tex(HOOKED_pos).x; float r = LINELUMA_tex(HOOKED_pos + vec2(d.x, 0.0)).x; //Horizontal Gradient //[-1 0 1] //[-2 0 2] //[-1 0 1] float xgrad = (-l + r); //Vertical Gradient //[-1 -2 -1] //[ 0 0 0] //[ 1 2 1] float ygrad = (l + c + c + r); //Computes the luminance's gradient return vec4(xgrad, ygrad, 0.0, 0.0);}//!DESC Anime4K-v3.2-Upscale-Original-x2-Kernel-Y//!HOOK MAIN//!BIND HOOKED//!BIND LUMAD//!SAVE LUMAD//!WIDTH MAIN.w 2 *//!HEIGHT MAIN.h 2 *//!COMPONENTS 2/* --------------------- SETTINGS --------------------- *///Strength of edge refinement, good values are between 0.2 and 4#define REFINE_STRENGTH 0.5/* --- MODIFY THESE SETTINGS BELOW AT YOUR OWN RISK --- *///Bias of the refinement function, good values are between 0 and 1#define REFINE_BIAS 0.0//Polynomial fit obtained by minimizing MSE error on image#define P5 ( 11.68129591)#define P4 (-42.46906057)#define P3 ( 60.28286266)#define P2 (-41.84451327)#define P1 ( 14.05517353)#define P0 (-1.081521930)/* ----------------- END OF SETTINGS ----------------- */float power_function(float x) { float x2 = x * x; float x3 = x2 * x; float x4 = x2 * x2; float x5 = x2 * x3; return P5*x5 + P4*x4 + P3*x3 + P2*x2 + P1*x + P0;}vec4 hook() { vec2 d = HOOKED_pt; //[tl t tr] //[ l cc r] //[bl b br] float tx = LUMAD_tex(HOOKED_pos + vec2(0.0, -d.y)).x; float cx = LUMAD_tex(HOOKED_pos).x; float bx = LUMAD_tex(HOOKED_pos + vec2(0.0, d.y)).x; float ty = LUMAD_tex(HOOKED_pos + vec2(0.0, -d.y)).y; //float cy = LUMAD_tex(HOOKED_pos).y; float by = LUMAD_tex(HOOKED_pos + vec2(0.0, d.y)).y; //Horizontal Gradient //[-1 0 1] //[-2 0 2] //[-1 0 1] float xgrad = (tx + cx + cx + bx); //Vertical Gradient //[-1 -2 -1] //[ 0 0 0] //[ 1 2 1] float ygrad = (-ty + by); //Computes the luminance's gradient float sobel_norm = clamp(sqrt(xgrad * xgrad + ygrad * ygrad), 0.0, 1.0); float dval = clamp(power_function(clamp(sobel_norm, 0.0, 1.0)) * REFINE_STRENGTH + REFINE_BIAS, 0.0, 1.0); return vec4(sobel_norm, dval, 0.0, 0.0);}//!DESC Anime4K-v3.2-Upscale-Original-x2-Kernel-X//!HOOK MAIN//!BIND HOOKED//!BIND LUMAD//!SAVE LUMAMM//!WIDTH MAIN.w 2 *//!HEIGHT MAIN.h 2 *//!COMPONENTS 2vec4 hook() { vec2 d = HOOKED_pt; if (LUMAD_tex(HOOKED_pos).y < 0.1) { return vec4(0.0); } //[tl t tr] //[ l c r] //[bl b br] float l = LUMAD_tex(HOOKED_pos + vec2(-d.x, 0.0)).x; float c = LUMAD_tex(HOOKED_pos).x; float r = LUMAD_tex(HOOKED_pos + vec2(d.x, 0.0)).x; //Horizontal Gradient //[-1 0 1] //[-2 0 2] //[-1 0 1] float xgrad = (-l + r); //Vertical Gradient //[-1 -2 -1] //[ 0 0 0] //[ 1 2 1] float ygrad = (l + c + c + r); return vec4(xgrad, ygrad, 0.0, 0.0);}//!DESC Anime4K-v3.2-Upscale-Original-x2-Kernel-Y//!HOOK MAIN//!BIND HOOKED//!BIND LUMAD//!BIND LUMAMM//!SAVE LUMAMM//!WIDTH MAIN.w 2 *//!HEIGHT MAIN.h 2 *//!COMPONENTS 2vec4 hook() { vec2 d = HOOKED_pt; if (LUMAD_tex(HOOKED_pos).y < 0.1) { return vec4(0.0); } //[tl t tr] //[ l cc r] //[bl b br] float tx = LUMAMM_tex(HOOKED_pos + vec2(0.0, -d.y)).x; float cx = LUMAMM_tex(HOOKED_pos).x; float bx = LUMAMM_tex(HOOKED_pos + vec2(0.0, d.y)).x; float ty = LUMAMM_tex(HOOKED_pos + vec2(0.0, -d.y)).y; //float cy = LUMAMM_tex(HOOKED_pos).y; float by = LUMAMM_tex(HOOKED_pos + vec2(0.0, d.y)).y; //Horizontal Gradient //[-1 0 1] //[-2 0 2] //[-1 0 1] float xgrad = (tx + cx + cx + bx); //Vertical Gradient //[-1 -2 -1] //[ 0 0 0] //[ 1 2 1] float ygrad = (-ty + by); float norm = sqrt(xgrad * xgrad + ygrad * ygrad); if (norm <= 0.001) { xgrad = 0.0; ygrad = 0.0; norm = 1.0; } return vec4(xgrad/norm, ygrad/norm, 0.0, 0.0);}//!DESC Anime4K-v3.2-Upscale-Original-x2-Apply//!HOOK MAIN//!BIND HOOKED//!BIND LUMAD//!BIND LUMAMM//!WIDTH MAIN.w 2 *//!HEIGHT MAIN.h 2 *vec4 hook() { vec2 d = HOOKED_pt; float dval = LUMAD_tex(HOOKED_pos).y; if (dval < 0.1) { return HOOKED_tex(HOOKED_pos); } vec4 dc = LUMAMM_tex(HOOKED_pos); if (abs(dc.x + dc.y) <= 0.0001) { return HOOKED_tex(HOOKED_pos); } float xpos = -sign(dc.x); float ypos = -sign(dc.y); vec4 xval = HOOKED_tex(HOOKED_pos + vec2(d.x * xpos, 0.0)); vec4 yval = HOOKED_tex(HOOKED_pos + vec2(0.0, d.y * ypos)); float xyratio = abs(dc.x) / (abs(dc.x) + abs(dc.y)); vec4 avg = xyratio * xval + (1.0 - xyratio) * yval; return avg * dval + HOOKED_tex(HOOKED_pos) * (1.0 - dval);}neovide/config.toml
Modified+4 / −3 text lines
neovim/.editorconfig
Modified+141 / −141 text lines
root = true
# see https://github.com/CppCXY/EmmyLuaCodeStyle
# optional space/tab
indent_style = space
# if indent_style is space, this is valid
indent_size = 2
# if indent_style is tab, this is valid
tab_width = 2
# none/single/double
quote_style = single
continuation_indent = 2
# this mean utf8 length , if this is 'unset' then the line width is no longer checked
# this option decides when to chopdown the code
max_line_length = 120
# optional crlf/lf/cr/auto, if it is 'auto', in windows it is crlf other platforms are lf
# in neovim the value 'auto' is not a valid option, please use 'unset'
end_of_line = lf
# none/ comma / semicolon / only_kv_colon
table_separator_style = comma
#optional keep/never/always/smart
trailing_table_separator = smart
# keep/remove/remove_table_only/remove_string_only
call_arg_parentheses = remove
detect_end_of_line = false
# this will check text end with new line
insert_final_newline = true
# [space]
space_around_table_field_list = true
space_before_attribute = true
space_before_function_open_parenthesis = false
space_before_function_call_open_parenthesis = false
space_before_closure_open_parenthesis = true
# optional always/only_string/only_table/none
# or true/false
space_before_function_call_single_arg = always
space_before_open_square_bracket = false
space_inside_function_call_parentheses = true
space_inside_function_param_list_parentheses = true
space_inside_square_brackets = false
# like t[#t+1] = 1
space_around_table_append_operator = false
ignore_spaces_inside_function_call = false
space_before_inline_comment = 1
# [operator space]
space_around_math_operator = true
space_after_comma = true
space_after_comma_in_for_statement = true
space_around_concat_operator = true
# [align]
align_call_args = true
align_function_params = true
align_continuous_assign_statement = true
align_continuous_rect_table_field = true
align_continuous_line_space = 2
align_if_branch = true
# option none / always / contain_curly/
align_array_table = true
align_continuous_similar_call_args = true
align_continuous_inline_comment = true
# option none / always / only_call_stmt
align_chain_expr = none
# [indent]
never_indent_before_if_condition = false
never_indent_comment_on_if_branch = false
# [line space]
# The following configuration supports four expressions
# keep
# fixed(n)
# min(n)
# max(n)
# for eg. min(2)
line_space_after_if_statement = keep
line_space_after_do_statement = keep
line_space_after_while_statement = keep
line_space_after_repeat_statement = keep
line_space_after_for_statement = keep
line_space_after_local_or_assign_statement = keep
line_space_after_function_statement = fixed(2)
line_space_after_expression_statement = keep
line_space_after_comment = keep
# [line break]
break_all_list_when_line_exceed = false
auto_collapse_lines = false
break_before_braces = false
# [preference]
ignore_space_after_colon = false
remove_call_expression_list_finish_comma = false
root = true# see https://github.com/CppCXY/EmmyLuaCodeStyle# optional space/tabindent_style = space# if indent_style is space, this is validindent_size = 2# if indent_style is tab, this is validtab_width = 2# none/single/doublequote_style = singlecontinuation_indent = 2# this mean utf8 length , if this is 'unset' then the line width is no longer checked# this option decides when to chopdown the codemax_line_length = 120# optional crlf/lf/cr/auto, if it is 'auto', in windows it is crlf other platforms are lf# in neovim the value 'auto' is not a valid option, please use 'unset'end_of_line = lf# none/ comma / semicolon / only_kv_colontable_separator_style = comma#optional keep/never/always/smarttrailing_table_separator = smart# keep/remove/remove_table_only/remove_string_onlycall_arg_parentheses = removedetect_end_of_line = false# this will check text end with new lineinsert_final_newline = true# [space]space_around_table_field_list = truespace_before_attribute = truespace_before_function_open_parenthesis = falsespace_before_function_call_open_parenthesis = falsespace_before_closure_open_parenthesis = true# optional always/only_string/only_table/none# or true/falsespace_before_function_call_single_arg = alwaysspace_before_open_square_bracket = falsespace_inside_function_call_parentheses = truespace_inside_function_param_list_parentheses = truespace_inside_square_brackets = false# like t[#t+1] = 1space_around_table_append_operator = falseignore_spaces_inside_function_call = falsespace_before_inline_comment = 1# [operator space]space_around_math_operator = truespace_after_comma = truespace_after_comma_in_for_statement = truespace_around_concat_operator = true# [align]align_call_args = truealign_function_params = truealign_continuous_assign_statement = truealign_continuous_rect_table_field = truealign_continuous_line_space = 2align_if_branch = true# option none / always / contain_curly/align_array_table = truealign_continuous_similar_call_args = truealign_continuous_inline_comment = true# option none / always / only_call_stmtalign_chain_expr = none# [indent]never_indent_before_if_condition = falsenever_indent_comment_on_if_branch = false# [line space]# The following configuration supports four expressions# keep# fixed(n)# min(n)# max(n)# for eg. min(2)line_space_after_if_statement = keepline_space_after_do_statement = keepline_space_after_while_statement = keepline_space_after_repeat_statement = keepline_space_after_for_statement = keepline_space_after_local_or_assign_statement = keepline_space_after_function_statement = fixed(2)line_space_after_expression_statement = keepline_space_after_comment = keep# [line break]break_all_list_when_line_exceed = falseauto_collapse_lines = falsebreak_before_braces = false# [preference]ignore_space_after_colon = falseremove_call_expression_list_finish_comma = falseneovim/.luarc.json
Addednew file mode 100644+11 / −0 text lines
neovim/.system/MISSION.md
Addednew file mode 100644+4 / −0 text lines
neovim/.system/RULES.md
Addednew file mode 100644+4 / −0 text lines
neovim/.system/SYSTEM.md
Addednew file mode 100644+4 / −0 text lines
neovim/.system/board.json
Addednew file mode 100644+41 / −0 text lines
{ "schemaVersion": 0, "items": { "NVIM-ISSUE-9MP5JYUO": { "state": "done", "updatedAt": "2026-10-02T01:47:18.875Z", "source": "agent", "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." }, "NVIM-ISSUE-INA9RX_F": { "state": "done", "updatedAt": "2026-10-02T01:17:38.217Z", "source": "agent", "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)." }, "NVIM-PLAN-CEJPO_XF": { "state": "done", "updatedAt": "2026-10-02T02:38:40.635Z", "source": "agent", "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." }, "NVIM-PLAN-LAJ8PGRK": { "state": "done", "updatedAt": "2026-10-02T02:38:40.635Z", "source": "agent", "note": "All 7 transcript slices implemented; entry/render/fold/navigate/detail specs pass. Fresh just test: 669 pass, 0 fail/err." }, "NVIM-PLAN-T7XG71CC": { "state": "done", "updatedAt": "2026-10-02T02:38:40.635Z", "source": "agent", "note": "All 7 tool-presentation slices implemented; tool/diff/navigate/render/fold specs pass. Fresh just test: 669 pass, 0 fail/err." }, "NVIM-SPEC-GMWDCMJZ": { "state": "todo", "source": "agent", "updatedAt": "2026-10-02T03:07:41.664Z", "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." } }}neovim/.system/config.json
Addednew file mode 100644+5 / −0 text lines
neovim/.system/issues/NVIM-ISSUE-8I3OSH4M-prompt-accept-auto-steers-diverging-from-explici/index.md
Addednew file mode 100644+47 / −0 text lines
---id: NVIM-ISSUE-8I3OSH4Mtype: issuetitle: Prompt accept auto-steers, diverging from explicit queued deliveryspecs: - NVIM-SPEC-GMWDCMJZ---# Prompt accept auto-steers, diverging from explicit queued delivery## SymptomAccepting 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.## ImpactDiverges from [NVIM-SPEC-GMWDCMJZ](../../specs/NVIM-SPEC-GMWDCMJZ-pivi-native-neovim-integration/index.md), which states:- "While a session run is active, a new submission is queued with an explicit delivery choice and is never silently dropped."- "Queued submissions remain listable and clearable before delivery."- Acceptance: "A submission made during an active run is queued with explicit delivery and can be listed and cleared before delivery."Two gaps against that contract:- Delivery is now implicit for the accept key: pressing accept while working picks steer with no separate choice.- A steer is injected into the active run, so it is neither queued nor listable nor clearable, unlike a follow-up.Nothing 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.## Evidence`lua/bugabinga/pivi/command.lua`, the prompt `send`:- When no delivery is passed and the session is busy, it sets delivery to `steer`.- `<Plug>(pivi-submit)` and `<Plug>(pivi-accept)` call `send()` with no delivery, so the accept key auto-steers during a run.- `<Plug>(pivi-follow-up)` calls `send('follow_up')`, which queues.`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.## ExpectedResolve the divergence one way:- 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- Change the behavior so an accept during a run requires an explicit delivery choice and queues rather than injecting.The 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
Addednew file mode 100644+80 / −0 text lines
---id: NVIM-ISSUE-9MP5JYUOtype: issuetitle: Session status never fetches or publishes model, context, and costspecs: - NVIM-SPEC-GMWDCMJZ---# Session status never fetches or publishes model, context, and cost## SymptomA 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.## ImpactViolates the transport-and-status contract of [NVIM-SPEC-GMWDCMJZ](../../specs/NVIM-SPEC-GMWDCMJZ-pivi-native-neovim-integration/index.md):- "Status also exposes available model, thinking, session, context, usage, and extension-status data."- "Status changes redraw native status surfaces and emit a semantic event."Consumers 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.Scope 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.## GeneralityThe fix must not depend on the reporter's specific Pi extensions.- 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.- 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.- 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.## SurfacePi'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.- 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).- 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.- 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.## EvidenceThe reducers for the two status-bearing RPC responses exist but are never driven:- `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.- `status.reduce_stats` (folds `get_session_stats`: context usage, cost) has no caller at all; it is dead code.- `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.- `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.Net 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.```mermaidsequenceDiagram participant Pi participant session as pivi.session participant status as pivi.status (reducer) participant publish as pivi.publish participant consumer as user statusline Pi-->>session: event stream (agent/tool/queue) session->>status: reduce(event) status->>publish: connection/run/tool/queue only Note over session,status: get_state / get_session_stats never requested Note over status: reduce_state, reduce_stats never called publish-->>consumer: vim.g.pivi without model/context/cost consumer-->>consumer: nothing to show```## Expected- 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.- `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.- Published status is structured per-field data with multi-line widget arrays preserved; the single-line `summary` remains a convenience, not the only output.- Status evaluation still performs no RPC; refreshes are triggered by run lifecycle, not by consumers reading the variable.## Reproduction1. Start a session and submit a prompt that calls a model.2. Inspect `vim.g.pivi.sessions[<name>]` during and after the run.3. 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
Addednew file mode 100644+68 / −0 text lines
---id: NVIM-ISSUE-INA9RX_Ftype: issuetitle: Transcript force-scrolls to bottom on every writespecs: - NVIM-SPEC-GMWDCMJZ---# Transcript force-scrolls to bottom on every write## SymptomIn 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.## ImpactViolates transcript behavior of [NVIM-SPEC-GMWDCMJZ](../../specs/NVIM-SPEC-GMWDCMJZ-pivi-native-neovim-integration/index.md):- Transcript navigation requires moving between entries "with ordinary motions"; the cursor cannot be held off the last line while a run streams.- Follow mode is "optional and disabled unless selected", yet the transcript force-follows unconditionally.- Entry collapse/expand is defeated because the expanded entry is scrolled out of view and the toggle acts on the wrong line.## Evidence`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`:```local follow_windows = function( bufnr ) local last = vim.api.nvim_buf_line_count( bufnr ) for _, win in ipairs( vim.api.nvim_list_wins() ) do if vim.api.nvim_win_get_buf( win ) == bufnr then pcall( vim.api.nvim_win_set_cursor, win, { last, 0, } ) end endend```No guard checks whether a window is already tailing the bottom, so any user navigation is overwritten by the next streamed delta.Expand 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.```mermaidsequenceDiagram participant User participant session participant transcript participant window as transcript window participant fold User->>window: move cursor up / expand entry session->>transcript: append streamed delta transcript->>window: follow_windows -> cursor = last line window-->>User: view jumps to bottom User->>fold: toggle entry at cursor fold->>window: reads cursor (already at last line) window-->>User: wrong entry toggled, scrolled away```## Expected- Auto-follow only when the window is already at the transcript tail; otherwise leave cursor and view untouched.- User navigation holds across streamed writes.- Expanding or collapsing acts on the entry the reader is on and keeps it in view.## Reproduction1. Start a session and submit a prompt that produces a long streamed answer with tool calls.2. While it streams, move the cursor up or expand a collapsed tool entry.3. 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
Addednew file mode 100644+104 / −0 text lines
---id: NVIM-PLAN-CEJPO_XFtype: plantitle: Deliver pivi native Neovim integrationspec: NVIM-SPEC-GMWDCMJZstatus: approved---# Deliver pivi native Neovim integration## IntentDeliver [NVIM-SPEC-GMWDCMJZ](../../specs/NVIM-SPEC-GMWDCMJZ-pivi-native-neovim-integration/index.md) as vertical slices, each observable through Neovim surfaces.Evidence for transport, tool authority, and concurrency comes from [NVIM-RESEARCH-KZYYEFY_](../../research/NVIM-RESEARCH-KZYYEFY_-pi-and-neovim-capabilities-for-pivi/index.md).Placement: 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/`.Module-level testing rules live in that directory's `AGENTS.md`.Publishing state through native variables and `User` events still holds, so other configuration consumes pivi without depending on its internals.## Module map```mermaidflowchart TB command["bugabinga.pivi.command"] --> session["bugabinga.pivi.session"] command --> help["bugabinga.pivi.help"] session --> rpc["bugabinga.pivi.rpc"] session --> status["bugabinga.pivi.status"] status --> publish["bugabinga.pivi.publish"] session --> transcript["bugabinga.pivi.transcript"] session --> context["bugabinga.pivi.context"] session --> dialog["bugabinga.pivi.dialog"] rpc --> extension["companion Pi extension"] extension --> edit["bugabinga.pivi.edit"] edit --> activity["bugabinga.pivi.activity"] activity --> follow["bugabinga.pivi.follow"] help --> rpc```| Module | Responsibility || --- | --- || `bugabinga.pivi.rpc` | Child process lifetime, strict LF JSONL framing, request correlation, deferral out of fast contexts || `bugabinga.pivi.session` | Session identity, working directory, queue delivery, abort, resume, switch || `bugabinga.pivi.status` | Cached semantic state; no RPC during status evaluation || `bugabinga.pivi.publish` | `vim.g` state plus `User` autocmd events with payload data || `bugabinga.pivi.transcript` | Prompt, transcript, and detail buffers || `bugabinga.pivi.context` | Immutable submission snapshots and ambient editor state || `bugabinga.pivi.edit` | Buffer-authoritative mutation, undo coherence, disk visibility || `bugabinga.pivi.activity` | Extmarks, signs, virtual text, diagnostics, quickfix and location lists || `bugabinga.pivi.follow` | Optional viewport following || `bugabinga.pivi.dialog` | Extension UI requests mapped to `vim.ui` surfaces || `bugabinga.pivi.help` | Ephemeral session-less run || `bugabinga.pivi.command` | `:Pi` subcommands, slash-command entry, `<Plug>` mappings || companion extension | Editor tools plus buffer-authoritative operations for built-in Pi tools |## Slice order```mermaidflowchart LR s1["1 Ask and stream"] --> s3["3 Status and events"] s1 --> s2["2 Ephemeral help"] s3 --> s4["4 Session control"] s4 --> s5["5 Submission context"] s5 --> s6["6 Buffer-authoritative reads"] s6 --> s7["7 Native edits"] s7 --> s8["8 Activity and lists"] s7 --> s9["9 Streaming ghost text"] s8 --> s10["10 Follow mode"] s4 --> s11["11 Slash commands"] s4 --> s12["12 Extension dialogs"]```| # | Observable behavior | Modules touched | Verified by || --- | --- | --- | --- || 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 || 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 || 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 || 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 || 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 || 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 || 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 || 8 | Edits leave a navigable trail; findings populate quickfix, location lists, and a distinct diagnostic namespace | `bugabinga.pivi.activity` | Namespace isolation and navigation spec || 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 || 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 || 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 || 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 |Slice 1 is the walking skeleton; every later slice keeps `just test` green before the next begins.## Critical paths- Child output arrives in fast contexts; all editor work defers through scheduling before API calls.- Submission during an active run always chooses steering or follow-up; rejection is never silent.- Help spawns its own session-less child so working-session history, queue, and status remain untouched.- Buffer authority prefers injecting operations into Pi's built-in tools over reimplementing them, because result and detail shapes must match exactly.## Risks| Risk | Slice | Mitigation || --- | --- | --- || Undo join refuses after undo or redo | 7 | Detect refusal and fall back to separate undo blocks rather than losing the edit || Partial tool arguments are invalid JSON | 9 | Treat ghost text as presentation only; mutate solely on complete validated arguments || Tool override breaks rendering or session state | 6, 7 | Keep built-in renderers and detail shapes; override behavior only || Status consumers stall the statusline | 3 | Read cached state only || 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
Addednew file mode 100644+92 / −0 text lines
---id: NVIM-PLAN-LAJ8PGRKtype: plantitle: Deliver pivi transcript presentation and navigationspec: NVIM-SPEC-GMWDCMJZstatus: approveddepends_on: - NVIM-PLAN-CEJPO_XF---# Deliver pivi transcript presentation and navigation## IntentDeliver the transcript presentation and navigation behavior of[NVIM-SPEC-GMWDCMJZ](../../specs/NVIM-SPEC-GMWDCMJZ-pivi-native-neovim-integration/index.md).[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.This plan makes the transcript the conversation document it already is: addressable entries, message text as authored, rendered formatting, and ordinary motion.Placement continues from the earlier plan: `lua/bugabinga/pivi/`, with module-level testing rules in that directory's `AGENTS.md`.Measured constraint, not assumption: a transcript that reparses on every streamed delta costs roughly five hundred times a transcript that lets redraw drive parsing.Presentation must therefore never force parsing per delta.## Module map```mermaidflowchart TB session["bugabinga.pivi.session"] --> entry["bugabinga.pivi.entry"] entry --> transcript["bugabinga.pivi.transcript"] transcript --> render["bugabinga.pivi.render"] entry --> fold["bugabinga.pivi.fold"] entry --> navigate["bugabinga.pivi.navigate"] navigate --> follow["bugabinga.pivi.follow"] navigate --> detail["bugabinga.pivi.detail"] command["bugabinga.pivi.command"] --> navigate command --> fold```| Module | Responsibility || --- | --- || `bugabinga.pivi.entry` | Entry identity, kind, bounds, metadata, and lifecycle over a transcript buffer || `bugabinga.pivi.transcript` | Buffer ownership; message text only, with framing delegated to presentation || `bugabinga.pivi.render` | Formatting, embedded language presentation, and framing decoration || `bugabinga.pivi.fold` | Collapsed and expanded presentation of an entry || `bugabinga.pivi.navigate` | Motion between entries and tool calls, and reaching a referenced location || `bugabinga.pivi.detail` | Detailed inspection of one entry without leaving the transcript || `bugabinga.pivi.session` | Emits entries instead of writing framing text || `bugabinga.pivi.command` | `:Pi` subcommands and `<Plug>` mappings for the new behavior |## Slice order```mermaidflowchart LR s1["1 Addressable entries"] --> s2["2 Pure message text"] s1 --> s3["3 Collapse and expand"] s2 --> s4["4 Rendered formatting"] s1 --> s5["5 Motion between entries"] s5 --> s6["6 Reach a referenced location"] s3 --> s7["7 Detailed inspection"]```| # | Observable behavior | Modules touched | Verified by || --- | --- | --- | --- || 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 || 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 || 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 || 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 || 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 || 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 || 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 |Slice 1 is the walking skeleton; every later slice keeps the whole suite green before the next begins.## Critical paths- Entry bounds must be extmark-backed, because text appended later shifts every fixed line number.- Presentation is driven by redraw, never by a forced parse per streamed delta.- Framing lives in decoration, so the buffer stays copyable message text.- Collapsing is presentation only; the session transcript and Pi history are untouched.- Location navigation reuses follow-mode surfaces rather than introducing a second window policy.## Risks| Risk | Slice | Mitigation || --- | --- | --- || Entry bounds drift as the transcript grows | 1 | Extmark-backed ranges, asserted after appends and after edits to earlier entries || 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 || Rendering cost grows with a long answer | 4 | Assert a streaming budget over a recorded answer; keep parsing redraw-driven || Collapsed entries hide errors the user needs | 3 | Collapse voluminous results only; keep errors expanded || 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
Addednew file mode 100644+103 / −0 text lines
---id: NVIM-PLAN-T7XG71CCtype: plantitle: Deliver pivi tool presentationspec: NVIM-SPEC-GMWDCMJZstatus: approveddepends_on: - NVIM-PLAN-CEJPO_XF - NVIM-PLAN-LAJ8PGRK---# Deliver pivi tool presentation## IntentMake a tool call as legible in Neovim as it is in Pi's own interface, using native surfaces rather than a ported component tree.[NVIM-PLAN-LAJ8PGRK](../NVIM-PLAN-LAJ8PGRK-deliver-pivi-transcript-presentation-and-navigat/index.md) made every tool call an addressable, collapsible entry.That 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.Blocker: the behavior below is not yet in [NVIM-SPEC-GMWDCMJZ](../../specs/NVIM-SPEC-GMWDCMJZ-pivi-native-neovim-integration/index.md).A tool presentation section and its acceptance criteria were drafted and await one-shot approval.This plan is not executable until that amendment lands.## EvidenceRead from the installed Pi 0.85.1 implementation, not from prose.Tool results reach a client unchanged, so everything a tool reports is already on the wire and merely unused.| Tool | What it reports about its own work | When || --- | --- | --- || edit | a display diff, a unified patch, and the first changed line | always || bash | progressive output, truncation, and a full output path | while running, throttled || read | truncation | only when truncated || grep, find, ls | truncation and the limit that was reached | only at a limit || write | nothing | — |Neovim side: no diff parser ships, but diff syntax and the diff highlight groups do, and the theme already defines them.## Module map```mermaidflowchart TB session["bugabinga.pivi.session"] --> tool["bugabinga.pivi.tool"] tool --> entry["bugabinga.pivi.entry"] tool --> render["bugabinga.pivi.render"] render --> fold["bugabinga.pivi.fold"] tool --> diff["bugabinga.pivi.diff"] diff --> command["bugabinga.pivi.command"] tool --> navigate["bugabinga.pivi.navigate"]```| Module | Responsibility || --- | --- || `bugabinga.pivi.tool` | Interprets what a tool reports: outcome, change, progress, language, truncation || `bugabinga.pivi.render` | Presents that interpretation as decoration inside the entry || `bugabinga.pivi.diff` | Editor comparison of a completed change || `bugabinga.pivi.fold` | Collapsed line that still states subject and outcome || `bugabinga.pivi.navigate` | Reaching the first changed line rather than the file start || `bugabinga.pivi.entry` | Carries the interpretation as entry metadata || `bugabinga.pivi.session` | Feeds tool reports in, including while a tool still runs |## Slice order```mermaidflowchart LR s1["1 Outcome after the name"] --> s2["2 Change as a diff"] s1 --> s6["6 Truncation is reachable"] s2 --> s3["3 First changed line"] s2 --> s4["4 Editor comparison"] s1 --> s5["5 Output while running"] s5 --> s7["7 Output in its language"]```| # | Observable behavior | Modules touched | Verified by || --- | --- | --- | --- || 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 || 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 || 3 | Navigating from an edit lands on its first changed line | `bugabinga.pivi.navigate`, `bugabinga.pivi.tool` | Navigation spec over a recorded edit || 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 || 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 || 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 || 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 |Slice 1 is the walking skeleton: it establishes the interpretation every later slice reads.## Critical paths- Interpretation is derived only from what a tool reports; a tool that reports nothing degrades to today's behavior rather than to a guess.- Diff presentation is decoration over reported change text, so the transcript still yields message text when copied.- An editor comparison reconstructs the prior content from the reported change rather than re-reading a file that has already moved on.- Progressive output replaces the tail of its own entry; entry bounds stay extmark-backed and must survive repeated rewrites.- Presentation stays redraw-driven, so a tool that emits output continuously cannot force parsing per update.## Risks| Risk | Slice | Mitigation || --- | --- | --- || Tools differ in what they report | 1 | Interpretation is per tool with a plain fallback, asserted for a tool that reports nothing || Diff decoration drifts from the text it marks | 2 | Anchor decoration to entry-relative rows and assert after later entries are appended || 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 || Frequent progress updates cost too much | 5 | Rewrite only the entry tail, keep parsing redraw-driven, and hold the streaming budget spec || 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
Addednew file mode 100644+144 / −0 text lines
---id: NVIM-RESEARCH-KZYYEFY_type: researchtitle: Pi and Neovim capabilities for pivi---# Pi and Neovim capabilities for pivi## SourcesInstalled documentation only; no remembered API behavior.| Source | Version | Location || --- | --- | --- || Pi docs (`rpc.md`, `extensions.md`, `usage.md`, `sessions.md`, `json.md`) | 0.85.1 | `$PI_CONTEXT_DOCS_PATH` || Neovim runtime docs (`api.txt`, `lua.txt`, `undo.txt`, `editing.txt`, `options.txt`) | 0.12.5 | `$VIMRUNTIME/doc` |## Pi facts### Transport- `pi --mode rpc` speaks JSON commands on stdin, responses and events on stdout.- Strict JSONL, LF only; clients strip a trailing `\r`; Unicode separators must not split records.- Optional `id` on commands correlates responses; most events carry no `id`.- Startup flags relevant to a client: `--provider`, `--model`, `--name`, `--session <path|id>`, `--session-dir`, `--no-session`, `-e <ext>`, `--tools`, `--append-system-prompt`.### Commands that map to pivi surfaces| pivi need | RPC command | Notes || --- | --- | --- || Submit prompt | `prompt` | During streaming requires `streamingBehavior: steer \| followUp`, else error || Queue while running | `steer`, `follow_up`, `clear_queue` | Extension commands rejected here || Stop | `abort`, `abort_retry`, `abort_bash` | `abort` waits for idle || Status | `get_state`, `get_session_stats` | Model, thinking, streaming, queue, context usage || Transcript | `get_messages`, `get_entries`, `get_tree` | `get_entries since` is a durable cursor; `leafId` detects branch moves || Sessions | `new_session`, `switch_session`, `fork`, `clone`, `set_session_name` | Switch/fork cancellable by extensions || Slash commands | `get_commands` | Returns extension, prompt-template, and skill commands; invoked as `/name` through `prompt` || Model/thinking | `set_model`, `cycle_model`, `get_available_models`, `set_thinking_level`, `get_available_thinking_levels` | || Compaction | `compact`, `set_auto_compaction` | |Built-in TUI commands such as `/settings` and `/hotkeys` are absent from `get_commands` and do not execute over RPC.### Concurrency semantics```mermaidstateDiagram-v2 [*] --> Idle Idle --> Streaming: prompt Streaming --> Streaming: steer / follow_up queued Streaming --> Streaming: extension command executes immediately Streaming --> Idle: agent_settled Streaming --> Idle: abort```- A plain `prompt` while streaming is rejected without `streamingBehavior`.- An extension command (`/name`) sent through `prompt` executes immediately even during streaming and manages its own LLM interaction.- `agent_end` marks one low-level run; `agent_settled` marks full settlement after retry, compaction, and queued continuations.- 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).### EventsStreamed 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`.- `message_update` carries only deltas; clients assemble partial state by `contentIndex`; `message_end.message` is authoritative.- 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.- `tool_execution_update.partialResult` is cumulative, not a delta.### Extension UI over RPC| Method | RPC behavior || --- | --- || `select`, `confirm`, `input`, `editor` | Request/response sub-protocol with matching `id`; optional `timeout` auto-resolves agent-side || `notify`, `setStatus`, `setWidget`, `setTitle`, `set_editor_text` | Fire-and-forget requests || `custom` | Returns `undefined` || `setWorkingMessage`, `setWorkingIndicator`, `setFooter`, `setHeader`, `setEditorComponent`, `setToolsExpanded` | No-ops || `getEditorText`, `getToolsExpanded`, theme getters/setters | Degraded or empty |`ctx.mode === "rpc"` and `ctx.hasUI === true`; TUI-only capability must be guarded on `ctx.mode === "tui"`.### Extension hooks a companion extension can use- `pi.registerTool` at load or at runtime; new tools are callable without `/reload`.- 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.- 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.- `tool_call` can mutate arguments or block; `tool_result` can post-process.- `input` event sees raw text with `source` of `interactive | rpc | extension` and can `continue`, `transform`, or `handled`.- `before_agent_start` exposes and can extend `systemPrompt` and structured `systemPromptOptions`.- `pi.registerCommand` supports `getArgumentCompletions`; `pi.getCommands` mirrors `get_commands`.- Tool output must be truncated; built-in limits are 50KB and 2000 lines.## Neovim facts### Transport- `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.- Output callbacks run in fast contexts; API calls must be deferred through `vim.schedule` (`api-fast`, `vim.in_fast_event()`).- `jobstart`/`nvim_chan_send` remain the alternative channel API.### Buffers and edits| Need | Mechanism | Caveat || --- | --- | --- || Precise edit | `nvim_buf_set_text`, `nvim_buf_set_lines` | Each call opens a new undo block || One undoable change | `:undojoin` before the next change | `E790` after undo/redo; must not be used blindly || Change detection | `nvim_buf_attach` `on_lines`, `b:changedtick` | Callbacks are fast-context || Diffing model output against buffer | `vim.text.diff` with `result_type = 'indices'` | Available in 0.12 || Disk coherence after buffer edits | buffer write plus `:checktime`; `'autoread'` defaults on | Unwritten buffers stay invisible to filesystem tools |### Presentation- Extmarks provide `virt_text` with `virt_text_pos = "inline"` for ghost text, `virt_lines` (with `virt_lines_above`, `virt_lines_overflow`), highlights, and signs.- `nvim_set_decoration_provider` with `ephemeral` marks renders per redraw without persistent state.- `vim.diagnostic` namespaces keep agent findings separate from LSP and compiler diagnostics.- Quickfix and location lists use `setqflist`/`setloclist` and normal navigation.### Integration surface- `nvim_exec_autocmds` emits `User` events with a `data` payload (`event-data`), which fits publishing cached pivi state.- `nvim_create_user_command` supplies subcommands, `nargs`, and custom completion for `:Pi help` and `:Pi command ...`.- `<Plug>` mappings expose behavior without claiming global keys.- `vim.ui.select` and `vim.ui.input` can back RPC dialog methods.## Spec claims versus evidence| Spec claim | Support | Risk || --- | --- | --- || Non-terminal JSONL subprocess channel | `pi --mode rpc` plus `vim.system` stdin/stdout | Low || Semantic status (queue, run, tool, retry, compaction) | `get_state`, `get_session_stats`, event stream | Low || Slash commands via `:Pi command ...` | `get_commands` plus `prompt` with `/name` | Low; TUI-only commands unavailable || `: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 || Loaded buffers authoritative for reads and edits | Built-in tool override or injected `ReadOperations`/`EditOperations`/`WriteOperations` | Medium; result and `details` shapes must match exactly || Progressive ghost text from streaming tool arguments | `toolcall_delta` plus inline `virt_text` | Medium; requires tolerant partial-JSON parsing || One coherent undoable change per edit | `nvim_buf_set_text` plus `:undojoin` | Medium; `E790` and multi-hunk edits || Edits visible to later shell work without watchers | Explicit buffer write plus `:checktime` | Medium; unwritten buffers diverge from disk || Extension dialogs mapped to native surfaces | `extension_ui_request`/`extension_ui_response` | Low || Multiple sessions, resume, switch | `--session`, `switch_session`, `new_session`, `fork`, `clone` | Low |## Open questions- Does `:Pi help` use a second short-lived Pi process, or a companion extension command inside the working session that suppresses history?- Can two Pi processes safely target one session file, or must ephemeral help always run with `--no-session`?- Is buffer authority better implemented as operations injection into built-in tools than as full tool overrides, given the exact `details` shape requirement?- How should partial `toolcall_delta` arguments be parsed safely enough to show ghost text without ever mutating a buffer?- 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
Addednew file mode 100644+76 / −0 text lines
---id: NVIM-RESEARCH-NOSZ7JUQtype: researchtitle: Pi session resume and transcript backfill capabilities---# Pi session resume and transcript backfill capabilitiesVerified against the installed Pi `0.87.1` (`pi --mode rpc`), not from prose.Probed live by resuming a real session with `--continue` and issuing query RPCs.## Resume is a native Pi capabilityPi already resolves "last session in cwd"; pivi need not enumerate to get the common case.| Flag | Meaning | Usable over RPC || --- | --- | --- || `--continue`, `-c` | resume the most recent session for the project (cwd) | yes || `--session <path\|id>` | resume a specific session file or partial UUID | yes || `--session-id <id>` | use an exact project session id, creating it if missing | yes || `--resume`, `-r` | interactive picker to select a session | no — TUI only || `--fork <path\|id>` | fork a session into a new one | yes || `--session-dir <dir>` | directory for session storage and lookup | yes || `--no-session` | ephemeral, nothing saved | yes || `--name`, `-n` | display name only, not a resume key | yes |`PI_CODING_AGENT_SESSION_DIR` sets the storage directory (`--session-dir` overrides it).On 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.## Session storage layout- Sessions are bucketed per project under the session dir, one directory per cwd.- The bucket directory name encodes the cwd (`/` to `-`, wrapped in `--…--`), but the encoding is lossy and ambiguous; do not decode it.- Each session is a file `<ISO-timestamp>_<uuid>.jsonl`.- The first line is a header: `{ "type":"session", "id", "timestamp", "cwd" }`.- 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.- 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.## Transcript backfill RPCsAll three return `success:true` on a resumed session with no prompt sent, so backfill performs no model call.| RPC | Response shape | Use || --- | --- | --- || `get_entries` | `{ entries: [ { type, id, parentId, timestamp, … } ] }` | flat log, authoritative for full re-render || `get_entries` with `since:<entryId>` | entries after the cursor; unknown id fails with `"Entry not found: <id>"` | durable incremental cursor || `get_tree` | `{ tree: [ { entry, children: [ … ] } ] }`, recursive | branch and leaf detection || `get_messages` | `{ messages: [ { role, content, sections:{ preamble, … } } ] }` | rendered messages, includes the system preamble |### Entry vocabulary`get_entries` entry `type` values observed: `model_change`, `thinking_level_change`, `message`, `session_info`, `custom`.A `message` entry carries a full message object under `.message`.Message roles: `system`, `user`, `assistant`, `toolResult`.- Assistant `message.content` is a list of parts, each tagged by `type`: - `{ type:"thinking", thinking, thinkingSignature }` - `{ type:"tool_call", id, name, arguments }` where `arguments` is a decoded object, not a string. - text parts. - Assistant messages also carry `usage`, `stopReason`, `model`, `provider`, `responseId`.- A tool result is its own message: `{ role:"toolResult", toolCallId, toolName, content:[{type,text}], isError, timestamp }`, matched to its call by `toolCallId`.## Conclusions- `: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.- A cwd session picker needs a filesystem scan of the session dir, filtering by each header's `cwd`, because no listing RPC exists.- 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.- 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".## Unresolved- Exact, reversible bucket-name encoding. Treated as opaque; headers are read instead.- 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.- `leafId` selection: `get_tree` exposes branches via `children`, but which leaf is the current head on resume is not yet pinned.- 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
Addednew file mode 100644+79 / −0 text lines
---id: NVIM-RESEARCH-T3BL4TK4type: researchtitle: Pi tool result formats for presentation---# Pi tool result formats for presentationRead from real Pi session logs on disk (`$PI_CODING_AGENT_SESSION_DIR`), not from prose.Each tool result is a `toolResult` message: `{ role, toolCallId, toolName, content, isError, timestamp, details? }`.`content` is always a text block list `[{ type:"text", text }]`; the rich, per-tool structure lives in `details`.This closes the evidence gap that blocked grep file-grouping and the bash full-output surface.## Per-tool shapes| Tool | `details` keys | `content` text shape || --- | --- | --- || edit | `diff`, `firstChangedLine` | a short sentence, e.g. `Successfully replaced 4 block(s) in <path>.` || grep | none | ripgrep context output, or `No matches found` || find | none | newline-separated names, no line numbers || ls | none | newline-separated entries, directories suffixed `/` || bash | `truncation`, `fullOutputPath` | the captured output, possibly truncated || read | `truncation` | file content || write | none | a short sentence |### edit`details.diff` is a display diff with a line-number gutter and change markers, for example:``` 9 * ...+ 11 * The tools use ...+ 12 * a system prompt section ...```A removed line is marked `-`, an added line `+`, and a context line has no marker.`details.firstChangedLine` is the first changed line number.This matches what pivi already consumes; no change needed for the edit diff.### grepNo `details`. The match structure is only in `content.text`, in ripgrep's context format:- a match line is `PATH:LINE:TEXT`- a context line is `PATH-LINE-TEXT`- distinct match groups may be separated by a `--` line- an empty search is exactly `No matches found`The 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 `-`.There 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.### find and ls`content.text` is a newline-separated list.`find` returns names or paths with no line numbers, so a find result groups trivially as a flat list.`ls` suffixes directories with `/`.### bash`details.truncation` carries `{ truncated: bool, ... }`; `details.fullOutputPath` is a filesystem path to the complete output when the kept result was trimmed.A full-output detail surface opens that path.### read`details.truncation` only; the subject path is the file itself, so a preview leads back to the file that was read.## Conclusions- 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.- 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.- The bash full-output surface opens `details.fullOutputPath`; truncation is `details.truncation.truncated`.- Edit diff and first-changed-line are already correct against the real shape; no rework there.## Unresolved- Whether ripgrep emits `--` separators and heading lines under every Pi configuration, or only with certain flags; the parser must tolerate both.- Whether a stable match column is ever present in any grep mode; none seen in the sampled logs.- 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
Addednew file mode 100644+297 / −0 text lines
---id: NVIM-SPEC-GMWDCMJZtype: spectitle: pivi Native Neovim Integrationresearch: - NVIM-RESEARCH-KZYYEFY_ - NVIM-RESEARCH-NOSZ7JUQ - NVIM-RESEARCH-T3BL4TK4---# pivi Native Neovim Integration## Intentpivi makes Pi feel native inside Neovim rather than embedding Pi's terminal interface.Pi remains a fully empowered coding agent.Neovim supplies editing, navigation, presentation, and live editor context.[Accepted native edit and follow-mode mockup](./native-agent-trail.html)## Scopepivi provides:- Persistent Pi sessions controlled through Pi RPC.- Neovim buffers for prompts, transcripts, session navigation, and detailed output.- Native quickfix lists, location lists, diagnostics, extmarks, signs, diffs, and navigation.- Live access to core Neovim state and unrestricted Neovim Lua execution.- A bundled Pi companion extension loaded in addition to the user's normal Pi configuration.Initial editor tools focus on buffers, selections, windows, tabs, marks, jumps, changes, lists, diagnostics, commands, and Lua execution.LSP-specific tools are outside the initial scope.## Session behavior- A Pi session is an explicit task identity with persistent history.- Each session captures a working directory as its execution scope.- Multiple sessions may share one working directory.- A tab may select a default session but does not own its lifetime.- Source buffers do not own sessions.- Closing a session window hides presentation without deleting history or implicitly stopping Pi.- A session can be resumed: the most recent session for the working directory by default, or an earlier session chosen by identity.- Resuming attaches to persistent history without starting a new conversation and without a model call.- Prior sessions for the working directory are listable so one can be chosen to resume.- The client can restart: pivi reloads itself while a working session is resumed by identity, losing neither its history nor its place.- 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.- Accepting the prompt while the agent is working steers the active run, the way Pi does; a separate, announced key queues a follow-up.- Steering reaches the active run; a follow-up is queued, and queued follow-ups remain listable and clearable before delivery.```mermaidstateDiagram-v2 [*] --> Idle Idle --> Running: submit Running --> Running: steer, or queue follow-up Running --> Idle: settle Running --> Idle: abort Idle --> [*]: stop session```## Session restorationResuming a session is worthless if the conversation it resumes is invisible, so a resumed session shows the document it already is.- Resuming rebuilds the transcript from the session's recorded history as addressable entries, with messages rendered and tool calls paired with their results.- A restored entry is navigable, collapsible, and inspectable exactly like a live one; restoration is presentation and never alters recorded history.- A restored tool entry whose recorded result carries no change detail degrades to its subject and result text rather than a fabricated diff.- Restoration performs the history reads it needs but no model call, and a large history stays responsive as it renders.pivi restores its own sessions; it never owns the editor's session persistence. Coupling to a native Neovim session workflow stays weak.- pivi publishes a serializable descriptor of its live sessions for a working directory, and an idempotent restore entry point.- 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.- Restore resumes the described sessions and rebuilds their transcripts; a missing descriptor or an absent session degrades quietly to no restoration.```mermaidstateDiagram-v2 [*] --> Absent Absent --> Resuming: resume last in cwd or chosen session Absent --> Resuming: consumer restore from descriptor Resuming --> Restored: history rebuilt as entries Restored --> Restored: restart reloads client, resumes by identity Restored --> [*]: stop session```## Slash commands- Pi slash commands are available through `:Pi command ...`.- Only commands Pi exposes to non-interactive clients are offered; terminal-only commands are absent.- In a Pi input buffer, `/` invokes slash-command entry only when the cursor is at the first character.- Elsewhere, `/` retains ordinary Neovim behavior.## One-shot help- `:Pi help` answers a fast question about Neovim, pivi, or Pi.- Help runs as an independent ephemeral agent run with no persisted session and no shared history.- Help never enters a working session's transcript, queue, or status.- Help stays available while a working session runs, and neither delays nor interrupts it.- Help failure is isolated and never degrades a working session.- Help may read, and never modifies the editor, the filesystem, or Pi state.- Each question carries what the user can currently see rather than whole buffers.- Editor documentation is answered from the running instance, so the version and installed plugins decide the answer.- pivi's own behavior is supplied as knowledge to the agent rather than assumed.```mermaidflowchart LR editor["Neovim"] --> session["Working session run"] editor --> help["Ephemeral help run"] session --> history["Persistent session history"] help --> discard["Discarded after answer"] help --> readonly["Read-only editor and documentation lookups"]```## Editor context- Each submission may carry an immutable snapshot of its originating buffer, path, revision, cursor, range, selection kind, selected text, and bounded surrounding text.- Queued submissions retain their own snapshots.- Pi can obtain fresh ambient editor state before later model calls.- Full buffer contents are fetched on demand rather than attaching every open buffer automatically.- Loaded buffers, including unsaved contents, are authoritative for editor-aware reads.- The Pi prompt receives a short stable orientation to the live Neovim environment without replacing existing system or project instructions.## Editing- Pi may edit without an approval gate.- Reads, edits, and writes preserve the behavior and improvements of Pi's upstream tools while making loaded Neovim buffers authoritative.- Agent changes to loaded buffers appear directly in Neovim, remain undoable, and become visible to filesystem-based commands without requiring manual reload.- Unloaded paths retain normal Pi filesystem behavior.- Validated edit intent may appear progressively as ghost text while tool arguments stream.- Real buffer mutation begins only after complete valid edit arguments exist.- An edit operation presents one coherent undoable change where Neovim permits it.- pivi uses no filesystem watchers.- Arbitrary shell or third-party tool mutations without identified paths are not represented as precise editor edits.## Transcript presentationA transcript is the conversation itself, presented as the document it already is.- Transcript text is the messages as authored; pivi's own framing is presentation rather than content.- Copying transcript text yields the original message text, without framing.- Message formatting is rendered rather than shown as markup, and embedded code is presented in its own language.- Rendering degrades to plain readable text when a format cannot be rendered.- Presentation never performs Pi RPC, and streaming stays responsive as a transcript grows.## Transcript navigationEvery transcript entry is an addressable unit: a submission, an answer, a tool call, a tool result, or an error.- An entry can be collapsed to a single readable line or expanded to its full content.- Voluminous entries, such as tool results, start collapsed.- The user can move between entries, and between tool calls, with ordinary motions.- An entry that names a location is navigable to that location.- An entry can be inspected in detail without leaving the transcript.- Entry state is presentation only and never alters session history.```mermaidstateDiagram-v2 [*] --> Collapsed: entry appended Collapsed --> Expanded: expand Expanded --> Collapsed: collapse Expanded --> Located: follow reference Located --> Expanded: return```## Tool presentationA 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.[Accepted tool presentation mockup](./tool-presentation.html)The transcript stays a lean log and the detail is summoned, not spilled.- A tool is one headline while collapsed: a tool-coloured gutter indicator, the tool, what it acted on, and how it ended.- An entry expands in place to its detail and collapses back; voluminous detail starts collapsed and an outcome stays legible either way.- Expanded detail reads as the tool's own content set apart from the conversation, not as more message text.- The focused entry is distinguished from the rest.- A tool that reports nothing about its own work degrades to its subject and indicator, never to a guess.Each tool is presented as what it actually reports.- 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.- 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.- A search tool groups its matches by file with the matched text distinguished, and its cross-file findings reach a quickfix list.- A file read shows a syntax-aware preview that leads to the file itself.- A failed tool shows a single red outcome and no body.Full detail that does not belong inline is a dedicated detail surface, distinct from the transcript and dismissible, never overwriting the user's working window.```mermaidstateDiagram-v2 [*] --> Collapsed: tool call Collapsed --> Collapsed: output arrives, outcome updates Collapsed --> Expanded: expand Expanded --> Collapsed: collapse Expanded --> Detail: open comparison or full output Collapsed --> Detail: open comparison or full output Detail --> Expanded: dismiss Detail --> Collapsed: dismiss```## Agent activity- Active edits may use signs, line highlights, extmarks, virtual text, or virtual lines.- Completed edits leave a navigable changed-line trail until cleared by defined editor activity or session action.- Activity belongs to its Pi session and does not overwrite unrelated diagnostic or extmark namespaces.- File and range references are navigable through normal Neovim motions and lists.- Cross-file findings use quickfix lists.- Window-associated findings use location lists.- AI diagnostics remain distinguishable from compiler and language-server diagnostics.## Follow-agent mode- Follow mode is optional and disabled unless selected by the user.- It follows location-bearing reads, edits, findings, and explicit navigation rather than every event.- It can follow in a dedicated window, a dedicated tab, or the current window.- Dedicated-window following preserves the user's working window.- Passive following avoids unnecessary jumplist pollution.- The user can return to the location held before following began.## Pi compatibility- Pi RPC is pivi's sole integration channel; no embedded Pi TUI or TUI escape hatch.- Implement every supported RPC capability through native Neovim surfaces, generically rather than per extension.- Preserve Pi-owned behavior; use public RPC operations without private internals or TUI emulation.- New features using existing RPC contracts remain usable without feature-specific pivi changes.- Unknown content remains readable and inspectable; unsupported interactions are reported explicitly.- RPC UI state belongs to its session; concurrent tool activity is correlated by call ID.- The companion extension is shipped with pivi and injected additively when Pi starts.- User, project, package, provider, skill, prompt, and tool configuration continues to load under Pi's normal rules.- pivi does not silently alter Pi project trust or restrict available tools.- Extension tools, commands, hooks, prompt changes, session behavior, and supported RPC dialogs remain functional.- TUI-only renderers, custom components, keybindings, headers, footers, and terminal input are not emulated.- Supported extension dialogs and status requests map to native Neovim surfaces.- Unrestricted Neovim Lua execution is available alongside structured convenience tools.## Native integration invariantpivi is an optional producer of native Neovim state, never the owner of surrounding configuration.- It does not replace or require a statusline, winbar, tabline, picker, notification system, layout, or keymap framework.- It publishes cached state through native variables and semantic `User` events.- It offers commands and `<Plug>` mappings without imposing global mappings.- Consumers can degrade to ordinary Neovim behavior when pivi is absent.- Loading pivi succeeds when the Pi executable is unavailable; starting Pi reports the missing capability.- Status consumers never perform Pi RPC during statusline evaluation.## Transport and status- Pi RPC uses a non-terminal JSONL subprocess channel.- Terminal dimensions, alternate screens, cursor escapes, and terminal key forwarding are not part of pivi.- Standard error remains separate from protocol output.- ANSI styling in payload text is stripped or translated before native presentation.- Semantic session status includes connection, queue, run, tool, waiting, compaction, retry, abort, and error states.- Status also exposes available model, thinking, session, context, usage, and extension-status data.- Status changes redraw native status surfaces and emit a semantic event.## Acceptance criteria- A Pi slash command can run through `:Pi command ...`; `/` invokes slash-command entry only at the first character of a Pi input buffer.- A transcript renders message formatting, presents embedded code in its own language, and still yields the original text when copied.- A collapsed tool entry is one line carrying a tool-coloured indicator, the subject, and the outcome; the focused entry is visibly distinguished.- A tool entry expands its detail in place and collapses back, and the detail is set apart from conversation text.- 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.- 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.- A search tool groups matches by file with the matched text distinguished and sends cross-file findings to a quickfix list.- A file read presents a syntax-aware preview that leads to the file.- A failed tool shows a single outcome line and no body.- A tool result is collapsed on arrival, expands on request, and collapsing never changes session history.- A user can move between transcript entries with ordinary motions and reach the location an entry names.- Transcript presentation performs no Pi RPC, and a long streamed answer stays responsive.- `:Pi help` answers while a working session run is active, without appearing in that session's history, queue, or status.- A help question carries the visible editor region, layout, selection, recent messages, and the last error, and no full buffer.- Help can answer an editor documentation question from the running instance, including documentation of installed plugins.- No help run can modify a buffer, a file, or Pi state.- 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.- Accepting the prompt while the agent is working steers the run; a separate announced key queues a follow-up.- A queued follow-up can be listed and cleared before delivery.- A user can create, resume, switch, and stop explicit Pi sessions without tying their lifetime to a source buffer or tab.- 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.- Prior sessions for the working directory can be listed and one chosen to resume.- Resuming rebuilds the transcript as addressable entries with rendered messages and tool calls paired to their results, and the rebuild performs no model call.- A restored tool entry whose recorded result carries no change detail shows its subject and result text rather than a fabricated diff.- Restarting reloads the pivi client and resumes the active session by identity with its history and place intact.- 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.- Restoring from a missing descriptor or an absent session degrades quietly to no restoration.- A prompt can include an unsaved selection with stable source and revision metadata.- Pi can read unsaved loaded-buffer content and use current core Neovim context on demand.- Pi can execute arbitrary Neovim Lua and use structured editor operations.- A normal Pi edit to a loaded buffer appears without reload, is undoable, remains coherent with subsequent shell work, and receives visible activity markers.- Streaming edit arguments can produce non-mutating ghost presentation; incomplete arguments never mutate the real buffer.- Follow mode can track an agent edit in a dedicated viewport without taking over the user's working window.- Quickfix, location-list, diagnostic, and file navigation use normal Neovim behavior.- Existing Pi extensions and tools continue to run except for capabilities inherently specific to Pi's TUI.- A custom Neovim configuration can consume pivi state and events without requiring pivi to be installed or loaded.- pivi does not modify user-owned statuslines, winbars, tablines, global mappings, or picker configuration.- No filesystem watcher is started.- 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.- 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
Addednew file mode 100644+92 / −0 text lines
<section class="pivi-mockup"> <style> :host { color-scheme: dark; font: 14px/1.35 ui-monospace, "Cascadia Mono", Consolas, monospace; } .pivi-mockup { max-width: 1120px; margin: 0 auto; color: #d7d7d7; background: #17191d; border: 1px solid #464b55; box-shadow: 0 10px 35px #0008; } .tabs, .winbar, .status { display: flex; align-items: center; min-height: 1.7em; padding: 0 .65em; white-space: pre; } .tabs { background: #242830; gap: 1.1em; color: #a9b0bc; } .tabs .active { color: #f0f0f0; background: #343945; margin: 0 -.4em; padding: 0 .4em; } .workspace { display: grid; grid-template-columns: minmax(0, 3fr) minmax(24em, 2fr); min-height: 29em; } .window { min-width: 0; position: relative; } .window + .window { border-left: 1px solid #464b55; } .winbar { justify-content: space-between; background: #202329; color: #bfc5cf; border-bottom: 1px solid #30343c; } .agent { color: #deb887; } .buffer { padding: .45em 0 1em; overflow: hidden; } .line { display: grid; grid-template-columns: 2em 1.2em minmax(0, 1fr); min-height: 1.45em; } .num { color: #636b78; text-align: right; padding-right: .45em; user-select: none; } .sign { color: #7f8794; text-align: center; } .code { white-space: pre; overflow: hidden; } .kw { color: #d49adf; } .str { color: #e6c384; } .editing { background: #3a3223; } .editing .sign { color: #efbd6b; } .changed { background: #22352c; } .changed .sign { color: #8ec07c; } .virt { display: grid; grid-template-columns: 3.2em minmax(0, 1fr); color: #87b98b; background: #1c2923; } .virt::before { content: "+"; text-align: right; padding-right: .55em; color: #8ec07c; } .ghost { color: #98a1ad; font-style: italic; } .status { justify-content: space-between; background: #292d35; color: #ccd0d8; border-top: 1px solid #464b55; } .external { color: #89919e; } .controls { display: flex; gap: .5em; padding: .65em; border-top: 1px solid #343944; background: #202329; } button { font: inherit; color: #d7d7d7; background: #303540; border: 1px solid #565d69; padding: .3em .7em; } button[aria-pressed="true"] { border-color: #d7a85d; color: #f3c77b; } button:focus-visible { outline: 2px solid #9ccfd8; outline-offset: 2px; } .note { margin-left: auto; align-self: center; color: #7f8794; } </style> <div class="tabs"><span class="active">1 api</span><span>2 tests</span><span>3 docs</span><span class="agent">π refactor-parser</span></div> <div class="workspace"> <article class="window"> <header class="winbar"><span>lua/parser.lua</span><span>human workspace</span></header> <div class="buffer"> <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> <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> <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> <div class="line"><span class="num">41</span><span class="sign"> </span><span class="code"><span class="kw">end</span></span></div> <div class="line"><span class="num">42</span><span class="sign"> </span><span class="code"></span></div> <div class="line"><span class="num">43</span><span class="sign"> </span><span class="code"><span class="kw">return</span> { parse = parse }</span></div> </div> </article> <article class="window"> <header class="winbar"><span>lua/tokenize.lua</span><span class="agent">π editing 17:19</span></header> <div class="buffer"> <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> <div class="line"><span class="num">16</span><span class="sign"> </span><span class="code"> <span class="kw">local</span> result = {}</span></div> <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> <div class="virt"><span></span><span class="code"> result[#result + 1] = normalize(token)</span></div> <div class="line editing"><span class="num">18</span><span class="sign">│</span><span class="code"> result[#result + 1] = token</span></div> <div class="line editing"><span class="num">19</span><span class="sign">└</span><span class="code"> <span class="kw">end</span></span></div> <div class="line"><span class="num">20</span><span class="sign"> </span><span class="code"> <span class="kw">return</span> result</span></div> <div class="line"><span class="num">21</span><span class="sign"> </span><span class="code"><span class="kw">end</span></span></div> </div> </article> </div> <footer class="status"><span>NORMAL lua/parser.lua</span><span class="external">existing user-owned statusline remains untouched</span><span>40:3</span></footer> <div class="controls" aria-label="Representative controls"> <button type="button" data-follow aria-pressed="true">Follow: window</button> <button type="button" data-state aria-pressed="false">Show completed state</button> <span class="note">Illustrative interaction only</span> </div> <script> (() => { const root = document.currentScript.mockupRoot; const follow = root.querySelector('[data-follow]'); const state = root.querySelector('[data-state]'); follow.addEventListener('click', () => { const on = follow.getAttribute('aria-pressed') !== 'true'; follow.setAttribute('aria-pressed', String(on)); follow.textContent = on ? 'Follow: window' : 'Follow: off'; }); state.addEventListener('click', () => { const completed = state.getAttribute('aria-pressed') !== 'true'; state.setAttribute('aria-pressed', String(completed)); state.textContent = completed ? 'Show active state' : 'Show completed state'; root.querySelectorAll('.editing').forEach((line) => { line.classList.toggle('editing', !completed); line.classList.toggle('changed', completed); }); const winbar = root.querySelectorAll('.winbar')[1].lastElementChild; winbar.textContent = completed ? 'π edited 17:19' : 'π editing 17:19'; const ghost = root.querySelector('.ghost'); ghost.textContent = completed ? 'π changed' : 'π editing…'; }); })(); </script></section>neovim/.system/specs/NVIM-SPEC-GMWDCMJZ-pivi-native-neovim-integration/tool-presentation.html
Addednew file mode 100644+96 / −0 text lines
<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>pivi tool presentation — accepted direction (C2 canonical)</title><style> body{background:#111;margin:0;padding:24px;color-scheme:dark;font-family:system-ui,sans-serif} .cap{max-width:680px;margin:0 auto 12px;color:#bbb;font:13px/1.5 system-ui} .cap b{color:#c9b6eb} .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} .r{display:grid;grid-template-columns:3ch 1fr;white-space:pre;padding:0 10px} .sign{text-align:center} .head{cursor:pointer}.head:hover{background:#202020} .user{color:#b59ae4}.pi{color:#3ec5e3}.dim{color:#8b8b8b}.faint{color:#5d5d5d} .add{color:#7ba1aa}.del{color:#ec6376}.ok{color:#7ba1aa}.bad{color:#ec6376}.warn{color:#f0ee69} .se{color:#b59ae4}.sb{color:#3ec5e3}.sg{color:#f0ee69}.sr{color:#8b8b8b} .cur{background:#242424}.rail{color:#39343f}.gut{color:#5d5d5d} .kw{color:#b59ae4}.fn{color:#3ec5e3}.str{color:#7ba1aa} .hide{display:none}.cmp{color:#c9b6eb;text-decoration:underline;cursor:pointer}.file{color:#9aabae} .flo{position:absolute;right:12px;top:96px;width:42ch;background:#1f1f1f;border:1px solid #4f3c69;border-radius:4px;font-size:12px} .flo .h{color:#c9b6eb;background:#2d2440;padding:3px 9px;display:flex;justify-content:space-between} .flo .b{padding:5px 9px;white-space:pre}</style></head><body><div class="cap"> <b>pivi tool presentation — accepted visual direction.</b> Neovim transcript, nugu dark, monospace cells. One headline line per tool, collapsed by default; click a headline to expand detail inline; click the edit's <i>compare</i> to toggle the floating comparison. Terminal fidelity: border-only floats, no shadow.</div><section class="t"> <div class="r user"><span class="sign">█</span><span class="user"> you</span></div> <div class="r user"><span class="sign">█</span><span class="user">refactor the submission path and run tests</span></div> <div class="r"><span class="sign"></span><span class="pi"> pi</span></div> <div class="r"><span class="sign"></span><span>Reworking delivery resolution, then verifying.</span></div> <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> <div data-body="edit"> <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> <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> <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> </div> <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> <div data-body="bash" class="hide"> <div class="r"><span class="sign"><span class="rail">│</span></span><span class="dim">Testing: tests/bugabinga/pivi/…</span></div> <div class="r"><span class="sign"><span class="rail">│</span></span><span><span class="ok">Success: 669</span> Failed: 0 Errors: 0</span></div> <div class="r"><span class="sign"><span class="rail">│</span></span><span class="faint">… 2140 lines truncated · full output</span></div> </div> <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> <div data-body="grep" class="hide"> <div class="r"><span class="sign"><span class="rail">│</span></span><span class="file">session.lua</span></div> <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> <div class="r"><span class="sign"><span class="rail">│</span></span><span class="file">status.lua</span></div> <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> </div> <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> <div data-body="read" class="hide"> <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> <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> <div class="r"><span class="sign"><span class="rail">│</span></span><span class="faint">… open file</span></div> </div> <div class="r"><span class="sign bad"></span><span><span class="dim">write</span> /etc/hosts <span class="bad">✗ permission denied</span></span></div> <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 {}<span class="gut">38</span> <span class="del">- local busy = status.is_busy(self)</span><span class="gut">38</span> <span class="add">+ local busy, delivery =</span><span class="gut">39</span> <span class="add">+ resolve( self, options )</span><span class="gut">40</span> if busy and not delivery then</div></div></section><script> (() => { const root = document; root.querySelectorAll('.head').forEach((h) => { h.addEventListener('click', (e) => { if (e.target.dataset && e.target.dataset.cmp) { root.querySelector('[data-float]').classList.toggle('hide'); e.stopPropagation(); return; } const body = root.querySelector('[data-body="' + h.dataset.k + '"]'); const chev = h.querySelector('.dim'); const open = !body.classList.contains('hide'); body.classList.toggle('hide'); chev.textContent = chev.textContent.replace(open ? '▾' : '▸', open ? '▸' : '▾'); }); }); })();</script></body></html>neovim/AGENTS.md
Modified+1 / −1 text lines
neovim/after/ftplugin/image.lua
Addednew file mode 100644+10 / −0 text lines
vim.opt_local.number = falsevim.opt_local.relativenumber = falsevim.opt_local.signcolumn = 'no'vim.opt_local.foldcolumn = '0'vim.opt_local.cursorline = falsevim.opt_local.wrap = falsevim.opt_local.spell = falsevim.opt_local.winbar = ''vim.opt_local.statuscolumn = ''vim.opt_local.scrolloff = 0neovim/after/ftplugin/markdown.lua
Modified+5 / −1 text lines
neovim/after/ftplugin/qml.lua
Addednew file mode 100644+12 / −0 text lines
-- QML/QMLLS tooling.-- Quickshell populates this marker with local import paths when the config runs.local current = vim.api.nvim_buf_get_name(0)local dir = vim.fs.dirname(current)local root = dir and vim.fs.root(dir, 'shell.qml')if root and current:find('/quickshell/', 1, true) then local marker = root .. '/.qmlls.ini' if vim.fn.filereadable(marker) == 0 then vim.fn.writefile({}, marker) endendneovim/after/queries/bash/injections.scm
Addednew file mode 100644+45 / −0 text lines
; extends((comment) @injection.content (#lua-match? @injection.content "^#MISE ") (#offset! @injection.content 0 6 0 0) (#set! injection.language "toml"))((comment) @injection.content (#lua-match? @injection.content "^# MISE ") (#offset! @injection.content 0 7 0 0) (#set! injection.language "toml"))((comment) @injection.content (#lua-match? @injection.content "^#%[MISE%] ") (#offset! @injection.content 0 8 0 0) (#set! injection.language "toml"))((comment) @injection.content (#lua-match? @injection.content "^# %[MISE%] ") (#offset! @injection.content 0 9 0 0) (#set! injection.language "toml"))((comment) @injection.content (#lua-match? @injection.content "^#USAGE ") (#offset! @injection.content 0 7 0 1) (#set! injection.combined) (#set! injection.language "kdl"))((comment) @injection.content (#lua-match? @injection.content "^# USAGE ") (#offset! @injection.content 0 8 0 1) (#set! injection.combined) (#set! injection.language "kdl"))((comment) @injection.content (#lua-match? @injection.content "^#%[USAGE%] ") (#offset! @injection.content 0 9 0 1) (#set! injection.combined) (#set! injection.language "kdl"))((comment) @injection.content (#lua-match? @injection.content "^# %[USAGE%] ") (#offset! @injection.content 0 10 0 1) (#set! injection.combined) (#set! injection.language "kdl"))neovim/after/queries/javascript/injections.scm
Addednew file mode 100644+45 / −0 text lines
; extends((comment) @injection.content (#lua-match? @injection.content "^//MISE ") (#offset! @injection.content 0 7 0 0) (#set! injection.language "toml"))((comment) @injection.content (#lua-match? @injection.content "^// MISE ") (#offset! @injection.content 0 8 0 0) (#set! injection.language "toml"))((comment) @injection.content (#lua-match? @injection.content "^//%[MISE%] ") (#offset! @injection.content 0 9 0 0) (#set! injection.language "toml"))((comment) @injection.content (#lua-match? @injection.content "^// %[MISE%] ") (#offset! @injection.content 0 10 0 0) (#set! injection.language "toml"))((comment) @injection.content (#lua-match? @injection.content "^//USAGE ") (#offset! @injection.content 0 8 0 1) (#set! injection.combined) (#set! injection.language "kdl"))((comment) @injection.content (#lua-match? @injection.content "^// USAGE ") (#offset! @injection.content 0 9 0 1) (#set! injection.combined) (#set! injection.language "kdl"))((comment) @injection.content (#lua-match? @injection.content "^//%[USAGE%] ") (#offset! @injection.content 0 10 0 1) (#set! injection.combined) (#set! injection.language "kdl"))((comment) @injection.content (#lua-match? @injection.content "^// %[USAGE%] ") (#offset! @injection.content 0 11 0 1) (#set! injection.combined) (#set! injection.language "kdl"))neovim/after/queries/nu/injections.scm
Addednew file mode 100644+45 / −0 text lines
; extends((comment) @injection.content (#lua-match? @injection.content "^#MISE ") (#offset! @injection.content 0 6 0 0) (#set! injection.language "toml"))((comment) @injection.content (#lua-match? @injection.content "^# MISE ") (#offset! @injection.content 0 7 0 0) (#set! injection.language "toml"))((comment) @injection.content (#lua-match? @injection.content "^#%[MISE%] ") (#offset! @injection.content 0 8 0 0) (#set! injection.language "toml"))((comment) @injection.content (#lua-match? @injection.content "^# %[MISE%] ") (#offset! @injection.content 0 9 0 0) (#set! injection.language "toml"))((comment) @injection.content (#lua-match? @injection.content "^#USAGE ") (#offset! @injection.content 0 7 0 1) (#set! injection.combined) (#set! injection.language "kdl"))((comment) @injection.content (#lua-match? @injection.content "^# USAGE ") (#offset! @injection.content 0 8 0 1) (#set! injection.combined) (#set! injection.language "kdl"))((comment) @injection.content (#lua-match? @injection.content "^#%[USAGE%] ") (#offset! @injection.content 0 9 0 1) (#set! injection.combined) (#set! injection.language "kdl"))((comment) @injection.content (#lua-match? @injection.content "^# %[USAGE%] ") (#offset! @injection.content 0 10 0 1) (#set! injection.combined) (#set! injection.language "kdl"))neovim/after/queries/python/injections.scm
Addednew file mode 100644+45 / −0 text lines
; extends((comment) @injection.content (#lua-match? @injection.content "^#MISE ") (#offset! @injection.content 0 6 0 0) (#set! injection.language "toml"))((comment) @injection.content (#lua-match? @injection.content "^# MISE ") (#offset! @injection.content 0 7 0 0) (#set! injection.language "toml"))((comment) @injection.content (#lua-match? @injection.content "^#%[MISE%] ") (#offset! @injection.content 0 8 0 0) (#set! injection.language "toml"))((comment) @injection.content (#lua-match? @injection.content "^# %[MISE%] ") (#offset! @injection.content 0 9 0 0) (#set! injection.language "toml"))((comment) @injection.content (#lua-match? @injection.content "^#USAGE ") (#offset! @injection.content 0 7 0 1) (#set! injection.combined) (#set! injection.language "kdl"))((comment) @injection.content (#lua-match? @injection.content "^# USAGE ") (#offset! @injection.content 0 8 0 1) (#set! injection.combined) (#set! injection.language "kdl"))((comment) @injection.content (#lua-match? @injection.content "^#%[USAGE%] ") (#offset! @injection.content 0 9 0 1) (#set! injection.combined) (#set! injection.language "kdl"))((comment) @injection.content (#lua-match? @injection.content "^# %[USAGE%] ") (#offset! @injection.content 0 10 0 1) (#set! injection.combined) (#set! injection.language "kdl"))neovim/after/queries/toml/injections.scm
Addednew file mode 100644+12 / −0 text lines
neovim/after/queries/typescript/injections.scm
Addednew file mode 100644+45 / −0 text lines
; extends((comment) @injection.content (#lua-match? @injection.content "^//MISE ") (#offset! @injection.content 0 7 0 0) (#set! injection.language "toml"))((comment) @injection.content (#lua-match? @injection.content "^// MISE ") (#offset! @injection.content 0 8 0 0) (#set! injection.language "toml"))((comment) @injection.content (#lua-match? @injection.content "^//%[MISE%] ") (#offset! @injection.content 0 9 0 0) (#set! injection.language "toml"))((comment) @injection.content (#lua-match? @injection.content "^// %[MISE%] ") (#offset! @injection.content 0 10 0 0) (#set! injection.language "toml"))((comment) @injection.content (#lua-match? @injection.content "^//USAGE ") (#offset! @injection.content 0 8 0 1) (#set! injection.combined) (#set! injection.language "kdl"))((comment) @injection.content (#lua-match? @injection.content "^// USAGE ") (#offset! @injection.content 0 9 0 1) (#set! injection.combined) (#set! injection.language "kdl"))((comment) @injection.content (#lua-match? @injection.content "^//%[USAGE%] ") (#offset! @injection.content 0 10 0 1) (#set! injection.combined) (#set! injection.language "kdl"))((comment) @injection.content (#lua-match? @injection.content "^// %[USAGE%] ") (#offset! @injection.content 0 11 0 1) (#set! injection.combined) (#set! injection.language "kdl"))neovim/after/syntax/vfp.lua
Deleteddeleted file mode 100644+0 / −276 text lines
-- File: ~/.config/nvim/after/syntax/vfp.lua-- Syntax highlighting for Visual FoxPro 9.0-- Bail if syntax is already setif vim.b.current_syntax then return endlocal api = vim.apilocal fn = vim.fn-- Case-insensitive matchingvim.opt.ignorecase = true-- Define VFP9 Commands (unchanged from earlier)local commands = { 'accept', 'activate', 'add', 'additive', 'after', 'again', 'aindent', 'alias', 'all', 'alt', 'alter', 'alternate', 'ansi', 'any', 'aplabout', 'app', 'append', 'array', 'as', 'asc', 'ascending', 'ascii', 'assert', 'asserts', 'assist', 'attributes', 'aused', 'automatic', 'autosave', 'average', 'avg', 'before', 'begin', 'bell', 'bitmap', 'blank', 'blink', 'blocksize', 'border', 'bottom', 'box', 'browse', 'brstatus', 'bucket', 'buffers', 'build', 'by', 'calculate', 'calcvalue', 'call', 'cancel', 'carry', 'cascade', 'catalog', 'cd', 'center', 'century', 'cga', 'change', 'character', 'chdir', 'check', 'classlib', 'clear', 'click', 'clock', 'close', 'cnt', 'codepage', 'collate', 'color', 'column', 'com1', 'com2', 'command', 'compact', 'compatible', 'compile', 'compress', 'confirm', 'connection', 'connections', 'connstring', 'console', 'container', 'continue', 'control', 'copies', 'copy', 'count', 'cpcompile', 'cpdialog', 'create', 'currency', 'cursor', 'cursorgetprop', 'cursorsetprop', 'cycle', 'database', 'databases', 'datasession', 'datasource', 'db4', 'dblclick', 'dbmemo3', 'dbtrap', 'dde', 'deactivate', 'debug', 'decimals', 'declare', 'default', 'defaultsource', 'define', 'delete', 'deletetables', 'delimited', 'delimiters', 'desc', 'design', 'development', 'device', 'dif', 'dimension', 'dir', 'directory', 'disabled', 'display', 'distinct', 'dll', 'dlls', 'do', 'dohistory', 'dos', 'dosmem', 'double', 'down', 'drag', 'draw', 'driver', 'duplex', 'echo', 'edit', 'editwork', 'ega25', 'ega43', 'eject', 'ems64', 'ems', 'enabled', 'encrypt', 'encryption', 'end', 'environment', 'erase', 'escape', 'events', 'exact', 'except', 'exclusive', 'exe', 'exists', 'exit', 'export', 'expression', 'extended', 'external', 'f11f12', 'fdow', 'fetch', 'fields', 'file', 'filer', 'fill', 'find', 'fixed', 'float', 'flush', 'foldconst', 'font', 'footer', 'for', 'force', 'foreign', 'form', 'format', 'formset', 'found', 'fox2x', 'foxplus', 'free', 'freeze', 'from', 'full', 'function', 'fw2', 'fweek', 'gather', 'general', 'get', 'getexpr', 'getnextmodified', 'getobject', 'gets', 'global', 'go', 'goto', 'group', 'grow', 'halfheight', 'having', 'heading', 'headings', 'height', 'help', 'helpfilter', 'hidden', 'hide', 'highlight', 'history', 'hmemory', 'hours', 'iblock', 'icon', 'id', 'import', 'in', 'index', 'indexes', 'information', 'inner', 'input', 'insert', 'instruct', 'integer', 'intensity', 'intersect', 'into', 'is', 'isometric', 'join', 'keyboard', 'keycolumns', 'keycomp', 'keyset', 'label', 'last', 'ldcheck', 'ledit', 'left', 'level', 'library', 'line', 'linked', 'list', 'load', 'local', 'locate', 'logerrors', 'long', 'loop', 'lparameters', 'lpartition', 'mac', 'macdesktop', 'machelp', 'mackey', 'macro', 'macros', 'margin', 'mark', 'master', 'maxmem', 'mblock', 'md', 'mdi', 'memlimit', 'memo', 'memos', 'memowidth', 'memvar', 'menu', 'menus', 'message', 'messages', 'middle', 'minimize', 'minus', 'mkdir', 'modal', 'modify', 'module', 'mono43', 'mono', 'mouse', 'move', 'movers', 'multilocks', 'multiselect', 'mvarsiz', 'mvcount', 'name', 'near', 'negotiate', 'next', 'noalias', 'noappend', 'noclear', 'noclose', 'noconsole', 'nocptrans', 'nodata', 'nodebug', 'nodelete', 'nodefault', 'nodup', 'noedit', 'noeject', 'noenvironment', 'nofloat', 'nofollow', 'nogrow', 'noinit', 'nolgrid', 'nolink', 'nolock', 'nolog', 'nomargin', 'nomdi', 'nomenu', 'nominimize', 'nomodify', 'nomouse', 'none', 'nooptimize', 'noorganize', 'nooverwrite', 'noprompt', 'noprojecthook', 'noread', 'norefresh', 'norequery', 'norgrid', 'normal', 'nosave', 'noshadow', 'noshow', 'nospace', 'notify', 'noupdate', 'novalidate', 'noverify', 'nowait', 'nowindow', 'nowrap', 'nozoom', 'npv', 'null', 'number', 'nvl', 'object', 'objects', 'odometer', 'of', 'off', 'ole', 'oleobject', 'oleobjects', 'olepublic', 'on', 'only', 'open', 'optimize', 'order', 'orientation', 'outer', 'output', 'outshow', 'overlay', 'overwrite', 'pack', 'page', 'palette', 'panel', 'paperlength', 'papersize', 'paperwidth', 'parameters', 'partition', 'password', 'path', 'pattern', 'pause', 'pdox', 'pdsetup', 'pen', 'percent', 'pfs', 'picture', 'pixels', 'plain', 'play', 'point', 'pop', 'popup', 'popups', 'precision', 'preference', 'preview', 'primary', 'printer', 'printquality', 'private', 'procedure', 'procedures', 'production', 'progwork', 'project', 'protected', 'public', 'push', 'query', 'quit', 'random', 'range', 'rd', 'read', 'readborder', 'readerror', 'recall', 'record', 'recover', 'recsize', 'redit', 'reference', 'references', 'refresh', 'regional', 'reindex', 'relation', 'relative', 'release', 'remote', 'remove', 'rename', 'replace', 'report', 'reprocess', 'required', 'resource', 'rest', 'restore', 'restrict', 'resume', 'retry', 'return', 'right', 'rmdir', 'rollback', 'rowset', 'rpd', 'run', 'runscript', 'runtime', 'safety', 'same', 'sample', 'save', 'say', 'scale', 'scatter', 'scheme', 'screen', 'screens', 'scroll', 'sdf', 'seek', 'select', 'selection', 'separator', 'set', 'setfldstate', 'shadows', 'shared', 'sheet', 'shell', 'shift', 'show', 'shutdown', 'single', 'size', 'skip', 'some', 'sort', 'sortwork', 'spinner', 'sql', 'standalone', 'status', 'std', 'step', 'sticky', 'store', 'stretch', 'string', 'structure', 'style', 'subclass', 'sum', 'summary', 'suspend', 'sylk', 'sysformats', 'sysmenu', 'sysmenus', 'system', 'tab', 'tag', 'table', 'tables', 'tabs', 'talk', 'tedit', 'textmerge', 'this', 'this_access', 'thisform', 'thisformset', 'timeout', 'titles', 'tmpfiles', 'to', 'top', 'topic', 'total', 'transaction', 'trap', 'trbetween', 'trigger', 'ttoption', 'type', 'typeahead', 'udfparms', 'union', 'unlock', 'up', 'update', 'use', 'userid', 'users', 'validate', 'values', 'var', 'verb', 'vga25', 'vga50', 'view', 'views', 'volume', 'wait', 'when', 'where', 'width', 'window', 'windows', 'with', 'wk1', 'wk3', 'wks', 'workarea', 'wp', 'wr1', 'wrap', 'wrk', 'xcmdfile', 'xl5', 'xls', 'zap',}-- Define VFP9 Functions (unchanged)local functions = { 'abs', 'aclass', 'acopy', 'acos', 'adatabases', 'adbobjects', 'addbs', 'adel', 'adir', 'aelement', 'aerror', 'afields', 'afont', 'agetclass', 'agetfileversion', 'ains', 'ainstance', 'alen', 'alias', 'alines', 'alltrim', 'amembers', 'amouseobj', 'anetresources', 'ansitooem', 'aprinters', 'asc', 'ascan', 'aselobj', 'asin', 'asort', 'asubscript', 'at', 'at_c', 'atan', 'atc', 'atcc', 'atcline', 'atline', 'atn2', 'aused', 'avcxclasses', 'avg', 'bar', 'barcount', 'barprompt', 'between', 'bintoc', 'bitand', 'bitclear', 'bitlshift', 'bitnot', 'bitor', 'bitrshift', 'bitset', 'bittest', 'bitxor', 'bof', 'candidate', 'capslock', 'cdow', 'cdx', 'ceiling', 'chr', 'chrsaw', 'chrtran', 'chrtranc', 'cmonth', 'cntbar', 'cntpad', 'col', 'comarray', 'comclassinfo', 'compobj', 'comreturnerror', 'count', 'cos', 'cpconvert', 'cpcurrent', 'cpdbf', 'createbinary', 'createobject', 'createobjectex', 'createoffline', 'ctobin', 'ctod', 'ctot', 'curdir', 'cursorgetprop', 'cursorsetprop', 'curval', 'date', 'datetime', 'day', 'dbc', 'dbf', 'dbgetprop', 'dbsetprop', 'dbused', 'ddeaborttrans', 'ddeadvise', 'ddeenabled', 'ddeexecute', 'ddeinitiate', 'ddelasterror', 'ddepoke', 'dderequest', 'ddesetoption', 'ddesetservice', 'ddesettopic', 'ddeterminate', 'defaulttext', 'deleted', 'descending', 'difference', 'directory', 'diskspace', 'dmy', 'dodefault', 'dow', 'drivetype', 'dropoffline', 'dtoc', 'dtor', 'dtos', 'dtot', 'empty', 'eof', 'error', 'evaluate', 'exp', 'fchsize', 'fclose', 'fcount', 'fcreate', 'fdate', 'feof', 'ferror', 'fflush', 'fgets', 'field', 'file', 'filetostr', 'filter', 'fklabel', 'fkmax', 'fldlist', 'flock', 'floor', 'fontmetric', 'fopen', 'for', 'forceext', 'forcepath', 'found', 'fputs', 'fread', 'fseek', 'fsize', 'ftime', 'fullpath', 'fv', 'fwrite', 'getbar', 'getcolor', 'getcp', 'getdir', 'getenv', 'getfile', 'getfldstate', 'getfont', 'gethost', 'getnextmodified', 'getobject', 'getpad', 'getpem', 'getpict', 'getprinter', 'gomonth', 'header', 'home', 'hour', 'idxcollate', 'iif', 'imestatus', 'indbc', 'indexseek', 'inkey', 'inlist', 'insmode', 'int', 'isalpha', 'isblank', 'iscolor', 'isdigit', 'isexclusive', 'isflocked', 'ishosted', 'isleadbyte', 'islower', 'ismouse', 'isnull', 'isreadonly', 'isrlocked', 'isupper', 'justdrive', 'justext', 'justfname', 'justpath', 'juststem', 'key', 'keymatch', 'lastkey', 'left', 'leftc', 'len', 'lenc', 'like', 'likec', 'lineno', 'loadpicture', 'locfile', 'lock', 'log', 'log10', 'lookup', 'lower', 'ltrim', 'lupdate', 'max', 'mcol', 'mdown', 'mdx', 'mdy', 'memlines', 'memory', 'menu', 'message', 'messagebox', 'min', 'minute', 'mline', 'mod', 'month', 'mrkbar', 'mrkpad', 'mrow', 'mton', 'mwindow', 'ndx', 'newobject', 'normalize', 'ntom', 'numlock', 'nvl', 'objnum', 'objtoclient', 'objvar', 'occurs', 'oemtoansi', 'oldval', 'on', 'order', 'os', 'pad', 'padc', 'padl', 'padr', 'parameters', 'payment', 'pcol', 'pcount', 'pemstatus', 'pi', 'popup', 'primary', 'printstatus', 'prmbar', 'prmpad', 'program', 'prompt', 'proper', 'prow', 'prtinfo', 'putfile', 'pv', 'rand', 'rat', 'ratc', 'ratline', 'rdlevel', 'readkey', 'reccount', 'recno', 'recsize', 'refresh', 'relation', 'replicate', 'requery', 'rgb', 'rgbscheme', 'right', 'rightc', 'rlock', 'round', 'row', 'rtod', 'rtrim', 'savepicture', 'scheme', 'scols', 'sec', 'seconds', 'seek', 'select', 'set', 'setfldstate', 'sign', 'sin', 'skpbar', 'skppad', 'soundex', 'space', 'sqlcancel', 'sqlcolumns', 'sqlcommit', 'sqlconnect', 'sqldisconnect', 'sqlexec', 'sqlgetprop', 'sqlmoreresults', 'sqlrollback', 'sqlsetprop', 'sqlstringconnect', 'sqltables', 'sqrt', 'srows', 'str', 'strconv', 'strtofile', 'strtran', 'stuff', 'stuffc', 'substr', 'substrc', 'sum', 'sys', 'sysmetric', 'tablerevert', 'tableupdate', 'tag', 'tagcount', 'tagno', 'tan', 'target', 'time', 'transform', 'trim', 'ttoc', 'ttod', 'txnlevel', 'txtwidth', 'type', 'unique', 'updated', 'upper', 'used', 'val', 'varread', 'vartype', 'version', 'wborder', 'wchild', 'wcols', 'week', 'wexist', 'wfont', 'wlast', 'wlcol', 'wlrow', 'wmaximum', 'wminimum', 'wontop', 'woutput', 'wparent', 'wread', 'wrows', 'wtitle', 'wvisible', 'year',}-- Define VFP9 System Variables (unchanged)local sysvars = { '_alignment', '_asciicols', '_asciirows', '_assist', '_beautify', '_box', '_browser', '_builder', '_calcmem', '_calcvalue', '_cliptext', '_converter', '_coverage', '_curobj', '_datetimeformat', '_dblclick', '_diarydate', '_dos', '_fontclass', '_foxbaseclass', '_foxdoc', '_foxdragdrop', '_foxdroptarget', '_foxgraph', '_gallery', '_gengraph', '_genhtml', '_genmenu', '_genpd', '_genscrn', '_genxtab', '_getexpr', '_helpwebdevonly', '_helpwebdirectory', '_helpwebfiller1', '_helpwebfiller2', '_helpwebmsdnonline', '_helpwebmsfthomepage', '_helpwebsearch', '_helpwebtutorial', '_helpwebvfpfaq', '_helpwebvfpfreestuff', '_helpwebvfphomepage', '_helpwebvfponlinesupport', '_helpwebvfpsendfeedback', '_helpwebvsprodnews', '_include', '_indent', '_lmargin', '_mac', '_mbr_appnd', '_mbr_cpart', '_mbr_delet', '_mbr_font', '_mbr_goto', '_mbr_grid', '_mbr_link', '_mbr_mode', '_mbr_mvfld', '_mbr_mvprt', '_mbr_seek', '_mbr_sp100', '_mbr_sp200', '_mbr_szfld', '_mbrowse', '_mda_appnd', '_mda_avg', '_mda_brow', '_mda_calc', '_mda_copy', '_mda_count', '_mda_label', '_mda_pack', '_mda_reprt', '_mda_rindx', '_mda_setup', '_mda_sort', '_mda_sp100', '_mda_sp200', '_mda_sp300', '_mda_sum', '_mda_total', '_mdata', '_mdiary', '_med_beaut', '_med_bldex', '_med_clear', '_med_copy', '_med_cut', '_med_cvtst', '_med_exblk', '_med_find', '_med_finda', '_med_goto', '_med_insob', '_med_link', '_med_obj', '_med_paste', '_med_pref', '_med_pstlk', '_med_redo', '_med_repl', '_med_repla', '_med_slcta', '_med_sp100', '_med_sp200', '_med_sp300', '_med_sp400', '_med_sp500', '_med_sp600', '_med_undo', '_medit', '_mfi_clall', '_mfi_close', '_mfi_export', '_mfi_import', '_mfi_new', '_mfi_open', '_mfi_pgset', '_mfi_prevu', '_mfi_print', '_mfi_printonecopy', '_mfi_quit', '_mfi_revrt', '_mfi_savas', '_mfi_save', '_mfi_saveashtml', '_mfi_send', '_mfi_setup', '_mfi_sp100', '_mfi_sp200', '_mfi_sp300', '_mfi_sp400', '_mfi_sysprint', '_mfile', '_mfiler', '_mfirst', '_mlabel', '_mlast', '_mline', '_mmacro', '_mmb_delet', '_mmb_gener', '_mmb_gopts', '_mmb_insbr', '_mmb_insrt', '_mmb_mopts', '_mmb_prevu', '_mmb_quick', '_mmb_sp100', '_mmb_sp200', '_mmb_sp300', '_mmbldr', '_mouseevents', '_mouseeventsnodbl', '_mpr_beaut', '_mpr_cancl', '_mpr_compl', '_mpr_do', '_mpr_docum', '_mpr_formwz', '_mpr_gener', '_mpr_graph', '_mpr_resum', '_mpr_sp100', '_mpr_sp200', '_mpr_sp300', '_mpr_suspend', '_mprog', '_mproj', '_mrc_appnd', '_mrc_chnge', '_mrc_cont', '_mrc_delet', '_mrc_goto', '_mrc_locat', '_mrc_recal', '_mrc_repl', '_mrc_seek', '_mrc_sp100', '_mrc_sp200', '_mrecord', '_mreport', '_mrqbe', '_mscreen', '_msm_data', '_msm_edit', '_msm_file', '_msm_format', '_msm_prog', '_msm_recrd', '_msm_systm', '_msm_text', '_msm_tools', '_msm_view', '_msm_windo', '_mst_about', '_mst_ascii', '_mst_calcu', '_mst_captr', '_mst_dbase', '_mst_diary', '_mst_docum', '_mst_filer', '_mst_help', '_mst_hphow', '_mst_hpsch', '_mst_macro', '_mst_msdnc', '_mst_msdni', '_mst_msdns', '_mst_office', '_mst_puzzl', '_mst_samp', '_mst_sp100', '_mst_sp200', '_mst_sp300', '_mst_specl', '_mst_techs', '_msysmenu', '_msystem', '_mtable', '_mtb_appnd', '_mtb_cpart', '_mtb_delet', '_mtb_delrc', '_mtb_goto', '_mtb_link', '_mtb_mvfld', '_mtb_mvprt', '_mtb_props', '_mtb_recal', '_mtb_sp100', '_mtb_sp200', '_mtb_sp300', '_mtb_sp400', '_mtb_szfld', '_mti_callstack', '_mti_dbgout', '_mti_locals', '_mti_runactivedoc', '_mti_trace', '_mti_watch', '_mtl_browser', '_mtl_coverage', '_mtl_debugger', '_mtl_gallery', '_mtl_macro', '_mtl_optns', '_mtl_sp100', '_mtl_sp200', '_mtl_sp300', '_mtl_sp400', '_mtl_spell', '_mtl_wzrds', '_mtools', '_mvi_toolb', '_mview', '_mwi_arran', '_mwi_clear', '_mwi_cmd', '_mwi_color', '_mwi_debug', '_mwi_hide', '_mwi_hidea', '_mwi_min', '_mwi_move', '_mwi_rotat', '_mwi_showa', '_mwi_size', '_mwi_sp100', '_mwi_sp200', '_mwi_toolb', '_mwi_trace', '_mwi_view', '_mwi_zoom', '_mwindow', '_mwizards', '_mwz_all', '_mwz_applic', '_mwz_application', '_mwz_database', '_mwz_form', '_mwz_foxdoc', '_mwz_import', '_mwz_label', '_mwz_mail', '_mwz_pivot', '_mwz_query', '_mwz_reprt', '_mwz_setup', '_mwz_table', '_mwz_upsizing', '_mwz_webpublishing', '_netware', '_olebasecontrol', '_oledragdrop', '_oracle', '_padvance', '_pageno', '_pbpage', '_pcolno', '_pcopies', '_pdparms', '_pdriver', '_pdsetup', '_pecode', '_peject', '_pepage', '_pform', '_plength', '_plineno', '_ploffset', '_ppitch', '_pquality', '_pretext', '_pscode', '_pspacing', '_pwait', '_rectclass', '_rmargin', '_runactivedoc', '_samples', '_scctext', '_screen', '_shell', '_spellchk', '_sqlserver', '_startup', '_tabs', '_tally', '_text', '_throttle', '_transport', '_triggerlevel', '_unix', '_vfp', '_viewport', '_webdevonly', '_webmenu', '_webmsfthomepage', '_webvfphomepage', '_webvfponlinesupport', '_windows', '_wizard', '_wrap',}-- Define Highlight Groupslocal function set_highlights() api.nvim_set_hl( 0, 'vfpSpecial', { link = 'Special' } ) api.nvim_set_hl( 0, 'vfpPreProc', { link = 'PreProc' } ) api.nvim_set_hl( 0, 'vfpCmd', { link = 'Statement' } ) api.nvim_set_hl( 0, 'vfpFunc', { link = 'Identifier' } ) api.nvim_set_hl( 0, 'vfpSysVar', { link = 'String' } ) api.nvim_set_hl( 0, 'vfpString', { link = 'String' } ) api.nvim_set_hl( 0, 'vfpConst', { link = 'Constant' } ) api.nvim_set_hl( 0, 'vfpNumber', { link = 'Number' } ) api.nvim_set_hl( 0, 'vfpFloat', { link = 'Float' } ) api.nvim_set_hl( 0, 'vfpOperator', { link = 'Operator' } ) api.nvim_set_hl( 0, 'vfpComment', { link = 'Comment' } ) api.nvim_set_hl( 0, 'vfpError', { link = 'Error' } ) api.nvim_set_hl( 0, 'vfpXmlFunc', { link = 'Function' } ) api.nvim_set_hl( 0, 'vfpOop', { link = 'Type' } )endset_highlights()-- Define Syntax Patterns with proper matchaddlocal function define_syntax() local buf = api.nvim_get_current_buf() local priority = 10 -- Standard priority for syntax matches local id_base = 1000 -- Unique ID base to avoid collisions -- Helper to apply matchadd with consistent args local function add_match( group, pattern, pri, id ) fn.matchadd( group, pattern ) end -- Special Characters local specials = { [[^\s*!]], '&', [[;\s*$]], [[^\s*=]], [[^\s*\\]], [[^\s*\\\\]], [[^\s*?]], [[^\s*??]], [[^\s*???]], [[\<m\>\.]], [[\<this\>\.]], [[\<thisform\>\.]], [[\<thisformset\>\.]], } for i, pat in ipairs( specials ) do add_match( 'vfpSpecial', pat, priority, id_base + i ) end -- Preprocessor Directives local preprocs = { [[^\s*#\s*\(if\|elif\|else\|endif\)]], [[^\s*#\s*\(ifdef\|ifndef\|endif\)]], [[^\s*#\s*\(define\|undef\)]], [[^\s*#\s*\<region\>]], [[^\s*#\s*\<include\>]], [[^\s*#\s*\<itsexpression\>]], [[^\s*#\s*\<readclauses\>]], [[^\s*#\s*\<section\>]], [[^\s*#\s*\<wname\>]], } for i, pat in ipairs( preprocs ) do add_match( 'vfpPreProc', pat, priority, id_base + 100 + i ) end -- Commands local cmd_pattern = [[\<]] .. table.concat( commands, [[\>\|\<]] ) .. [[\>]] add_match( 'vfpCmd', cmd_pattern, priority, id_base + 200 ) -- Functions (with paren) local func_pattern = [[\<]] .. table.concat( functions, [[\>\|\<]] ) .. [[\>\s*(]] add_match( 'vfpFunc', func_pattern, priority, id_base + 300 ) -- System Variables local sysvar_pattern = [[\<]] .. table.concat( sysvars, [[\>\|\<]] ) .. [[\>]] add_match( 'vfpSysVar', sysvar_pattern, priority, id_base + 400 ) -- Strings -- Strings section from define_syntax() add_match( 'vfpString', [["[^"]*"]], priority, id_base + 500 ) -- Double-quoted add_match( 'vfpString', [['[^']*']], priority, id_base + 501 ) -- Single-quoted add_match( 'vfpString', '\\[[^\\]]*\\]', priority, id_base + 502 ) -- Bracketed -- Constants add_match( 'vfpConst', [[\.\(t\|f\|y\|n\|null\)\.]], priority, id_base + 600 ) add_match( 'vfpConst', [[\<null\>]], priority, id_base + 601 ) -- Numbers and Floats add_match( 'vfpNumber', [[\<[0-9]\+\>]], priority, id_base + 700 ) add_match( 'vfpFloat', [[\<[0-9]\+\.[0-9]*\(e[-+]\=[0-9]\+\)\=\>]], priority, id_base + 701 ) add_match( 'vfpFloat', [[\.[0-9]\+\(e[-+]\=[0-9]\+\)\=\>]], priority, id_base + 702 ) add_match( 'vfpFloat', [[\<[0-9]\+e[-+]\=[0-9]\+\>]], priority, id_base + 703 ) -- Operators local operators = { [[\$]], [[%]], [[&]], [[+]], [[-]], [[->]], [[!]], [[\.\(and\|not\|or\)\.]], [[\<and\>]], [[\<or\>]], [[\<not\>]], [[<]], [[<=]], [[<>]], [[!=]], [[#]], [[=]], [[==]], [[>]], [[>=]], [[@]], [[\*]], [[\<like\>]], } for i, op in ipairs( operators ) do add_match( 'vfpOperator', op, priority, id_base + 800 + i ) end -- Comments add_match( 'vfpComment', [[^\s*\*.*]], priority, id_base + 900 ) add_match( 'vfpComment', [[&&.*]], priority, id_base + 901 ) add_match( 'vfpComment', [[\<note\>.*]], priority, id_base + 902 ) -- VFP9-Specific: XML Functions local xml_functions = { 'xmltocursor', 'cursortoxml', 'xmlupdategram' } local xml_pattern = [[\<]] .. table.concat( xml_functions, [[\>\|\<]] ) .. [[\>\s*(]] add_match( 'vfpXmlFunc', xml_pattern, priority, id_base + 1000 ) -- VFP9-Specific: OOP Properties add_match( 'vfpOop', [[\<thisform\>\.]], priority, id_base + 1100 ) -- Syntax Syncing vim.cmd 'syntax sync minlines=1 maxlines=3'end-- Apply itdefine_syntax()-- Mark as loadedvim.b.current_syntax = 'vfp'neovim/init.lua
Modified+5 / −0 text lines
neovim/justfile
Modified+65 / −42 text lines
set shell := ['nu', '--commands']
# List available recipes.
default:
@just --list
# Reproduce some neovim issue
repro:
nvim -u repro.lua
puk:
nu puk.nu
puke:
@nu puk.nu update
@if ( "puk.plugins.updated.nuon" | path exists ) { mv puk.plugins.updated.nuon puk.plugins.nuon }
# DANGER NEVER CALL! delete all current neovim state, cache and other ephemeral data. does NOT delete the configs
nuke:
rm --interactive --recursive --force (nvim "--headless" "--clean" +'lua print(vim.fn.stdpath[[data]])' +q | complete | get stderr)
rm --interactive --recursive --force (nvim "--headless" "--clean" +'lua print(vim.fn.stdpath[[cache]])' +q | complete | get stderr)
rm --interactive --recursive --force (nvim "--headless" "--clean" +'lua print(vim.fn.stdpath[[state]])' +q | complete | get stderr)
# run all tests, or only the ones in the directory of file given
test path="tests":
timeit { nvim --headless --noplugin -u tests/minimal_init.lua -c "PlenaryBustedDirectory {{ path }} {minimal_init = 'tests/minimal_init.lua'}" +q }
# run manual tests
test-manual:
nvim -c "set rtp^=." -c "luafile tests/manual/input.lua"
# lint the nvim lua config code
lint:
lua-language-server --check=. --checklevel=Warning
# run nvim healthcheck in console
checkhealth:
@nvim --headless -c "luafile print_checkhealth.lua"
# run ast-grep refactoring on the neovim configuration
refac:
ast-grep scan --interactive
set shell := ['nu', '--commands']# List available recipes.default: @just --list# Reproduce some neovim issuerepro: nvim -u repro.luapuk: nu puk.nupuke: @nu puk.nu update @if ( "puk.plugins.updated.nuon" | path exists ) { mv --force puk.plugins.updated.nuon puk.plugins.nuon } @if ( "puk.parsers.updated.nuon" | path exists ) { mv --force puk.parsers.updated.nuon puk.parsers.nuon }# DANGER NEVER CALL! delete all current neovim state, cache and other ephemeral data. does NOT delete the configsnuke: rm --interactive --recursive --force (nvim "--headless" "--clean" +'lua print(vim.fn.stdpath[[data]])' +q | complete | get stderr) rm --interactive --recursive --force (nvim "--headless" "--clean" +'lua print(vim.fn.stdpath[[cache]])' +q | complete | get stderr) rm --interactive --recursive --force (nvim "--headless" "--clean" +'lua print(vim.fn.stdpath[[state]])' +q | complete | get stderr)# run all tests, or only the ones in the directory of file giventest path="tests": timeit { nvim --headless --noplugin -u tests/minimal_init.lua -c "PlenaryBustedDirectory {{ path }} {minimal_init = 'tests/minimal_init.lua', sequential = true}" +q }test-puk: nu --no-config-file tests/puk.nu# drive a live neovim and mutate its files from the outsidedrive-file-changed: nvim --headless --clean -l tests/drive/file_changed.lua# drive a real neovide window over rpc, without touching mouse or keyboarddrive-neovide: nvim --headless --clean -l tests/drive/neovide.luapivi-install: npm --prefix pivi ci --ignore-scripts --no-audit --no-fundtest-pivi: npm --prefix pivi test just test tests/bugabinga/pivi just test-pivi-inputtest-pivi-input: nvim --headless --clean -l tests/drive/pivi.lua# run manual teststest-manual: nvim -c "set rtp^=." -c "luafile tests/manual/input.lua"# lint the nvim lua config codelint: with-env { VIMRUNTIME: (nvim --headless --clean +"lua io.stdout:write(vim.env.VIMRUNTIME)" +q | complete | get stdout) } { lua-language-server --check=. --checklevel=Warning }# run nvim healthcheck in consolecheckhealth: @nvim --headless -c "luafile print_checkhealth.lua"# run ast-grep refactoring on the neovim configurationrefac: ast-grep scan --interactiveneovim/lsp/bashls.lua
Addednew file mode 100644+5 / −0 text lines
neovim/lsp/denols.lua
Modified+3 / −3 text lines
local result = client.request_sync('deno/virtualTextDocument', params) local result = client:request_sync('deno/virtualTextDocument', params) client.request('workspace/executeCommand', params, function(err, _result, ctx) client:request('workspace/executeCommand', params, function(err, _result, ctx)neovim/lsp/html.lua
Modified+6 / −1 text lines
neovim/lsp/jdtls.lua
Modified+1 / −2 text lines
neovim/lsp/lua_ls.lua
Modified+0 / −38 text lines
on_init = function ( client ) if client.workspace_folders then local root = client.workspace_folders[1].name local abs_root = assert( realpath( root ) ) local path = normalize( abs_root ) local abs_config = assert( realpath( vim.fn.stdpath 'config' ) ) local config_path = normalize( abs_config ) if path ~= config_path then return end end client.config.settings.Lua = vim.tbl_deep_extend( 'force', client.config.settings.Lua, { runtime = { version = 'LuaJIT', path = { 'lua/?.lua', 'lua/?/init.lua', }, }, diagnostics = { globals = { 'vim', 'describe', 'it', }, }, workspace = { checkThirdParty = false, library = { vim.env.VIMRUNTIME, '${3rd}/luv/library', }, }, } ) end,neovim/lsp/marksman.lua
Modified+1 / −1 text lines
neovim/lsp/qmlls.lua
Addednew file mode 100644+11 / −0 text lines
neovim/lua/bugabinga/cmdline/format.lua
Modified+2 / −1 text lines
vim.validate({ prompt = { prompt, 'string' }, max_width = { max_width, 'number' } })neovim/lua/bugabinga/cmdline/popupmenu.lua
Modified+1 / −2 text lines
border = vim.g.border_style,neovim/lua/bugabinga/cmdline/render.lua
Modified+0 / −3 text lines
neovim/lua/bugabinga/cmdline/state.lua
Modified+6 / −8 text lines
neovim/lua/bugabinga/code_action.lua
Modified+5 / −4 text lines
---@cast params lsp.CodeActionParamsneovim/lua/bugabinga/cycle.lua
Modified+11 / −7 text lines
vim.hl.range(bufnr, hl_ns, h.icon_hl, { h.line_idx, 0 }, { h.line_idx, 2 }) vim.api.nvim_buf_add_highlight(bufnr, hl_ns, 'CycleBufferFileName', h.line_idx, h.name_start - 1, h.name_end_exclusive - 1) vim.api.nvim_buf_clear_highlight(state.popup_buf, state.hl_ns, 0, -1) vim.api.nvim_buf_clear_namespace(state.popup_buf, state.hl_ns, 0, -1) border = vim.g.border_style,neovim/lua/bugabinga/d2.lua
Modified+4 / −6 text lines
vim.api.nvim_set_option_value('spell', false, { win = winnr }) local bufnr = (args and args.bufnr) or vim.api.nvim_get_current_buf() local bufnr = (args and args.buf) or vim.api.nvim_get_current_buf() local preview_buf = args.bufnr map.normal { keys = '<leader>dp', command = preview_toggle, buffer = preview_buf, description = 'Toggle D2 preview' } map.normal { keys = '<leader>du', command = preview_update, buffer = preview_buf, description = 'Update D2 preview' } map.normal { keys = 'q', command = close_preview_window, buffer = preview_buf, description = 'Close D2 preview' } map.normal { keys = '<leader>dp', command = preview_toggle, buffer = args.buf, description = 'Toggle D2 preview' } map.normal { keys = '<leader>du', command = preview_update, buffer = args.buf, description = 'Update D2 preview' } map.normal { keys = 'q', command = close_preview_window, buffer = args.buf, description = 'Close D2 preview' }neovim/lua/bugabinga/devicons.lua
Modified+4 / −4 text lines
neovim/lua/bugabinga/diagnostic.lua
Modified+7 / −9 text lines
neovim/lua/bugabinga/editorconfig.lua
Modified+0 / −1 text lines
neovim/lua/bugabinga/file_changed.lua
Addednew file mode 100644+319 / −0 text lines
-- Sane handling of files that change on disk while loaded in neovim.---- Neovim already has `autoread` on by default, but it only ever looks at the-- filesystem after a shell command, after `:checktime` and on `FocusGained`-- ( see `:help timestamp` ). So a formatter, a git checkout or an agent can-- rewrite a file and neovim happily keeps showing stale text for minutes.---- Three layers, from fastest to most reliable:---- 1. `uv.fs_event` on the *parent directory* of every loaded file-- -> push notification, millisecond latency, but unreliable-- ( network shares, WSL interop, watcher limits ).-- 2. a plain repeating timer-- -> the floor. always works, independent of terminal focus reporting-- and of `updatetime`.-- 3. `FocusGained` and friends-- -> zero latency for the common "alt tab back into neovim" case.---- All three funnel into `:checktime`, which decides nothing by itself. The-- actual policy lives in the `FileChangedShell` handler below.---- Note on the directory watch: tools write files by creating a temporary file-- and renaming it over the target. That replaces the inode, so an `fs_event`-- registered on the *file* goes deaf after the first write. Watching the-- containing directory survives this.local auto = require 'std.auto'local uv = vim.uv-- reading a file again must stay undoable, also for big files.-- see `:help 'undoreload'`vim.opt.undoreload = 100000-- global value. plugins may still set a local one, that is their business.vim.opt.autoread = true--[[ POLICY ]]-- `FileChangedShell` only fires for the cases neovim can not decide on its-- own. A clean buffer whose file changed is reloaded silently by `autoread`-- and never reaches this handler.---- Defining this autocommand suppresses the built in W11/W12/W16/E211 warnings-- and dialogs entirely, so it owns the whole user experience.--- remembers which buffers we already complained about, to not repeat--- ourselves on every check. keyed by buffer number.--- deliberately not a buffer local variable: `FileChangedShell` runs with the--- buffer list locked.---@type table<integer, string>local warned = {}local relative_name = function ( path ) return vim.fn.fnamemodify( path, ':~:.' ) endlocal warn_once = function ( buffer, reason, message ) if warned[buffer] == reason then return end warned[buffer] = reason vim.notify( message, vim.log.levels.WARN, { title = 'file changed', } )endauto 'file_changed_policy' { { description = 'decide what to do with a file that changed outside of neovim', events = 'FileChangedShell', command = function ( event ) local reason = vim.v.fcs_reason local name = relative_name( event.file ) if reason == 'mode' or reason == 'time' then -- permissions or timestamp only, contents are identical. -- typical for version control checkouts. nothing to lose. vim.v.fcs_choice = 'reload' elseif reason == 'changed' then -- contents differ and the buffer is clean. -- 'edit' instead of 'reload' so that 'fileformat', 'fileencoding' and -- 'binary' are detected again. a formatter or a `dos2unix` run may -- have changed them. vim.v.fcs_choice = 'edit' elseif reason == 'conflict' then -- changed on disk AND in the buffer. never pick a winner. vim.v.fcs_choice = '' warn_once( event.buf, reason, ( '`%s` changed on disk **and** in the buffer.\n' .. '`:DiffDisk` compare · `:e!` take disk · `:w!` take buffer' ):format( name ) ) elseif reason == 'deleted' then -- keep the text. it may be the only copy left. vim.v.fcs_choice = '' warn_once( event.buf, reason, ( '`%s` is gone from disk.' ):format( name ) ) end end, }, { description = 'report a file that was reloaded from disk', events = 'FileChangedShellPost', command = function ( event ) warned[event.buf] = nil if vim.wo.diff then vim.cmd.diffupdate() end vim.notify( ( 'reloaded `%s`' ):format( relative_name( event.file ) ), vim.log.levels.INFO, { title = 'file changed', } ) end, }, { -- writing, or reading the file again ( `:e!`, `:edit` ), means buffer and -- disk agree again. without this the next conflict would be swallowed by -- the latch of the previous one. description = 'forget complaints once the buffer is in sync again', events = { 'BufWritePost', 'BufReadPost', 'BufWipeout', }, command = function ( event ) warned[event.buf] = nil end, },}--[[ BUFFERS ]]--- the file a buffer is backed by, or nil if it is not a plain file buffer.---@param buffer integer---@return string? path, string? directory, string? filelocal file_of = function ( buffer ) if not vim.api.nvim_buf_is_valid( buffer ) then return end if vim.bo[buffer].buftype ~= '' then return end -- reloading these costs more than the staleness does if vim.bo[buffer].filetype == 'bigfile' then return end local name = vim.api.nvim_buf_get_name( buffer ) -- `oil://`, `fugitive://`, ... are not files if name == '' or name:match '^%a[%w+.-]*://' then return end local path = vim.fs.normalize( vim.fn.fnamemodify( name, ':p' ) ) return path, vim.fs.dirname( path ), vim.fs.basename( path )end--[[ TRIGGERS ]]-- Everything funnels through one debounced, quiescence gated `:checktime`.---- The gate matters: a lot of tools truncate a file and only then write it,-- and on windows the gap between the two can be hundreds of milliseconds.-- Reading in that window loads an empty file, the cursor gets clamped to-- line 1, and the next read restores the contents but no longer knows where-- the cursor was. So wait until size and mtime of every watched file stopped-- moving before looking at them.local settle_delay = 150local settle_attempts = 8local timer = assert( uv.new_timer() )---@type table<string, string>?local previous_fingerprint = nillocal attempt = 0--- size and modification time of every file a loaded buffer is backed by.--- The second return value marks a file that is almost certainly half written:--- it is empty while its buffer still holds text. Waiting for the fingerprint--- to stop moving does not catch this, because a truncated file sits there--- perfectly stable until the writer gets around to producing its bytes.---@return table<string, string> fingerprints, boolean half_writtenlocal fingerprint = function () local prints = {} local half_written = false for _, buffer in ipairs( vim.api.nvim_list_bufs() ) do if vim.api.nvim_buf_is_loaded( buffer ) then local path = file_of( buffer ) if path then local stat = uv.fs_stat( path ) prints[path] = stat and ( '%d:%d:%d' ):format( stat.size, stat.mtime.sec, stat.mtime.nsec ) or 'gone' if stat and stat.size == 0 and vim.api.nvim_buf_line_count( buffer ) > 1 then half_written = true end end end end return prints, half_writtenendlocal settlelocal function arm ( delay ) timer:stop() timer:start( delay, 0, vim.schedule_wrap( settle ) )endsettle = function () -- the reload is postponed by neovim until it is harmless anyway, but -- checking while typing or selecting only produces noise. if vim.fn.getcmdwintype() ~= '' then return end -- E11 if vim.api.nvim_get_mode().mode ~= 'n' then return end local current, half_written = fingerprint() local moved = not vim.deep_equal( previous_fingerprint, current ) if attempt < settle_attempts and ( moved or half_written ) then -- somebody is still writing. look again in a moment. -- after `settle_attempts` we give up and read whatever is there: the file -- may really have been emptied on purpose. previous_fingerprint = current attempt = attempt + 1 arm( settle_delay ) return end previous_fingerprint = nil attempt = 0 pcall( vim.cmd.checktime )endlocal check = function ( delay ) previous_fingerprint = nil attempt = 0 arm( delay )endauto 'file_changed_triggers' { description = 'check timestamps whenever attention returns to neovim', events = { 'FocusGained', 'BufEnter', 'TermLeave', 'TermClose', 'VimResume', 'InsertLeave', }, command = function () check( 50 ) end,}-- The floor. Deliberately not `CursorHold`: that event is edge triggered, it-- fires once per idle period and never again until the cursor moves. Sitting-- still and reading is exactly when an external change would be missed.local poll_interval = 2000local poll = assert( uv.new_timer() )poll:start( poll_interval, poll_interval, vim.schedule_wrap( function () -- do not interrupt a debounce that is already running if timer:is_active() then return end check( 0 )end ) )--[[ DIRECTORY WATCHERS ]]-- one `uv_fs_event_t` per directory, shared by all buffers in it.local max_directories = 64---@type table<string, { handle: uv.uv_fs_event_t, files: table<string, true> }>local watchers = {}--- plain lua, no `vim.*`: this also runs inside libuv callbacks.local basename = function ( path ) return path:match '[^/\\]*$' endlocal watch = function ( buffer ) local _, directory, file = file_of( buffer ) if not directory or not file then return end local watcher = watchers[directory] if watcher then watcher.files[file] = true return end if vim.tbl_count( watchers ) >= max_directories then return end local handle = assert( uv.new_fs_event() ) local _, error_message = handle:start( directory, {}, function ( error, changed ) if error then return end local current = watchers[directory] if not current then return end -- `changed` is nil on some platforms. then we can not tell which file it -- was and have to check them all, which `:checktime` does anyway. if changed and not current.files[basename( changed )] then return end check( 100 ) end ) if error_message then -- unwatchable directory ( network share, permissions, ... ). -- the poll timer still covers this buffer. handle:close() return end watchers[directory] = { handle = handle, files = { [file] = true, }, }endlocal unwatch = function ( buffer ) local _, directory, file = file_of( buffer ) if not directory or not file then return end local watcher = watchers[directory] if not watcher then return end watcher.files[file] = nil if next( watcher.files ) == nil then watcher.handle:stop() watcher.handle:close() watchers[directory] = nil endendauto 'file_changed_watchers' { { description = 'watch the directory of every file backed buffer', events = { 'BufReadPost', 'BufNewFile', 'BufFilePost', 'BufWritePost', }, command = function ( event ) watch( event.buf ) end, }, { description = 'release the directory watcher when a buffer goes away', events = { 'BufWipeout', 'BufFilePre', }, command = function ( event ) unwatch( event.buf ) end, },}-- buffers that were already loaded before this module ranfor _, buffer in ipairs( vim.api.nvim_list_bufs() ) do if vim.api.nvim_buf_is_loaded( buffer ) then watch( buffer ) endend--[[ COMMANDS ]]vim.api.nvim_create_user_command( 'DiffDisk', function () local filetype = vim.bo.filetype vim.cmd 'vertical new' vim.opt_local.buftype = 'nofile' vim.opt_local.bufhidden = 'wipe' vim.opt_local.swapfile = false vim.cmd 'read ++edit #' vim.cmd '0d_' vim.bo.filetype = filetype vim.cmd 'diffthis' vim.cmd 'wincmd p' vim.cmd 'diffthis'end, { desc = 'diff the current buffer against the file on disk', } )neovim/lua/bugabinga/file_explorer.lua
Modified+0 / −5 text lines
neovim/lua/bugabinga/format.lua
Modified+48 / −44 text lines
local has_treesitter_parser = function ( _, ctx ) local filetype = vim.bo[ctx.buf].filetype if filetype == '' then return true end local language = vim.treesitter.language.get_lang( filetype ) local ok = pcall( vim.treesitter.get_string_parser, '', language ) return okendlocal conform = puk 'conform'puk.defer 'conform' ( function ( conform ) conform.setup { formatters = { injected = { condition = has_treesitter_parser }, sqruff = { command = 'sqruff', args = { 'fix', '-' }, stdin = true, },conform.setup { formatters = { -- lenient JSON parsing so formatting repairs trailing commas instead of -- refusing; applies to every repo, no biome.json needed. append_args keeps -- the builtin args ($FILENAME, indent fallback) untouched biome = { append_args = { '--json-parse-allow-trailing-commas=true' }, formatters_by_ft = { toml = { 'taplo' }, sh = { 'shfmt' }, just = { 'just' }, go = { 'goimports', 'gofmt' }, kdl = { 'kdlfmt' }, nu = { 'nufmt' }, sql = { 'sqruff' }, d2 = { 'd2' }, markdown = { 'dprint', 'injected' }, ['markdown.mdx'] = { 'injected' }, html = { 'biome' }, javascript = { 'biome' }, javascriptreact = { 'biome' }, typescript = { 'biome' }, typescriptreact = { 'biome' }, json = { 'biome' }, jsonc = { 'biome' }, python = { 'ruff_format', 'ruff_fix', 'ruff_organize_imports' }, sass = { 'deno_fmt' }, -- Use the “_” file type to run formatters on file types that don't -- have other formatters configured. ['_'] = { 'trim_whitespace', 'trim_newlines' }, }, formatters_by_ft = { toml = { 'taplo' }, sh = { 'shfmt' }, just = { 'just' }, go = { 'goimports', 'gofmt' }, zig = { 'zigfmt' }, ziggy = { 'ziggy' }, ziggy_schema = { 'ziggy_schema' }, kdl = { 'kdlfmt' }, nu = { 'nufmt' }, qml = { 'qmlformat' }, sql = { 'sqruff' }, d2 = { 'd2' }, markdown = { 'dprint', 'injected' }, html = { 'superhtml' }, shtml = { 'superhtml' }, superhtml = { 'superhtml' }, javascript = { 'biome' }, javascriptreact = { 'biome' }, typescript = { 'biome' }, typescriptreact = { 'biome' }, json = { 'biome' }, jsonc = { 'biome' }, -- jsonl must never be rewritten by a JSON formatter (one object per line) jsonl = {}, python = { 'ruff_format', 'ruff_fix', 'ruff_organize_imports' }, sass = { 'deno_fmt' }, -- Use the “_” file type to run formatters on file types that don't -- have other formatters configured. ['_'] = { 'trim_whitespace', 'trim_newlines' }, }, log_level = dbg.get() and vim.log.levels.TRACE or vim.log.levels.ERROR,}neovim/lua/bugabinga/fun.lua
Modified+23 / −19 text lines
local opts = { width = 69, delay_ms = 69, inc_ms = 42 } dbg.kind( 'TRACE', 'Showing specs with {0}', opts ) require 'specs'.show_specs( opts ) local window = vim.api.nvim_get_current_win() local buffer = vim.api.nvim_win_get_buf( window ) local row = vim.api.nvim_win_get_cursor( window )[1] - 1 vim.hl.range( buffer, flash_ns, 'IncSearch', { row, 0 }, { row, 0 }, { regtype = 'V', -- linewise: flash the whole line regardless of column timeout = 300, } )puk.defer 'specs' ( function ( specs ) specs.setup { show_jumps = false, min_jump = 10, popup = { delay_ms = 10, -- delay before popup displays inc_ms = 10, -- time increments used for fade/resize effects blend = 10, -- starting blend, between 0-100 (fully transparent), see :h winblend width = 10, winhl = 'Cursor', fader = specs.exp_fader, resizer = specs.shrink_resizer,-- automatic cursor-trail animation on jumps, so the eye can follow a long-- motion to the new cursor position. this replaces specs.nvim.-- scroll animation is disabled on purpose: it fights fast navigation.puk.defer 'mini.animate' ( function ( animate ) animate.setup { cursor = { enable = true, timing = animate.gen_timing.linear { duration = 100, unit = 'total' },neovim/lua/bugabinga/fuzzy_find.lua
Modified+0 / −7 text lines
neovim/lua/bugabinga/health.lua
Modified+3 / −5 text lines
neovim/lua/bugabinga/image.lua
Addednew file mode 100644+246 / −0 text lines
-- Modified from folke/snacks.nvim (Apache-2.0); see lua/bugabinga/image/NOTICE.local auto = require 'std.auto'local kitty = require 'bugabinga.image.kitty'local raster = require 'bugabinga.image.raster'local terminal = require 'bugabinga.image.terminal'local geometry = require 'bugabinga.image.geometry'local patterns = { '*.[pP][nN][gG]', '*.[jJ][pP][gG]', '*.[jJ][pP][eE][gG]', '*.[wW][eE][bB][pP]', '*.[gG][iI][fF]' }local buffers, resources, placements = {}, {}, {}local queued, measuring, suspended, exiting = false, false, false, falselocal redrawing = falselocal reconcilelocal function text(buf, message) if not vim.api.nvim_buf_is_valid(buf) then return end local readonly = vim.bo[buf].readonly vim.bo[buf].readonly = false vim.bo[buf].modifiable = true local lines = message and vim.split(message:gsub('\r\n', '\n'), '\n', { plain = true }) or {} vim.api.nvim_buf_set_lines(buf, 0, -1, false, lines) vim.bo[buf].modified = false vim.bo[buf].modifiable = false vim.bo[buf].readonly = readonlyendlocal function remove(win) local placement = placements[win] if placement then kitty.delete(placement.image, placement.id) placements[win] = nil endendlocal function hide() for win in pairs(placements) do remove(win) endendlocal function schedule() if queued or exiting then return end queued = true vim.schedule(function() queued = false if not exiting then reconcile() end end)endlocal function forget(resource) if resource.uploaded then kitty.delete(resource.id); resource.uploaded = false endendlocal function refresh(invalidate) if exiting or not next(buffers) then return end hide() if invalidate then for _, resource in pairs(resources) do forget(resource) end end measuring = true terminal.refresh(function(size, err) if exiting then return end measuring = false for buf, state in pairs(buffers) do if state.resource and not state.resource.failed then if state.error ~= err then state.error = err text(buf, err and ('Image: ' .. err) or nil) end end end if size then schedule() end end)endlocal function release(buf) local state = buffers[buf] if not state then return end buffers[buf] = nil if state.cancel then state.cancel() end for win, placement in pairs(placements) do if placement.buf == buf then remove(win) end end local resource = state.resource if resource then resource.references = resource.references - 1 if resource.references == 0 then forget(resource) resources[resource.key] = nil end endendlocal function response(ev) local fields, message = ev.data.sequence:match('^\27_G([^;]+);(.+)') local id = fields and tonumber((',' .. fields):match(',i=(%d+)')) if not id or message == 'OK' then return end for _, resource in pairs(resources) do if resource.id == id then if message:match('^ENOENT') and not resource.failed then resource.uploaded = false for win, placement in pairs(placements) do if placement.image == id then remove(win) end end else resource.failed = true for buf, state in pairs(buffers) do if state.resource == resource then state.error = message; text(buf, 'Image: ' .. message) end end end schedule() return end endendlocal function load(buf) release(buf) local state = {} buffers[buf] = state vim.bo[buf].swapfile = false vim.bo[buf].readonly = true vim.bo[buf].filetype = 'image' text(buf, 'Loading image…') if not terminal.available() then state.error = 'Image viewing requires a Neovim terminal UI with Kitty graphics' text(buf, state.error) return end state.cancel = raster.prepare(vim.api.nvim_buf_get_name(buf), function(err, result) if exiting or buffers[buf] ~= state or not vim.api.nvim_buf_is_valid(buf) then return end state.cancel = nil if err then state.error = tostring(err) text(buf, 'Image: ' .. state.error) return end local resource = resources[result.key] if not resource then resource = vim.tbl_extend('force', result, { id = kitty.new_id(), references = 0 }) resources[result.key] = resource end resource.references = resource.references + 1 state.resource = resource text(buf) refresh(false) end)endlocal function floating_rect(win, config) local pos = vim.api.nvim_win_get_position(win) local border = config.border and config.border ~= 'none' and 2 or 0 return { row = pos[1] + 1, col = pos[2] + 1, cols = vim.api.nvim_win_get_width(win) + border, rows = vim.api.nvim_win_get_height(win) + border }endreconcile = function() if not next(buffers) or suspended or measuring or not terminal.available() then return end local cells = terminal.get() if not cells then return end local desired, floats = {}, {} for _, win in ipairs(vim.api.nvim_tabpage_list_wins(0)) do local config = vim.api.nvim_win_get_config(win) if not config.hide and not config.external then if config.relative ~= '' then floats[#floats + 1] = floating_rect(win, config) else local buf = vim.api.nvim_win_get_buf(win) local state = buffers[buf] if state and state.resource and not state.error then local info = vim.fn.getwininfo(win)[1] local rect = geometry.rectangle(info, state.resource, cells) if rect then desired[win] = { buf = buf, resource = state.resource, rect = rect } end end end end end for win, wanted in pairs(desired) do for _, rect in ipairs(floats) do if geometry.overlaps(wanted.rect, rect) then desired[win] = nil; break end end end for win, placement in pairs(placements) do local wanted = desired[win] if not wanted or placement.image ~= wanted.resource.id then remove(win) end end for win, wanted in pairs(desired) do local resource = wanted.resource if not resource.uploaded then local ok, err = kitty.upload(resource.id, resource.path) if not ok then buffers[wanted.buf].error = tostring(err) text(wanted.buf, 'Image: ' .. tostring(err)) remove(win) break end resource.uploaded = true end local placement = placements[win] if not placement then placement = { id = kitty.new_id(), image = resource.id, buf = wanted.buf } placements[win] = placement end if redrawing or not vim.deep_equal(placement.rect, wanted.rect) then local ok, err = kitty.place(resource.id, placement.id, wanted.rect) if ok then placement.rect = wanted.rect else remove(win) text(wanted.buf, 'Image: ' .. tostring(err)) end end end local visible = {} for _, placement in pairs(placements) do visible[placement.image] = true end for _, resource in pairs(resources) do if not visible[resource.id] then forget(resource) end end redrawing = falseendlocal register = auto 'bugabinga_image'register { { events = 'TermResponse', command = response }, { events = 'BufReadCmd', pattern = patterns, command = function(ev) load(ev.buf) end }, { events = 'BufWriteCmd', pattern = patterns, command = function() error('Image buffers are read-only') end }, { events = { 'BufUnload', 'BufWipeout' }, command = function(ev) release(ev.buf) end }, { events = { 'BufWinEnter', 'BufWinLeave', 'WinEnter', 'WinNew', 'WinClosed', 'WinResized', 'TabEnter', 'SessionLoadPost' }, command = schedule }, { events = 'OptionSet', pattern = { 'number', 'relativenumber', 'numberwidth', 'signcolumn', 'foldcolumn', 'statuscolumn', 'winbar', 'showtabline', 'laststatus', 'cmdheight' }, command = schedule }, { events = 'VimResized', command = function() refresh(false) end }, { events = { 'VimResume', 'FocusGained' }, command = function() suspended = false refresh(true) end }, { events = 'VimSuspend', command = function() suspended = true; hide() end }, { events = 'VimLeavePre', command = function() exiting = true hide() for buf in pairs(buffers) do release(buf) end end },}local namespace = vim.api.nvim_create_namespace('bugabinga_image')vim.api.nvim_set_decoration_provider(namespace, { on_end = function() if next(buffers) then redrawing = true; schedule() end end,})_G.BugabingaImage = { refresh = function() refresh(true) end }return BugabingaImageneovim/lua/bugabinga/image/LICENSE
Addednew file mode 100644+201 / −0 text lines
Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.neovim/lua/bugabinga/image/NOTICE
Addednew file mode 100644+6 / −0 text lines
Bugabinga image viewer includes modified code derived from folke/snacks.nvim.Upstream: https://github.com/folke/snacks.nvim/tree/e6fd58c82f2f3fcddd3fe81703d47d6d48fc7b9f/lua/snacks/imageUpstream license: Apache License 2.0, reproduced in LICENSE.Modified files: ../image.lua, kitty.lua, raster.lua, geometry.lua, terminal.lua.Changes: standalone Neovim raster buffers, FFmpeg conversion, native PNG dimensions, direct Kitty transport, per-window placements, corrected geometry and lifecycle, isolated WezTerm measurements.Snacks configuration, UI utilities, document integrations, placeholder rendering, and general conversion pipelines are not included.neovim/lua/bugabinga/image/README.md
Addednew file mode 100644+43 / −0 text lines
# Image buffersOpens local PNG, JPEG, WebP and GIF files in ordinary Neovim windows using the Kitty graphics protocol.PNG files are read directly.Other formats use FFmpeg from PATH to prepare a cached, first-frame RGBA PNG.No Snacks or ImageMagick dependency.## RequirementsNeovim 0.12 terminal UI and a Kitty-graphics-capable terminal.FFmpeg is required only for non-PNG images.Unix cell dimensions come from the terminal's native window-size report.WezTerm uses its CLI and WEZTERM_PANE to obtain actual pane pixel dimensions on any OS.Its incomplete proportional-sizing support is handled with explicit cell rectangles and minimized cell-grid distortion.Missing or zero measurements produce an error instead of guessed geometry.Neovide and image buffers inside floating windows are outside this viewer's scope.## BehaviorImages fit the text viewport without enlarging beyond their source dimensions, subject to a minimum terminal cell.Each window owns a separate placement; image data is shared while visible.Overlapping native floats temporarily hide the affected image.Hidden images release terminal storage; prepared raster files remain cached.Writes to image buffers are rejected.Window presentation settings live in after/ftplugin/image.lua.Incline's image exclusion lives in lua/bugabinga/winbar.lua.Neither policy is built into the renderer.The conversion cache is stdpath('cache')/bugabinga-image.Cache keys include source path, size, modification time and conversion version.Cache files persist without automatic size eviction.Conversions have a 30-second deadline, a 100-million-pixel limit and 100-MiB source/output checks.Large PNG uploads are streamed synchronously in bounded protocol chunks and can briefly occupy Neovim's event loop.Call :lua BugabingaImage.refresh() to remeasure and retransmit after an external terminal reset.Resize and focus/resume events refresh automatically.Owned terminal decoding errors are reported when the terminal forwards protocol replies.## ProvenanceModified derivative of folke/snacks.nvim's image implementation.Upstream commit, changes and Apache-2.0 license are recorded in NOTICE and LICENSE.neovim/lua/bugabinga/image/geometry.lua
Addednew file mode 100644+51 / −0 text lines
-- Modified from folke/snacks.nvim (Apache-2.0); see lua/bugabinga/image/NOTICE.local function rectangle(info, image, cells) vim.validate('info', info, 'table') vim.validate('image', image, 'table') vim.validate('cells', cells, 'table') local cols = info.width - info.textoff local rows = info.height if cols < 1 or rows < 1 then return end local width_scale = math.min(1, cols * cells.cell_width / image.width) local height_scale = math.min(1, rows * cells.cell_height / image.height) local axis if cells.explicit_size then local scale = math.min(width_scale, height_scale) local max_cols = math.min(cols, math.max(1, math.floor(image.width / cells.cell_width))) local max_rows = math.min(rows, math.max(1, math.floor(image.height / cells.cell_height))) local width = math.max(1, math.min(max_cols, math.floor(image.width * scale / cells.cell_width + 0.5))) local height = math.max(1, math.min(max_rows, math.floor(image.height * scale / cells.cell_height + 0.5))) local a = { cols = width, rows = math.min(max_rows, math.max(1, math.floor(width * cells.cell_width * image.height / image.width / cells.cell_height + 0.5))) } local b = { rows = height, cols = math.min(max_cols, math.max(1, math.floor(height * cells.cell_height * image.width / image.height / cells.cell_width + 0.5))) } local function aspect_error(candidate) return math.abs(candidate.cols * cells.cell_width * image.height / (candidate.rows * cells.cell_height * image.width) - 1) end local best = aspect_error(a) <= aspect_error(b) and a or b cols, rows, axis = best.cols, best.rows, 'both' elseif height_scale < width_scale then axis = 'rows' rows = math.max(1, math.floor(image.height * height_scale / cells.cell_height)) cols = math.min(cols, math.ceil(rows * cells.cell_height * image.width / image.height / cells.cell_width)) else axis = 'cols' cols = math.max(1, math.floor(image.width * width_scale / cells.cell_width)) rows = math.min(rows, math.ceil(cols * cells.cell_width * image.height / image.width / cells.cell_height)) end return { row = info.winrow + (info.winbar or 0), col = info.wincol + info.textoff, cols = cols, rows = rows, axis = axis }endlocal function overlaps(a, b) vim.validate('a', a, 'table') vim.validate('b', b, 'table') return a.row < b.row + b.rows and b.row < a.row + a.rows and a.col < b.col + b.cols and b.col < a.col + a.colsendreturn { rectangle = rectangle, overlaps = overlaps }neovim/lua/bugabinga/image/kitty.lua
Addednew file mode 100644+107 / −0 text lines
-- Modified from folke/snacks.nvim (Apache-2.0); see lua/bugabinga/image/NOTICE.local MAX_ID = 0xFFFFFFFFlocal CHUNK_BYTES = 3072local next_image_id = tonumber(vim.fn.sha256(tostring(vim.uv.hrtime()) .. ':' .. vim.fn.getpid()):sub(1, 7), 16)local function valid_id(value, name) vim.validate(name, value, 'number') if value < 1 or value > MAX_ID or value % 1 ~= 0 then error(name .. ' must be an integer between 1 and 4294967295') endendlocal function send(command) local ok, err = pcall(vim.api.nvim_ui_send, command) if not ok then return nil, err end return trueendlocal function transfer_chunk(image_id, payload, first, more) local fields if first then fields = ('a=t,f=100,t=d,i=%d,m=%d,q=1;'):format(image_id, more and 1 or 0) else fields = ('m=%d,q=1;'):format(more and 1 or 0) end return send('\27_G' .. fields .. payload .. '\27\\')endlocal function new_id() if next_image_id == MAX_ID then error('Kitty image ID space exhausted') end next_image_id = next_image_id + 1 return next_image_idendlocal function upload(image_id, path) valid_id(image_id, 'image_id') vim.validate('path', path, 'string') local stat = vim.uv.fs_stat(path) if not stat or stat.type ~= 'file' then return nil, 'path must be a regular file' end local file, err = io.open(path, 'rb') if not file then return nil, err end local pending = file:read(CHUNK_BYTES) if not pending then file:close() return nil, 'image file is empty' end local first = true while true do local current = pending pending = file:read(CHUNK_BYTES) local more = pending ~= nil local ok, send_err = transfer_chunk(image_id, vim.base64.encode(current), first, more) if not ok then file:close() return nil, send_err end first = false if not more then break end end local closed, close_err = file:close() if closed == nil then return nil, close_err end return trueendlocal function place(image_id, placement_id, rect) valid_id(image_id, 'image_id') valid_id(placement_id, 'placement_id') vim.validate('rect', rect, 'table') for _, field in ipairs({ 'row', 'col', 'cols', 'rows' }) do vim.validate(field, rect[field], 'number') if rect[field] < 1 or rect[field] % 1 ~= 0 then error(field .. ' must be a positive integer') end end local size = rect.axis == 'rows' and ('r=' .. rect.rows) or ('c=' .. rect.cols) if rect.axis == 'both' then size = ('c=%d,r=%d'):format(rect.cols, rect.rows) end local command = ('\27[s\27[%d;%dH\27_Ga=p,i=%d,p=%d,%s,C=1,q=1\27\\\27[u'):format( rect.row, rect.col, image_id, placement_id, size ) return send(command)endlocal function delete(image_id, placement_id) valid_id(image_id, 'image_id') local command if placement_id ~= nil then valid_id(placement_id, 'placement_id') command = ('\27_Ga=d,d=i,i=%d,p=%d,q=1\27\\'):format(image_id, placement_id) else command = ('\27_Ga=d,d=I,i=%d,q=1\27\\'):format(image_id) end return send(command)endreturn { new_id = new_id, upload = upload, place = place, delete = delete }neovim/lua/bugabinga/image/raster.lua
Addednew file mode 100644+175 / −0 text lines
-- Modified from folke/snacks.nvim (Apache-2.0); see lua/bugabinga/image/NOTICE.local uv = vim.uvlocal MAX_SOURCE_SIZE = 100 * 1024 * 1024local MAX_OUTPUT_SIZE = 100 * 1024 * 1024local MAX_PIXELS = 100000000local function stat(path) local value = uv.fs_stat(path) if not value or value.type ~= 'file' then return nil, 'source is not a regular file' end if value.size > MAX_SOURCE_SIZE then return nil, 'source exceeds size limit' end return valueendlocal function fingerprint(path, value) return table.concat({ path, value.size, value.mtime.sec, value.mtime.nsec or 0 }, '\0')endlocal function read_png(path) local file, err = io.open(path, 'rb') if not file then return nil, err end local header = file:read(24) file:close() if not header or #header < 24 or header:sub(1, 8) ~= '\137PNG\r\n\26\n' then return nil, 'invalid PNG signature or IHDR' end if header:sub(9, 12) ~= '\0\0\0\13' or header:sub(13, 16) ~= 'IHDR' then return nil, 'invalid PNG IHDR' end local function uint32(offset) local a, b, c, d = header:byte(offset, offset + 3) return ((a * 256 + b) * 256 + c) * 256 + d end local width, height = uint32(17), uint32(21) if width == 0 or height == 0 or width * height > MAX_PIXELS then return nil, 'invalid PNG dimensions' end return width, heightendlocal function dimensions(path) vim.validate('path', path, 'string') local value, err = stat(path) if not value then return nil, err end return read_png(path)endlocal function cache_paths(key) local directory = vim.fs.joinpath(vim.fn.stdpath('cache'), 'bugabinga-image') return directory, vim.fs.joinpath(directory, key .. '.png')endlocal function prepare(path, callback) vim.validate('path', path, 'string') vim.validate('callback', callback, 'function') local canceled = false local job local partial local function finish(err, result) if not canceled then vim.schedule(function() if not canceled then callback(err, result) end end) end end local function cancel() canceled = true if job then job:kill(15) end if partial then uv.fs_unlink(partial) end end local source, source_err = stat(path) if not source then finish(source_err) return cancel end local identity = 'ffmpeg-rgba-v2\0' .. fingerprint(path, source) local key = vim.fn.sha256(identity) local directory, cached = cache_paths(key) local function result_for(file) local width, height = read_png(file) local output = uv.fs_stat(file) if not width or not output or output.size > MAX_OUTPUT_SIZE then return nil end return { path = file, width = width, height = height, key = key } end local cached_result = result_for(cached) if cached_result then finish(nil, cached_result) return cancel end local extension = path:lower():match('%.([^.]+)$') if extension == 'png' then local width, height = read_png(path) if not width then finish(height) return cancel end finish(nil, { path = path, width = width, height = height, key = key }) return cancel end if extension ~= 'jpg' and extension ~= 'jpeg' and extension ~= 'webp' and extension ~= 'gif' then finish('unsupported image format') return cancel end local mkdir_status = vim.fn.mkdir(directory, 'p') if mkdir_status ~= 1 and not uv.fs_stat(directory) then finish('unable to create image cache directory') return cancel end partial = vim.fs.joinpath( directory, key .. '.' .. tostring(uv.os_getpid()) .. '.' .. string.format('%.0f', uv.hrtime()) .. '.partial.png' ) local args = { 'ffmpeg', '-nostdin', '-v', 'error', '-threads', '1', '-max_pixels', tostring(MAX_PIXELS), '-i', path, '-frames:v', '1' } vim.list_extend(args, { '-threads', '1', '-f', 'image2', '-vcodec', 'png', '-pix_fmt', 'rgba', '-fs', tostring(MAX_OUTPUT_SIZE), '-y', partial }) local ok, system_job = pcall(vim.system, args, { text = true, timeout = 30000 }, function(response) if canceled then if partial then uv.fs_unlink(partial) end return end job = nil if response.code ~= 0 then uv.fs_unlink(partial) finish(response.stderr and response.stderr ~= '' and response.stderr or 'ffmpeg conversion failed') return end local current = stat(path) if not current or 'ffmpeg-rgba-v2\0' .. fingerprint(path, current) ~= identity then uv.fs_unlink(partial) finish('source changed during conversion') return end local output = uv.fs_stat(partial) local width, height = read_png(partial) if not output or output.size > MAX_OUTPUT_SIZE or not width then uv.fs_unlink(partial) finish('ffmpeg produced invalid PNG') return end local renamed, rename_err = uv.fs_rename(partial, cached) if not renamed then uv.fs_unlink(partial) finish(rename_err or 'unable to commit image cache entry') return end partial = nil finish(nil, { path = cached, width = width, height = height, key = key }) end) if not ok then uv.fs_unlink(partial) finish(system_job) else job = system_job end return cancelendreturn { dimensions = dimensions, prepare = prepare }neovim/lua/bugabinga/image/terminal.lua
Addednew file mode 100644+110 / −0 text lines
-- Modified from folke/snacks.nvim (Apache-2.0); see lua/bugabinga/image/NOTICE.local metricslocal pendinglocal dirty = falselocal callbacks = {}local function available() for _, ui in ipairs(vim.api.nvim_list_uis()) do local channel = vim.api.nvim_get_chan_info(ui.chan) if channel.client and channel.client.name == 'nvim-tui' then return true end end return falseendlocal function valid(width, height) return type(width) == 'number' and type(height) == 'number' and width > 0 and height > 0 and width < math.huge and height < math.hugeendlocal function ioctl_metrics() local request = ({ Linux = 0x5413, OSX = 0x40087468, BSD = 0x40087468 })[jit.os] if not request then return end local ok, result = pcall(function() local ffi = require 'ffi' if not pcall(ffi.typeof, 'bugabinga_image_winsize') then ffi.cdef [[ typedef struct { unsigned short row, col, xpixel, ypixel; } bugabinga_image_winsize; int ioctl(int, unsigned long, ...); ]] end local size = ffi.new('bugabinga_image_winsize') if ffi.C.ioctl(1, request, size) ~= 0 or size.row == 0 or size.col == 0 then return end if not valid(tonumber(size.xpixel), tonumber(size.ypixel)) then return end return { cell_width = size.xpixel / size.col, cell_height = size.ypixel / size.row } end) if ok then return result endendlocal function decode(panes) vim.validate('panes', panes, 'table') for _, pane in ipairs(panes) do if type(pane) == 'table' and tostring(pane.pane_id) == vim.env.WEZTERM_PANE then local size = type(pane.size) == 'table' and pane.size or {} if valid(size.cols, size.rows) and valid(size.pixel_width, size.pixel_height) then return { cell_width = size.pixel_width / size.cols, cell_height = size.pixel_height / size.rows, explicit_size = true } end return nil, 'WezTerm did not report valid pane pixel dimensions' end end return nil, 'Current pane was not found in WezTerm'endlocal function get() if not vim.env.WEZTERM_PANE then return ioctl_metrics() end return metricsendlocal function refresh(callback) vim.validate('callback', callback, 'function') if not available() then vim.schedule(function() callback(nil, 'Image viewing requires a Neovim terminal UI') end) return end if not vim.env.WEZTERM_PANE then local size = ioctl_metrics() vim.schedule(function() callback(size, not size and 'Terminal did not provide valid cell pixel dimensions' or nil) end) return end callbacks[#callbacks + 1] = callback if pending then dirty = true; return end local function finish(result, err) vim.schedule(function() pending = nil local waiting = callbacks callbacks = {} if dirty then dirty = false refresh(function(size, failure) for _, cb in ipairs(waiting) do cb(size, failure) end end) return end metrics = result for _, cb in ipairs(waiting) do cb(result, err) end end) end local ok, job = pcall(vim.system, { 'wezterm', 'cli', 'list', '--format', 'json' }, { text = true, timeout = 2000 }, vim.schedule_wrap(function(result) if result.code ~= 0 then finish(nil, 'Cannot measure WezTerm pane: ' .. vim.trim(result.stderr or 'command failed')) return end local parsed, panes = pcall(vim.json.decode, result.stdout) if not parsed or type(panes) ~= 'table' then finish(nil, 'Invalid WezTerm pane response') return end finish(decode(panes)) end)) if ok then pending = job else finish(nil, tostring(job)) endendreturn { available = available, get = get, refresh = refresh, decode = decode }neovim/lua/bugabinga/key_preview.lua
Modified+2 / −1 text lines
{ mode = 'n', keys = '<Leader>o', desc = '+OpenCode' },neovim/lua/bugabinga/lsp/attach.lua
Modified+1 / −7 text lines
neovim/lua/bugabinga/lsp/commands.lua
Modified+12 / −28 text lines
local names = {} local seen = {} for _, client in ipairs( clients ) do if not seen[client.name] then seen[client.name] = true names[#names + 1] = client.name end end local names = client_names( clients ) local clients = vim.lsp.get_clients() local seen = {} local names = {} for _, client in ipairs( clients ) do if not seen[client.name] then seen[client.name] = true names[#names + 1] = client.name end end return names return client_names( vim.lsp.get_clients() ) local names = {} local seen = {} for _, client in ipairs( clients ) do if not seen[client.name] then seen[client.name] = true names[#names + 1] = client.name end end local names = client_names( clients )neovim/lua/bugabinga/lsp/info.lua
Deleteddeleted file mode 100644+0 / −106 text lines
local icon = require 'std.icon'local table = require 'std.table'local cap_fields = { hoverProvider = 'Hover', definitionProvider = 'Go to Definition', referencesProvider = 'References', completionProvider = 'Completion', renameProvider = 'Rename', codeActionProvider = 'Code Actions', documentFormattingProvider = 'Formatting', documentSymbolProvider = 'Document Symbols', workspaceSymbolProvider = 'Workspace Symbols', inlayHintProvider = 'Inlay Hints', semanticTokensProvider = 'Semantic Tokens', signatureHelpProvider = 'Signature Help', declarationProvider = 'Go to Declaration', typeDefinitionProvider = 'Go to Type Definition', implementationProvider = 'Go to Implementation', documentHighlightProvider = 'Document Highlight', codeLensProvider = 'Code Lens', documentLinkProvider = 'Document Links', foldingRangeProvider = 'Folding Range', selectionRangeProvider = 'Selection Range', callHierarchyProvider = 'Call Hierarchy', documentRangeFormattingProvider = 'Range Formatting', documentOnTypeFormattingProvider = 'On-Type Formatting', diagnosticProvider = 'Pull Diagnostics', executeCommandProvider = 'Execute Command',}local show = function( clients ) if #clients == 0 then vim.notify( 'No active LSP clients', vim.log.levels.INFO ) return end local buf = vim.api.nvim_create_buf( false, true ) local width = math.floor( vim.o.columns * 0.8 ) local height = math.floor( vim.o.lines * 0.8 ) local row = math.floor( (vim.o.lines - height) / 2 ) local col = math.floor( (vim.o.columns - width) / 2 ) local win = vim.api.nvim_open_win( buf, true, { relative = 'editor', width = width, height = height, row = row, col = col, style = 'minimal', border = 'rounded', title = icon.lsp .. ' LSP Info', title_pos = 'center', } ) local lines = {} for i, client in ipairs( clients ) do if i > 1 then table.insert( lines, '' ) end table.insert( lines, string.format( '# %s %s', icon.lsp, client.name ) ) local root = client.config.root_dir or 'No root' table.insert( lines, string.format( '**Root:** %s', root ) ) if client.config.filetypes then table.insert( lines, string.format( '**Filetypes:** %s', table.concat( client.config.filetypes, ', ' ) ) ) end table.insert( lines, string.format( '**ID:** %d', client.id ) ) local cmd = client.config.cmd if type( cmd ) == 'table' and cmd[1] then table.insert( lines, string.format( '**Binary:** %s', cmd[1] ) ) end if client.workspace_folders and #client.workspace_folders > 0 then table.insert( lines, '**Workspace Folders:**' ) for _, wf in ipairs( client.workspace_folders ) do table.insert( lines, string.format( ' - %s', wf.name ) ) end end local caps = client.server_capabilities local cap_list = {} for field, name in pairs( cap_fields ) do if caps[field] then cap_list[#cap_list + 1] = name end end table.insert( lines, string.format( '**Capabilities (%d):**', #cap_list ) ) table.insert( lines, ' ' .. table.concat( cap_list, ', ' ) ) if client.server_info and client.server_info.version then table.insert( lines, string.format( '**Version:** %s', client.server_info.version ) ) end end vim.api.nvim_buf_set_lines( buf, 0, -1, false, lines ) vim.api.nvim_buf_set_lines( buf, 0, -1, false, lines ) vim.api.nvim_set_option_value( 'filetype', 'markdown', { buf = buf } ) vim.api.nvim_set_option_value( 'spell', false, { win = win } ) vim.api.nvim_set_option_value( 'wrap', true, { win = win } ) vim.api.nvim_set_option_value( 'readonly', true, { buf = buf } ) vim.api.nvim_set_option_value( 'modifiable', false, { buf = buf } ) vim.keymap.set( 'n', 'q', '<cmd>close<CR>', { buffer = buf, noremap = true, silent = true } ) vim.keymap.set( 'n', '<Esc>', '<cmd>close<CR>', { buffer = buf, noremap = true, silent = true } ) vim.api.nvim_set_current_win( win )endreturn { show = show }No final newlineneovim/lua/bugabinga/lsp/init.lua
Modified+4 / −10 text lines
neovim/lua/bugabinga/mise.lua
Addednew file mode 100644+36 / −0 text lines
local function is_mise(path) vim.validate('path', path, 'string') path = vim.fs.normalize(path) local name = vim.fs.basename(path) return name:match('^%.?mise.*%.toml$') ~= nil or path:match('/%.?mise/config%.toml$') ~= nil or path:match('/%.?mise/config%.[^/]+%.toml$') ~= nil or path:match('/%.?mise/conf%.d/[^/]+%.toml$') ~= nilendvim.treesitter.query.add_predicate('is-mise?', function(_, _, source) return type(source) == 'number' and is_mise(vim.api.nvim_buf_get_name(source))end, { force = true })vim.treesitter.query.add_directive('mise-run!', function(match, _, source, directive, metadata) local id = directive[2] local node = match[id][1] local text = vim.treesitter.get_node_text(node, source) local delimiter = (text:sub(1, 3) == '"""' or text:sub(1, 3) == "'''") and 3 or 1 local content = text:sub(delimiter + 1, -delimiter - 1) local shebang = content:match('^\r?\n?#!([^\r\n]+)') local language = 'bash' if shebang then local interpreter, args = shebang:match('^%s*(%S+)%s*(.*)') interpreter = interpreter and interpreter:match('([^/\\]+)$') if interpreter == 'env' then if args:match('^%-S%s+') then args = args:gsub('^%-S%s+', '') end interpreter = args:match('^(%S+)') end language = interpreter and (vim.treesitter.language.get_lang(interpreter) or interpreter) or '' end metadata['injection.language'] = language metadata[id] = { offset = { 0, delimiter, 0, -delimiter } }end, { force = true })return { is_mise = is_mise }neovim/lua/bugabinga/nugu/init.lua
Modified+14 / −7 text lines
_['@error'] = _.DiagnosticErrorneovim/lua/bugabinga/nugu/palette.lua
Modified+17 / −0 text lines
neovim/lua/bugabinga/options/behaviour.lua
Modified+9 / −0 text lines
-- BufReadPost fires on every read of this buffer, not just the first one. -- Reloading a file that changed on disk ( `:checktime`, 'autoread' ) reads -- it again with READ_NEW and therefore triggers this too. -- Restoring the last known position is a once per buffer action, so latch -- it. Buffer local variables survive a reload, the buffer object stays the -- same and only its lines are replaced. if vim.b[ev.buf].cursor_restored then return end vim.b[ev.buf].cursor_restored = trueneovim/lua/bugabinga/options/core.lua
Modified+63 / −68 text lines
-- disable bundled vimscript runtime plugins.-- none of these are used, each one sources a .vim file at startup.-- the guard variable differs from the plugin name in several cases-- ( netrw needs loaded_netrwPlugin, not loaded_netrw ), so set the-- full set explicitly.for _, plugin in ipairs { 'gzip', 'matchit', 'matchparen', 'netrw', 'netrwPlugin', 'netrwSettings', 'netrwFileHandlers', 'tar', 'tarPlugin', 'zip', 'zipPlugin', 'tutor', 'tutor_mode_plugin', 'remote_plugins', '2html_plugin', 'logipat', 'rrhelper', 'vimball', 'vimballPlugin', 'spellfile_plugin',} do vim.g['loaded_' .. plugin] = 1end-- disable the builtin vim regex syntax engine. treesitter only.-- this stops per-filetype syntax/*.vim files from sourcing.-- consequence: any filetype without a treesitter parser gets no-- highlighting at all. accepted tradeoff.vim.cmd.syntax 'off'-- drop the system vim directory from the runtime and pack paths.-- it leaks vimscript into neovim: fzf.vim, skim.vim and package ftdetect-- files ( PKGBUILD, SRCINFO, ghostty ) all live here.vim.opt.runtimepath:remove '/usr/share/vim/vimfiles'vim.opt.runtimepath:remove '/usr/share/vim/vimfiles/after'vim.opt.packpath:remove '/usr/share/vim/vimfiles'vim.opt.packpath:remove '/usr/share/vim/vimfiles/after'-- How many milliseconds must pass before neovim decides I was "idle".-- Drives the swap file flush and the CursorHold event. Below ~100ms nothing-- feels faster to a human, but every CursorHold consumer ( lsp document-- highlight, code action signs ) fires another round of requests.vim.opt.updatetime = 150vim.opt.incsearch = truevim.opt.wildmode = 'full'vim.opt.winborder = 'shadow'-- no transparent popups and floating windowsvim.opt.pumblend = 0vim.opt.winblend = 0-- use this in various places for consistent border stylevim.g.border_style = { { '🬷', 'FloatBorderCorner' }, -- top left { '▔', 'FloatBorder' }, -- top { '🬲', 'FloatBorderCorner' }, -- top right { '🮈', 'FloatBorder' }, -- right { '🬕', 'FloatBorderCorner' }, -- bottom right { '▁', 'FloatBorder' }, -- bottom { '🬨', 'FloatBorderCorner' }, -- bottom left { '▍', 'FloatBorder' }, -- left}-- consistent, simple float borders everywhere ( lsp hover, pickers, my own-- popups ). single source of truth: the global 'winborder'. every float that-- does not pass an explicit border inherits this one.-- plain box drawing ( U+2500 ) on purpose: the sextants from "Symbols for-- Legacy Computing" ( U+1FBxx ) render as tofu in almost every font/frontend-- except wezterm, which draws them itself.vim.o.winborder = '┌,─,┐,│,┘,─,└,│'neovim/lua/bugabinga/options/filetypes.lua
Modified+12 / −1 text lines
neovim/lua/bugabinga/options/ftplugin.lua
Addednew file mode 100644+63 / −0 text lines
-- replace the vimscript filetype machinery with pure lua.---- what neovim does by default:-- filetype on -> detection ( lua, vim.filetype )-- filetype plugin on -> sources $VIMRUNTIME/ftplugin/<ft>.vim ( vimscript )-- filetype indent on -> sources $VIMRUNTIME/indent/<ft>.vim ( vimscript )---- we keep detection ( lua ) and kill the two vimscript loaders.-- this also stops our own after/ftplugin/*.lua from loading, because they-- ride the same builtin autocmd. so we reimplement that loader below.-- keep detection, drop the vimscript plugin + indent sourcing.vim.cmd 'filetype plugin indent off'-- indentation: delegate to treesitter ( pure lua ).-- nvim-treesitter main ships an experimental indent module + indents.scm queries.-- get_indent returns -1 when no parser is available, which makes neovim fall-- back to 'autoindent'. wrapped in pcall so a not-yet-loaded treesitter or a-- query error never spams indentexpr errors.function _G.BugabingaIndent() local ok, indent = pcall( function() return require( 'nvim-treesitter.indent' ).get_indent( vim.v.lnum ) end ) return ok and indent or -1endvim.o.indentexpr = 'v:lua.BugabingaIndent()'-- our own filetype loader, replacing the builtin vimscript one.-- sets commentstring from a lua table ( native gc reads vim.bo.commentstring )-- and sources our after/ftplugin/<ft>.lua files. mirrors neovim by splitting-- compound filetypes into their dotted components.local commentstring = require 'std.commentstring'local ftoptions = require 'std.ftoptions'local config_dir = vim.fn.stdpath 'config'local group = vim.api.nvim_create_augroup( 'bugabinga_ftplugin', { clear = true } )vim.api.nvim_create_autocmd( 'FileType', { group = group, desc = 'pure-lua ftplugin: commentstring + user after/ftplugin', callback = function ( args ) for ft in vim.gsplit( args.match, '.', { plain = true } ) do if ft ~= '' then local cs = commentstring[ft] if cs then vim.bo[args.buf].commentstring = cs end -- pure-data per-ft options ( comments, define, include, path, … ) -- that the killed vimscript ftplugins used to set. local opts = ftoptions[ft] if opts then for name, value in pairs( opts ) do vim.bo[args.buf][name] = value end end local file = config_dir .. '/after/ftplugin/' .. ft .. '.lua' if vim.uv.fs_stat( file ) then local chunk = loadfile( file ) if chunk then chunk() end end end end end,} )neovim/lua/bugabinga/options/grep.lua
Modified+3 / −1 text lines
neovim/lua/bugabinga/options/init.lua
Modified+7 / −2 text lines
neovim/lua/bugabinga/options/neovide.lua
Modified+31 / −3 text lines
-- Neovide has no bundled fallback font, unlike wezterm, which also draws -- box and block glyphs itself instead of asking the font for them. -- So the chain has to be spelled out, and every link earns its place: -- JetBrains Mono the text, same as wezterm uses -- Symbols Nerd Font Mono every `nf-*` icon in `std.icon` -- Cascadia Code braille ( the spinner ) and block elements -- Segoe UI Symbol ↴ ⦿ 🔭 and friends, win32 only -- DejaVu Sans Mono the same job on linux -- Missing families are skipped, so listing both platforms is harmless. local font_size = vim.fn.hostname() == 'x230' and 11 or 13 vim.opt.guifont = ( '%s:h%d' ):format( table.concat( { 'JetBrains Mono', 'Symbols Nerd Font Mono', 'Cascadia Code', 'Segoe UI Symbol', 'DejaVu Sans Mono', }, ',' ), font_size ) vim.opt.pumblend = 15 vim.opt.winblend = 15 vim.g.neovide_opacity = 0.84 vim.g.neovide_floating_blur_amount_x = 4.0 vim.g.neovide_floating_blur_amount_y = 4.0 vim.g.neovide_floating_corner_radius = 0.42 vim.g.neovide_position_animation_length = 0.12 vim.g.neovide_scroll_animation_length = 0.2 vim.g.neovide_cursor_animation_length = 0.1 vim.g.neovide_cursor_trail_size = 0.8 vim.g.neovide_cursor_vfx_mode = 'railgun' vim.g.experimental_layer_grouping = trueneovim/lua/bugabinga/options/shell.lua
Modified+3 / −9 text lines
if vim.fn.executable 'nu' then '| complete | get stderr stdout | str join (char nl) | ansi strip | tee { save --force --raw "%s" }' -- WARN: disable the usage of temp files for shell commands -- because Nu doesn't support `input redirection` which Neovim uses to send buffer content to a command: -- `{shell_command} < {temp_file_with_selected_buffer_content}` -- When set to `false` the stdin pipe will be used instead. -- NOTE: some info about `shelltemp`: https://github.com/neovim/neovim/issues/1008 vim.opt.shelltemp = falseneovim/lua/bugabinga/options/spelling.lua
Deleteddeleted file mode 100644+0 / −28 text lines
local table = require 'std.table'local joinpath = vim.fs.joinpath-- disable spell checking initiallyvim.opt.spell = falsevim.opt.spelloptions:append 'camel'vim.opt.spellcapcheck = ''-- English, German, Polish and tech wordsvim.opt.spelllang:append 'en'vim.opt.spelllang:append 'de'vim.opt.spelllang:append 'pl'vim.opt.spelllang:append 'nerd'local config_dir = vim.fn.stdpath 'config'---@diagnostic disable-next-line: param-type-mismatchlocal spell_dir = joinpath(config_dir, 'spell')vim.opt.spellfile = table.concat( { joinpath(spell_dir, 'nerd.utf-8.add'), joinpath(spell_dir, 'en.utf-8.add'), joinpath(spell_dir, 'de.utf-8.add'), joinpath(spell_dir, 'pl.utf-8.add'), }, ',')-- create new spl file with:-- mkspell ~/.config/nvim/spell/[lang] ~/Downloads/[lang]-- update nerd words with-- vim.cmd [[ mkspell! ~/.config/nvim/spell/nerd ~/.config//nvim/spell/nerd.words ]]-- vim.cmd [[ mkspell! ~/.config/nvim/spell/nerd.utf-8.add ]]neovim/lua/bugabinga/options/win32.lua
Modified+1 / −12 text lines
neovim/lua/bugabinga/otter.lua
Addednew file mode 100644+91 / −0 text lines
local auto = require 'std.auto'local mise = require 'bugabinga.mise'local otter = require('std.puk') 'otter'local keeper = require 'otter.keeper'local pending = {}require('bugabinga.health').add_dependency { name_of_executable = 'bash-language-server' }otter.setup { extensions = { nu = 'nu', toml = 'toml', kdl = 'kdl' } }local function eligible(buffer) if not vim.api.nvim_buf_is_loaded(buffer) or vim.bo[buffer].buftype ~= '' then return false end local name = vim.api.nvim_buf_get_name(buffer) if name:match('%.otter%.[^/\\]+$') then return false end local ft = vim.bo[buffer].filetype return ft == 'markdown' or (ft == 'toml' and mise.is_mise(name))endlocal function languages(buffer, parser) local found, unsafe = {}, {} parser:for_each_tree(function(concrete, tree) local lang = tree:lang() if lang == parser:lang() or not OtterConfig.extensions[lang] then return end found[lang] = true if vim.bo[buffer].filetype ~= 'toml' then return end for _, range in ipairs(concrete:included_ranges()) do local sr, sc, er, ec = unpack(range) if sc > 0 then local line = vim.api.nvim_buf_get_lines(buffer, sr, sr + 1, false)[1] or '' local first = line:sub(sc + 1, sr == er and ec or #line) if first:find('%S') then unsafe[lang] = true end end end end) for lang in pairs(unsafe) do found[lang] = nil end return foundendlocal function reconcile(buffer) if pending[buffer] or (not eligible(buffer) and not keeper.rafts[buffer]) then return end pending[buffer] = true vim.schedule(function() pending[buffer] = nil if not eligible(buffer) then if keeper.rafts[buffer] and vim.api.nvim_buf_is_valid(buffer) then vim.api.nvim_buf_call(buffer, otter.deactivate) end return end local ok, parser = pcall(vim.treesitter.get_parser, buffer) if not ok or not parser then return end parser:parse(true) local wanted = languages(buffer, parser) local raft = keeper.rafts[buffer] local changed = raft and raft.parser ~= parser or false local prefix = vim.api.nvim_buf_get_name(buffer) .. '.otter.' for lang in pairs(wanted) do local generated = raft and raft.buffers[lang] if not generated or not vim.api.nvim_buf_is_valid(generated) or not vim.startswith(vim.api.nvim_buf_get_name(generated), prefix) then changed = true end end for lang in pairs(raft and raft.buffers or {}) do if not wanted[lang] then changed = true end end if not changed then return end if raft and next(raft.buffers) then pending[buffer] = true vim.api.nvim_buf_call(buffer, otter.deactivate) vim.schedule(function() pending[buffer] = nil reconcile(buffer) end) elseif next(wanted) then vim.api.nvim_buf_call(buffer, function() otter.activate(vim.tbl_keys(wanted)) end) end end)endauto 'otter_embedded_languages' { events = { 'FileType', 'BufEnter', 'BufFilePost', 'TextChanged', 'TextChangedI', 'TextChangedP', 'InsertLeave' }, command = function(args) reconcile(args.buf) end,}for _, buffer in ipairs(vim.api.nvim_list_bufs()) do reconcile(buffer)endneovim/lua/bugabinga/pivi/auth.lua
Addednew file mode 100644+244 / −0 text lines
local view = require 'bugabinga.pivi.view'local panellocal function info(message) vim.notify(message, vim.log.levels.INFO, { title = 'pivi' })endlocal function fail(message) vim.notify(tostring(message), vim.log.levels.ERROR, { title = 'pivi' })endlocal function draw() if not panel or not vim.api.nvim_win_is_valid(panel.window) then return end local hints = {} if panel.url then hints[#hints + 1] = 'o open browser' end if panel.url then hints[#hints + 1] = 'y copy ' .. (panel.code and 'code' or 'link') end if panel.manual then hints[#hints + 1] = 'p paste code' end hints[#hints + 1] = 'q cancel' local lines = { '# Sign in · ' .. panel.title, '' } vim.list_extend(lines, panel.body) vim.list_extend(lines, { panel.progress, '', table.concat(hints, ' ') }) local buffer = vim.api.nvim_win_get_buf(panel.window) vim.bo[buffer].modifiable = true vim.api.nvim_buf_set_lines(buffer, 0, -1, false, lines) vim.bo[buffer].modifiable = false local height = vim.api.nvim_win_text_height(panel.window, {}).all vim.api.nvim_win_set_height(panel.window, math.max(1, math.min(height, vim.o.lines - 6)))endlocal function browse() local _, failure = vim.ui.open(panel.url) if failure then table.insert(panel.body, 'No browser could be opened. Open the link yourself.') endendlocal function copy() vim.fn.setreg('"', panel.code or panel.url) pcall(vim.fn.setreg, '+', panel.code or panel.url) info(panel.code and 'Code copied.' or 'Link copied.')endlocal function show(event) local body = panel.body if event.type == 'progress' then panel.progress = event.message elseif event.type == 'info' then body[#body + 1] = event.message for _, link in ipairs(event.links or {}) do body[#body + 1] = (link.label and link.label .. ': ' or '') .. link.url panel.url = panel.url or link.url end body[#body + 1] = '' elseif event.type == 'auth_url' then panel.url, panel.progress = event.url, 'Waiting for the browser…' vim.list_extend(body, { event.instructions or 'Finish signing in in your browser.', '', event.url, '' }) browse() elseif event.type == 'device_code' then panel.url, panel.code, panel.progress = event.verificationUri, event.userCode, 'Waiting for the browser…' vim.list_extend( body, { 'Enter this code in your browser:', '', ' ' .. event.userCode, '', event.verificationUri, '' } ) copy() browse() end draw()endlocal function ask(state, id, prompt) local function answer(value) if value == nil or value == '' then state.transport.reply(id, false, 'Sign-in cancelled.') else state.transport.reply(id, true, value) end end local message = prompt.message .. (prompt.placeholder and ' (' .. prompt.placeholder .. ')' or '') .. ': ' if prompt.type == 'manual_code' and panel then panel.manual = { id = id, message = message, answer = answer } draw() elseif prompt.type == 'select' then local format = function(option) return option.description and option.label .. ' · ' .. option.description or option.label end vim.ui.select( prompt.options, { prompt = prompt.message, format_item = format }, function(option) answer(option and option.id) end ) elseif prompt.type == 'secret' then vim.schedule(function() answer(vim.fn.inputsecret(message)) end) else vim.ui.input({ prompt = message }, answer) endendlocal function paste() local manual = panel.manual if not manual then return end vim.ui.input({ prompt = manual.message }, function(value) if not value or value == '' or not panel or panel.manual ~= manual then return end panel.manual = nil manual.answer(value) draw() end)endlocal function receive(state, record) if record.type == 'prompt' then ask(state, record.id, record.prompt) elseif record.type == 'auth' and panel then show(record.event) elseif record.type == 'cancel' and panel and panel.manual and panel.manual.id == record.id then panel.manual = nil draw() endendlocal function start(state, provider, method, done) local window = view.float('sign-in', { '' }, 'pivi sign in') local cancelled = false local function cancel() if cancelled or not panel then return end cancelled = true state.transport.request('cancel', nil, function() end) end local progress = method.type == 'api_key' and 'Waiting for the API key…' or 'Starting…' panel = { window = window, title = provider.name, body = {}, progress = progress } local function key(lhs, action, needs_link) vim.keymap.set('n', lhs, function() if not panel or (needs_link and not panel.url) then return end action() draw() end, { buffer = 0, nowait = true }) end key('o', browse, true) key('y', copy, true) key('p', paste) key('q', cancel) key('<Esc>', cancel) vim.api.nvim_create_autocmd('WinClosed', { pattern = tostring(window), once = true, callback = cancel }) draw() state.transport.request('login', { provider = provider.id, method = method.type }, function(ok, failure) panel = nil if vim.api.nvim_win_is_valid(window) then vim.api.nvim_win_close(window, true) end if ok then info('Signed in to ' .. provider.name .. '.') done(provider) elseif cancelled then info('Sign-in cancelled.') else fail(failure) end end)endlocal function providers(state, done) state.transport.request('providers', nil, function(ok, list) if ok then done(list) else fail(list) end end)endlocal function rank(provider) return provider.stored and 1 or provider.source and 2 or 3endlocal function describe(provider) local status = provider.stored and 'signed in · ' .. (provider.stored == 'oauth' and 'account' or 'API key') or provider.source and 'ready · ' .. provider.source or 'not set up' return ('%s %-30s %s'):format(({ '●', '◐', '○' })[rank(provider)], provider.name, status)endlocal function login(state, id, done) if panel then fail('A sign-in is already in progress.') return end providers(state, function(list) local function with(provider) if not provider then return end local methods = provider.methods if #methods == 1 then start(state, provider, methods[1], done) return end local format = function(method) return (method.type == 'oauth' and 'Account · ' or 'API key · ') .. method.label end vim.ui.select( methods, { prompt = 'Sign in to ' .. provider.name .. ' with', format_item = format }, function(method) if method then start(state, provider, method, done) end end ) end list = vim.tbl_filter(function(provider) return #provider.methods > 0 end, list) if id ~= '' then local provider = vim.iter(list):find(function(item) return item.id == id end) if not provider then fail('Unknown provider: ' .. id) end with(provider) return end table.sort(list, function(a, b) if rank(a) ~= rank(b) then return rank(a) < rank(b) end return a.name < b.name end) vim.ui.select(list, { prompt = 'Sign in to', format_item = describe }, with) end)endlocal function logout(state, id) providers(state, function(list) local function with(provider) if not provider then return end state.transport.request('logout', { provider = provider.id }, function(ok, failure) if ok then info('Signed out of ' .. provider.name .. '.') else fail(failure) end end) end list = vim.tbl_filter(function(provider) return provider.stored ~= nil end, list) if id ~= '' then local provider = vim.iter(list):find(function(item) return item.id == id end) if not provider then fail('Not signed in to: ' .. id) end with(provider) elseif #list == 0 then info('No stored sign-ins.') else vim.ui.select(list, { prompt = 'Sign out of', format_item = describe }, with) end end)endreturn { login = login, logout = logout, receive = receive }neovim/lua/bugabinga/pivi/buffer.lua
Addednew file mode 100644+11 / −0 text lines
return function(buffer, lines) local old = vim.api.nvim_buf_get_lines(buffer, 0, -1, false) local before, after = table.concat(old, '\n') .. '\n', table.concat(lines, '\n') .. '\n' local hunks = vim.diff(before, after, { result_type = 'indices' }) for index = #hunks, 1, -1 do local start, count, new_start, new_count = unpack(hunks[index]) local first = count == 0 and start or start - 1 local replacement = vim.list_slice(lines, new_start, new_start + new_count - 1) vim.api.nvim_buf_set_lines(buffer, first, first + count, false, replacement) endendneovim/lua/bugabinga/pivi/draft.lua
Addednew file mode 100644+69 / −0 text lines
return function(buffer, directory) local path = directory .. '/draft.txt' local temporary = path .. '.' .. vim.fn.getpid() .. '.tmp' local blocked, pending, reported local stat, failure, code = vim.uv.fs_stat(path) if stat then local ok, lines = pcall(vim.fn.readfile, path) if ok then vim.api.nvim_buf_set_lines(buffer, 0, -1, false, lines) else blocked = 'Cannot restore draft; original file left untouched: ' .. tostring(lines) end elseif code ~= 'ENOENT' then blocked = 'Cannot inspect saved draft: ' .. tostring(failure) end local function save() if not vim.api.nvim_buf_is_valid(buffer) then return end local file local ok, err = pcall(function() if blocked then error(blocked) end vim.fn.mkdir(directory, 'p', 448) file = assert(vim.uv.fs_open(temporary, 'w', 384)) local text = table.concat(vim.api.nvim_buf_get_lines(buffer, 0, -1, false), '\n') assert(vim.uv.fs_write(file, text, 0) == #text, 'Incomplete draft write') assert(vim.uv.fs_fsync(file)) assert(vim.uv.fs_close(file)) file = nil assert(vim.uv.fs_rename(temporary, path)) end) if file then vim.uv.fs_close(file) end if not ok then vim.uv.fs_unlink(temporary) vim.bo[buffer].modified = true if reported ~= tostring(err) then reported = tostring(err) vim.notify('Pivi draft not saved: ' .. reported, vim.log.levels.ERROR) end return false end reported = nil vim.bo[buffer].modified = false return true end vim.bo[buffer].buftype = 'acwrite' vim.bo[buffer].modified = blocked ~= nil vim.api.nvim_buf_attach(buffer, false, { on_lines = function() -- the draft is saved on its own: the modified flag would flash in the -- status line on every keystroke vim.bo[buffer].modified = false if pending then return end pending = true vim.defer_fn(function() pending = false save() end, 250) end, }) vim.api.nvim_create_autocmd({ 'BufLeave', 'BufWriteCmd' }, { buffer = buffer, callback = function() save() end }) local leave = vim.api.nvim_create_autocmd('VimLeavePre', { callback = function() save() end }) vim.api.nvim_create_autocmd('BufWipeout', { buffer = buffer, callback = function() vim.api.nvim_del_autocmd(leave) end, }) if blocked then vim.notify(blocked, vim.log.levels.ERROR) end return saveendneovim/lua/bugabinga/pivi/init.lua
Addednew file mode 100644+651 / −0 text lines
local auto = require 'std.auto'local map = require 'std.map'local view = require 'bugabinga.pivi.view'local connect = require 'bugabinga.pivi.transport'local auth = require 'bugabinga.pivi.auth'local review = require 'bugabinga.pivi.review'local root = vim.fn.fnamemodify(debug.getinfo(1, 'S').source:sub(2), ':h:h:h:h') .. '/pivi'local currentlocal function notify(message) vim.notify(tostring(message), vim.log.levels.ERROR, { title = 'pivi' })endlocal function request(state, method, params, done, settled) if not state.transport.running() then if settled then settled() end notify('Pivi is disconnected.') return end state.transport.request(method, params, function(ok, result) if settled then settled() end if not ok then notify(result) elseif done then done(result) end end)endlocal function menu(prompt, choices) vim.ui.select(choices, { prompt = prompt, format_item = function(choice) return choice[1] end }, function(choice) if choice then choice[2]() end end)endlocal function label(buffer) local name = vim.api.nvim_buf_get_name(buffer) return name ~= '' and vim.fn.fnamemodify(name, ':~:.') or '[No Name]'endlocal function is_workspace(buffer) return vim.api.nvim_buf_is_valid(buffer) and not vim.api.nvim_buf_get_name(buffer):match('^pivi://')endlocal function recent_buffer() local recent for _, info in ipairs(vim.fn.getbufinfo({ buflisted = 1 })) do local workspace = vim.bo[info.bufnr].buftype == '' and is_workspace(info.bufnr) if workspace and ( not recent or info.lastused > recent.lastused or (info.lastused == recent.lastused and info.bufnr > recent.bufnr) ) then recent = info end end return recent and recent.bufnrend-- a short trail of where the person has been, so the agent knows what they were-- doing without askinglocal trail = {}local function note_trail() local buffer = vim.api.nvim_get_current_buf() if not is_workspace(buffer) then return end local line = vim.api.nvim_win_get_cursor(0)[1] local last = trail[#trail] if last and last.buffer == buffer and math.abs(last.line - line) < 20 then return end trail[#trail + 1] = { buffer = buffer, line = line } while #trail > 4 do table.remove(trail, 1) endendlocal function trail_text() local parts = {} for _, step in ipairs(trail) do if vim.api.nvim_buf_is_valid(step.buffer) then local name = vim.fn.fnamemodify(vim.api.nvim_buf_get_name(step.buffer), ':.') parts[#parts + 1] = ('%s:%d'):format(name, step.line) end end return #parts > 0 and table.concat(parts, ' → ') or nilendlocal function editor_context() local buffer = recent_buffer() local where = trail_text() if not buffer then return ('[editor: cwd %s%s]'):format(vim.fn.getcwd(), where and (' · recent ' .. where) or '') end local window = vim.fn.bufwinid(buffer) local line = window ~= -1 and vim.api.nvim_win_get_cursor(window)[1] or vim.api.nvim_buf_get_mark(buffer, '"')[1] return ('[editor: cwd %s · buffer %d %s · line %d · %s%s]'):format( vim.fn.getcwd(), buffer, vim.api.nvim_buf_get_name(buffer), math.max(line, 1), vim.bo[buffer].modified and 'unsaved changes' or 'saved', where and (' · recent ' .. where) or '' )end-- where the agent works, shown in the buffer itself: the person never has to-- look at the conversationlocal activity_namespace = vim.api.nvim_create_namespace('pivi_activity')local activity = {}local function mark_activity(state, buffer, line) local mark = activity[buffer] or {} mark.line = line mark.started = vim.uv.now() mark.id = vim.api.nvim_buf_set_extmark(activity_namespace, buffer, line - 1, 0, { id = mark.id, virt_text = { { ' ⟳ pivi', 'PiviTool' } }, virt_text_pos = 'eol', hl_mode = 'combine', }) activity[buffer] = mark state.on_tick = function() for target, entry in pairs(activity) do if not vim.api.nvim_buf_is_valid(target) then activity[target] = nil else local elapsed = vim.uv.now() - entry.started local text = state.busy and (' ⟳ pivi %s · %s'):format(state.activity or 'working', span(elapsed)) or (' ✓ pivi · %s'):format(span(elapsed)) vim.api.nvim_buf_set_extmark(activity_namespace, target, entry.line - 1, 0, { id = entry.id, virt_text = { { text, state.busy and 'PiviTool' or 'PiviHeading' } }, virt_text_pos = 'eol', hl_mode = 'combine', }) if not state.busy and entry.done ~= true then entry.done = true vim.notify('Pivi finished here. :Pivi review shows the changes.', vim.log.levels.INFO, { title = 'pivi' }) end end end endendlocal function it(state) local buffer = vim.api.nvim_get_current_buf() if not is_workspace(buffer) then notify('PiviIt works in a workspace buffer.') return end local cursor = vim.api.nvim_win_get_cursor(0) local lines = vim.api.nvim_buf_get_lines(buffer, 0, -1, false) local first = math.max(1, cursor[1] - 40) local last = math.min(#lines, cursor[1] + 40) local excerpt = table.concat(vim.list_slice(lines, first, last), '\n') local path = vim.api.nvim_buf_get_name(buffer) local content = ('%s\n\n%s\n\n%s'):format( ('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( path, cursor[1] ), ('Here is the buffer around that place:'), excerpt ) mark_activity(state, buffer, cursor[1]) request(state, 'submit', { content = editor_context() .. '\n' .. content, mode = 'submit' }, function() vim.notify('Pivi is working on ' .. vim.fn.fnamemodify(path, ':.'), vim.log.levels.INFO, { title = 'pivi' }) end, function() activity[buffer] = nil notify('Pivi could not start the work.') end)endlocal function select_attachment(state, prompt, done) vim.ui.select( state.attachments, { prompt = prompt, format_item = function(item) return item.label end }, function(item) if item then done(item) end end )endlocal function attach(state) local function add(kind, buffer) if not buffer or not is_workspace(buffer) then notify('No workspace buffer to attach.') return end vim.fn.bufload(buffer) table.insert(state.attachments, { kind = kind, buffer = buffer, label = kind .. ': ' .. label(buffer) }) view.winbar(state) end menu('Attach to draft', { { 'Buffer', function() local buffers = vim.tbl_filter( function(buffer) return vim.bo[buffer].buflisted and is_workspace(buffer) end, vim.api.nvim_list_bufs() ) local format = function(buffer) return buffer .. ': ' .. label(buffer) end vim.ui.select(buffers, { prompt = 'Buffer', format_item = format }, function(buffer) if buffer then add('buffer', buffer) end end) end, }, { 'File', function() vim.ui.input({ prompt = 'File: ', completion = 'file' }, function(path) if path and path ~= '' then add('file', vim.fn.bufadd(vim.fn.fnamemodify(path, ':p'))) end end) end, }, { 'Diagnostics', function() add('diagnostics', recent_buffer()) end }, })endlocal function detach(state) select_attachment(state, 'Remove attachment', function(selected) state.attachments = vim.tbl_filter(function(item) return item ~= selected end, state.attachments) view.winbar(state) end)endlocal function attachment_text(attachment) local buffer = attachment.buffer local name = vim.api.nvim_buf_get_name(buffer) if attachment.kind ~= 'diagnostics' then local content = table.concat(vim.api.nvim_buf_get_lines(buffer, 0, -1, false), '\n') return ('<buffer number="%d" name="%s">\n%s\n</buffer>'):format(buffer, name, content) end local lines = vim.tbl_map(function(diagnostic) local severity = vim.diagnostic.severity[diagnostic.severity] return ('%d:%d %s %s'):format(diagnostic.lnum + 1, diagnostic.col + 1, severity, diagnostic.message) end, vim.diagnostic.get(buffer)) return ('<diagnostics buffer="%d" name="%s">\n%s\n</diagnostics>'):format(buffer, name, table.concat(lines, '\n'))endlocal function submit(state, mode) if state.submitting then return end local text = view.draft(state) if text:match('^%s*$') then notify('Draft is empty.') return end local sent = vim.list_slice(state.attachments) local parts = { editor_context() .. '\n' .. text } for _, attachment in ipairs(sent) do if not vim.api.nvim_buf_is_valid(attachment.buffer) then notify('Attached buffer no longer exists: ' .. attachment.label) return end parts[#parts + 1] = attachment_text(attachment) end state.submitting = true view.winbar(state) request(state, 'submit', { content = table.concat(parts, '\n\n'), mode = mode }, function() if view.draft(state) == text then view.set_draft(state, '') end state.attachments = vim.tbl_filter(function(item) return not vim.tbl_contains(sent, item) end, state.attachments) view.winbar(state) for _, window in ipairs(vim.fn.win_findbuf(state.buffer)) do view.follow(state, window) end end, function() state.submitting = false view.winbar(state) end)endlocal function fork(state, id) if not id then notify('Place cursor on a committed entry.') return end local previous, prompt for _, item in ipairs(state.view.items) do local entry = item.entry if entry and entry.id == id then local lines = view.entry_lines(state, id) if entry.kind == 'pi.user' then prompt = table.concat(lines, '\n', 2, #lines - 1):gsub('^%[editor: [^\n]*%]\n', '') end break end previous = entry and entry.id or previous end if not prompt then request(state, 'fork', { entry = id }) elseif not view.draft(state):match('^%s*$') then notify('Draft is not empty. Submit or clear it before forking at a prompt.') else request(state, previous and 'fork' or 'new', { entry = previous }, function() view.set_draft(state, prompt) vim.api.nvim_set_current_buf(state.draft_buffer) end) endendlocal function inspect_entry(state, entry) if not entry then notify('No entry at cursor.') return end view.page('entry', view.entry_lines(state, entry))endlocal function open_attachment(state) if #state.attachments == 0 then notify('No attachments.') return end select_attachment(state, 'Open attachment', function(item) if vim.api.nvim_buf_is_valid(item.buffer) then vim.api.nvim_set_current_buf(item.buffer) end end)endlocal function goblin(state, first, last) local buffer = vim.api.nvim_get_current_buf() if buffer == state.buffer or buffer == state.draft_buffer then notify('Goblin works from a code buffer.') return end local name = vim.api.nvim_buf_get_name(buffer) local cursor = vim.api.nvim_win_get_cursor(vim.fn.bufwinid(buffer))[1] local lines = vim.api.nvim_buf_get_lines(buffer, first - 1, last, false) local selection = first ~= 1 or last ~= vim.api.nvim_buf_line_count(buffer) local position = selection and ('lines %d-%d of'):format(first, last) or ('cursor at line %d of'):format(cursor) local attachment = ('<buffer number="%d" name="%s" %s>' .. '\n' .. table.concat(lines, '\n') .. '\n</buffer>'):format(buffer, name, position) local prompt = vim.g.pivi_goblin_prompt or 'The attached buffer holds a rough sketch or pseudo-code. Finish it into working code at the marked position: ' .. 'complete the sketch, keep intent, naming and surroundings, and keep the edit unsaved for review.' request(state, 'submit', { content = editor_context() .. '\n' .. prompt .. '\n\n' .. attachment, mode = state.busy and 'followUp' or 'submit', })endlocal function goblin_keys(state) vim.keymap.set('x', 'gb', function() goblin(state, vim.fn.line('v'), vim.fn.line('.')) end, { desc = 'pivi goblin: send the selection to the agent', }) vim.keymap.set('n', 'gb', function() vim.go.operatorfunc = function() goblin(state, vim.fn.line("'['"), vim.fn.line("]")) end return 'g@' end, { expr = true, desc = 'pivi goblin: send a motion to the agent (gb with no motion sends the whole buffer)' })endlocal actions = { help = function(state) view.help(state, false) end, toggle = function(state) if vim.api.nvim_get_current_buf() == state.draft_buffer then view.focus_conversation(state) else view.draft_split(state) end end, submit = function(state) submit(state, 'submit') end, steer = function(state) submit(state, 'steer') end, followUp = function(state) submit(state, 'followUp') end, review = review, abort = function(state) if state.stopping then return end if not state.transport.running() then notify('Pivi is disconnected. Run :Pivi to reconnect before stopping retained work.') return end local inbox = state.view and state.view.docs['pi.inbox'] local queued = {} for _, item in ipairs(inbox and inbox.items or {}) do if type(item.content) == 'string' then queued[#queued + 1] = (item.content:gsub('^%[editor: [^\n]*%]\n', '')) end end if not state.view then return end state.stopping = true view.render(state, state.view) state.transport.request('abort', nil, function(ok, failure) state.stopping = false view.render(state, state.view) if not ok then notify(failure) elseif #queued > 0 then local draft = view.draft(state) if not draft:match('^%s*$') then table.insert(queued, 1, draft) end view.set_draft(state, table.concat(queued, '\n\n')) vim.notify('Queued messages are back in the draft.', vim.log.levels.INFO, { title = 'pivi' }) end end) end, fork = function(state) fork(state, view.entry(state)) end, inspect = function(state) if view.context(state) == 'draft' then open_attachment(state) else inspect_entry(state, view.entry(state)) end end, actions = function(state) if view.context(state) ~= 'draft' then local entry = view.entry(state) menu('Pivi entry', { { 'Inspect entry', function() inspect_entry(state, entry) end }, { 'Fork at entry', function() fork(state, entry) end }, }) elseif #state.attachments == 0 then attach(state) else menu('Pivi draft', { { 'Attach context', function() attach(state) end }, { 'Open attachment', function() open_attachment(state) end }, { 'Remove attachment', function() detach(state) end }, }) end end,}local function dispatch(state, action) if state ~= current then notify('This pivi buffer is not connected. Run :Pivi.') return end actions[action](state)endlocal function disconnected(state, message) view.disconnected(state, message)endlocal function stop() local state = current if not state then return end current = nil state.transport.close() disconnected(state)endlocal function start() if current and not (current.transport.running() and vim.api.nvim_buf_is_valid(current.buffer)) then stop() end if not current then if vim.fn.isdirectory(root .. '/node_modules') == 0 then notify('Pivi dependencies missing. Run `just pivi-install`.') return end local id = vim.g.PiviSession if type(id) ~= 'string' or not id:match('^[%w_-]+$') then id = vim.fn.sha256(vim.uv.hrtime() .. ':' .. vim.fn.getpid()):sub(1, 8) vim.g.PiviSession = id end vim.opt.sessionoptions:append('globals') local argv = { vim.g.pivi_node or 'node', root .. '/worker.mjs', vim.fn.stdpath('state') .. '/pivi/sessions/' .. id .. '/session.sqlite', vim.fn.stdpath('state') .. '/pivi/auth.json', vim.g.pivi_config, } local state = view.create(id, dispatch) local ok, transport = pcall(connect, argv, function(record) if current ~= state then return end if record.type == 'exit' then local message = (record.code ~= 0 or record.protocol_error or not state.ready) and ('Pivi worker exited (%d). %s'):format(record.code, record.error) or nil disconnected(state, message) if message then notify(message) end elseif record.type == 'view' then -- a view that cannot be drawn must not take the worker down local drawn, failure = pcall(view.render, state, record.view) if not drawn and failure ~= state.render_failure then state.render_failure = failure vim.notify('Pivi could not draw the conversation: ' .. tostring(failure), vim.log.levels.ERROR, { title = 'pivi', }) end elseif record.type == 'ready' then state.ready = true elseif record.type == 'report' then notify(record.error) elseif record.type == 'notice' then vim.notify(record.message, vim.log.levels.INFO, { title = 'pivi' }) else auth.receive(state, record) end end) if not ok then view.disconnected(state, tostring(transport)) vim.api.nvim_set_current_buf(state.buffer) notify(transport) return end state.id, state.transport, state.ready = id, transport, false current = state goblin_keys(state) end return currentendlocal function show() local state = start() if not state then return end vim.api.nvim_set_current_buf(state.buffer) view.draft_split(state)endlocal sign_inlocal function choose_model(state, value, only) local function configure(provider, model) request(state, 'configure', { model = { provider = provider, modelId = model } }) end if value ~= '' then local provider, model = value:match('^([^/]+)/(.+)$') if not provider then notify('Use provider/model-id.') return end configure(provider, model) return end request(state, 'models', nil, function(models) if only then models = vim.tbl_filter(function(item) return item.provider == only end, models) end if #models == 0 and only then notify('Signed in, but ' .. only .. ' offers no models.') return elseif #models == 0 then vim.notify('No usable models yet. Sign in to a provider first.', vim.log.levels.INFO, { title = 'pivi' }) sign_in(state, '') return end local format = function(item) return item.provider .. '/' .. item.modelId end vim.ui.select(models, { prompt = 'Pivi model', format_item = format }, function(choice) if choice then configure(choice.provider, choice.modelId) end end) end)endsign_in = function(state, provider) auth.login(state, provider, function(signed_in) if state.model == 'no model' then choose_model(state, '', signed_in.id) end end)endlocal commands = { login = sign_in, logout = auth.logout, show = function(state) vim.api.nvim_set_current_buf(state.buffer) view.draft_split(state) end, draft = function(state) view.draft_split(state) end, help = function(state) view.help(state, true) end, model = choose_model, attach = attach, fork = actions.fork, compact = function(state, instructions) request(state, 'compact', { instructions = instructions }) end, new = function(state) request(state, 'new') end, earlier = function(state) request(state, 'earlier') end, resume = function(state) request(state, 'resume') end, continue = function(state) if state.busy then notify('Work is still retained. Use :Pivi resume for suspended work, or :Pivi stop first.') return end if not (state.view and state.view.docs['pi.live'].runFailure) then notify('No stopped run to continue. Write a new draft instead.') return end menu('Continue from retained history? Existing edits stay; the model may repeat actions.', { { 'Keep stopped', function() end }, { 'Continue run', function() request(state, 'continue') end }, }) end, review = review, it = it, goblin = function(state) goblin(state, 1, vim.api.nvim_buf_line_count(vim.api.nvim_get_current_buf())) end, stop = function(state) actions.abort(state) end, reload = function() stop() for _, buffer in ipairs(vim.api.nvim_list_bufs()) do if vim.api.nvim_buf_get_name(buffer):match('^pivi://') then pcall(vim.api.nvim_buf_delete, buffer, { force = true }) end end for name in pairs(package.loaded) do if name:match('^bugabinga%.pivi') then package.loaded[name] = nil end end require('bugabinga.pivi').show() end,}local names = vim.tbl_keys(commands)table.insert(names, 'close')table.sort(names)vim.api.nvim_create_user_command('Pivi', function(options) local name, argument = options.args:match('^(%S*)%s*(.*)$') if name == 'close' then stop() return end local command = commands[name == '' and 'show' or name] if not command then notify('Unknown Pivi command: ' .. name) return end local state = start() if state then command(state, argument) endend, { nargs = '*', complete = function(lead) return vim.tbl_filter(function(name) return vim.startswith(name, lead) end, names) end, desc = 'Pivi: standalone Pi Durable harness',})map.normal { keys = view.prefix() .. 'p', description = 'Open pivi', category = 'pivi', command = show }map.normal { keys = view.prefix() .. 'pi', description = 'Let pivi finish the work here', category = 'pivi', command = function() local state = start() if state then it(state) end end,}auto('pivi_lifecycle') { { events = 'VimLeavePre', command = stop }, { events = 'BufModifiedSet', command = function() if current then view.winbar(current) end end, }, { events = 'SessionLoadPost', command = function() if current and current.id ~= vim.g.PiviSession then stop() end if vim.api.nvim_buf_get_name(0):match('^pivi://') then show() end end, },}vim.api.nvim_create_autocmd({ 'CursorMoved', 'BufEnter' }, { callback = note_trail })_G.BugabingaPivi = { show = show, close = stop, current = function() return current end,}return _G.BugabingaPivineovim/lua/bugabinga/pivi/lsp.lua
Addednew file mode 100644+163 / −0 text lines
local METHODS = { definition = 'textDocument/definition', references = 'textDocument/references', implementation = 'textDocument/implementation', type_definition = 'textDocument/typeDefinition', hover = 'textDocument/hover', rename = 'textDocument/rename', symbols = 'textDocument/documentSymbol', workspace_symbols = 'workspace/symbol',}local ATTACH_MS = 10000local RETRY_MS = 300local LIMIT = 100return function(helpers) local function kind(symbol) return (vim.lsp.protocol.SymbolKind[symbol.kind] or 'Symbol'):lower() end local function position(buffer, client, args) local text = vim.api.nvim_buf_get_lines(buffer, args.line - 1, args.line, false)[1] if not text then error(('Line %d does not exist in %s.'):format(args.line, args.path), 0) end local column = (text:find('%S') or 1) - 1 if args.symbol then local from = text:find(args.symbol, 1, true) if not from then error( ('"%s" is not on line %d of %s, which reads: %s'):format(args.symbol, args.line, args.path, vim.trim(text)), 0 ) end column = from - 1 end return { line = args.line - 1, character = vim.str_utfindex(text, client.offset_encoding, column) } end local function locations(result) local files, lines = {}, {} for _, item in ipairs(vim.islist(result) and result or { result }) do local path = vim.uri_to_fname(item.uri or item.targetUri) local start = (item.range or item.targetSelectionRange).start if not files[path] then local buffer = vim.fn.bufnr(path) local loaded = buffer ~= -1 and vim.api.nvim_buf_is_loaded(buffer) files[path] = loaded and vim.api.nvim_buf_get_lines(buffer, 0, -1, false) or vim.uv.fs_stat(path) and vim.fn.readfile(path) or {} end local source = vim.trim(files[path][start.line + 1] or '') lines[#lines + 1] = ('%s:%d:%d %s'):format(helpers.relative(path), start.line + 1, start.character + 1, source) end table.sort(lines) return helpers.limited(vim.fn.uniq(lines), LIMIT, 'locations') end local function outline(symbols, indent, lines) for _, symbol in ipairs(symbols) do local range = symbol.selectionRange or symbol.range or symbol.location.range lines[#lines + 1] = ('%s%s %s :%d'):format(indent, kind(symbol), symbol.name, range.start.line + 1) outline(symbol.children or {}, indent .. ' ', lines) end return lines end local function present(operation, result, client, args) if operation == 'hover' then return table.concat(vim.lsp.util.convert_input_to_markdown_lines(result.contents), '\n') elseif operation == 'symbols' then return helpers.limited(outline(result, '', {}), 300, 'symbols') elseif operation == 'workspace_symbols' then local lines = vim.tbl_map(function(symbol) local path = helpers.relative(vim.uri_to_fname(symbol.location.uri)) local line = symbol.location.range and symbol.location.range.start.line + 1 or 1 return ('%s:%d %s %s'):format(path, line, kind(symbol), symbol.name) end, result) table.sort(lines, function(a, b) local outside_a, outside_b = vim.startswith(a, '/'), vim.startswith(b, '/') if outside_a ~= outside_b then return outside_b end return a < b end) return helpers.limited(lines, LIMIT, 'symbols') elseif operation == 'rename' then vim.lsp.util.apply_workspace_edit(result, client.offset_encoding) local files = vim.tbl_keys(result.changes or {}) for _, change in ipairs(result.documentChanges or {}) do if change.textDocument then files[#files + 1] = change.textDocument.uri end end files = vim.tbl_map(function(uri) return helpers.relative(vim.uri_to_fname(uri)) end, files) table.sort(files) local list = table.concat(vim.fn.uniq(files), ', ') return ('Renamed to %s in: %s. These buffers have unsaved changes.'):format(args.newName, list) end return locations(result) end return function(args, done) local operation, method = args.operation, METHODS[args.operation] if not method then error('Unknown lsp operation: ' .. tostring(operation), 0) end local positional = operation ~= 'symbols' and operation ~= 'workspace_symbols' if operation ~= 'workspace_symbols' and not args.path then error(operation .. ' needs path.', 0) end if positional and not args.line then error(operation .. ' needs line.', 0) end if operation == 'rename' and not args.newName then error('rename needs newName.', 0) end if operation == 'workspace_symbols' and not args.query then error('workspace_symbols needs query.', 0) end local buffer = args.path and helpers.load(args.path) local deadline = vim.uv.now() + ATTACH_MS local timer, cancelled, waited local function later(action, delay) timer = vim.defer_fn(function() if not cancelled then action() end end, delay) end local function ask(client, params, retries) client:request(method, params, function(failure, result) if cancelled then return end if failure then return done { text = failure.message or vim.inspect(failure), error = true } end local empty = result == nil or (vim.islist(result) and #result == 0) if empty and retries > 0 then return later(function() ask(client, params, retries - 1) end, RETRY_MS) end if empty then return done { text = 'No results.' } end local ok, text = pcall(present, operation, result, client, args) done { text = text, error = not ok } end, buffer) end local function start() local client = vim.lsp.get_clients({ bufnr = buffer, method = method })[1] if client and client.initialized then local ok, params = pcall(function() if operation == 'workspace_symbols' then return { query = args.query } end local document = { uri = vim.uri_from_bufnr(buffer) } if operation == 'symbols' then return { textDocument = document } end local params = { textDocument = document, position = position(buffer, client, args) } params.context = operation == 'references' and { includeDeclaration = true } or nil params.newName = args.newName return params end) if not ok then return done { text = params, error = true } end return ask(client, params, waited and 20 or 2) end local configured, configs = pcall(vim.lsp.get_configs, { enabled = true, filetype = buffer and vim.bo[buffer].filetype }) if buffer and vim.uv.now() < deadline and (not configured or #configs > 0) then waited = true return later(start, 100) end local where = buffer and ('%s (filetype %s)'):format(args.path, vim.bo[buffer].filetype) or 'this session' done { text = ('No language server offers %s for %s. Search with rg instead.'):format(operation, where), error = true, } end start() return function() cancelled = true if timer and not timer:is_closing() then timer:close() end end endendneovim/lua/bugabinga/pivi/review.lua
Addednew file mode 100644+137 / −0 text lines
local set_lines = require 'bugabinga.pivi.buffer'local function notify(message) vim.notify(message, vim.log.levels.INFO, { title = 'pivi' })endlocal function collect() local lines, targets, hunks = {}, {}, {} local function add(line, buffer, row, hunk) lines[#lines + 1] = line targets[#lines] = { buffer = buffer, row = row, hunk = hunk } end add('pivi review · <CR> jump · s save change · r revert change · S save file · R revert file · q back') for _, buffer in ipairs(vim.api.nvim_list_bufs()) do local name = vim.api.nvim_buf_get_name(buffer) if vim.bo[buffer].modified and vim.bo[buffer].buftype == '' and name ~= '' then local saved = vim.uv.fs_stat(name) and table.concat(vim.fn.readfile(name), '\n') .. '\n' or '' local current = table.concat(vim.api.nvim_buf_get_lines(buffer, 0, -1, false), '\n') .. '\n' local path = vim.fn.fnamemodify(name, ':.') add('--- ' .. (saved == '' and '/dev/null' or 'a/' .. path), buffer, 1) add('+++ b/' .. path, buffer, 1) local row, hunk = 1, nil for _, line in ipairs(vim.split(vim.diff(saved, current, { ctxlen = 3 }), '\n', { trimempty = true })) do local old_start, old_count, new_start, new_count = line:match('^@@ %-(%d+),?(%d*) %+(%d+),?(%d*) @@') if old_start then old_count, new_count = tonumber(old_count) or 1, tonumber(new_count) or 1 hunk = { old_from = old_count == 0 and tonumber(old_start) or old_start - 1, old_count = old_count, new_from = new_count == 0 and tonumber(new_start) or new_start - 1, new_count = new_count, } row = math.max(tonumber(new_start), 1) hunks[#hunks + 1] = { bufnr = buffer, lnum = row, text = line } end add(line, buffer, row, hunk) if not old_start and line:sub(1, 1) ~= '-' then row = row + 1 end end end end return lines, targets, hunksendlocal page, origin, targetslocal function refresh() local lines, hunks lines, targets, hunks = collect() vim.bo[page].modifiable = true vim.api.nvim_buf_set_lines(page, 0, -1, false, #lines > 1 and lines or { 'No unsaved changes.' }) vim.bo[page].modifiable = false vim.fn.setqflist({}, 'r', { title = 'pivi review', items = hunks }) return #lines > 1endlocal function key(lhs, description, action) vim.keymap.set('n', lhs, function() local target = targets[vim.api.nvim_win_get_cursor(0)[1]] if target and target.buffer and vim.api.nvim_buf_is_valid(target.buffer) then action(target) end end, { buffer = page, nowait = true, desc = 'pivi: ' .. description })endlocal function create() page = vim.api.nvim_create_buf(false, true) vim.api.nvim_buf_set_name(page, 'pivi://review') vim.bo[page].filetype = 'diff' vim.bo[page].bufhidden = 'hide' vim.api.nvim_create_autocmd('BufEnter', { buffer = page, callback = refresh }) vim.keymap.set('n', 'q', function() if origin and vim.api.nvim_buf_is_valid(origin) then vim.api.nvim_set_current_buf(origin) end end, { buffer = page, nowait = true, desc = 'pivi: Leave review' }) key('<CR>', 'Jump to this change', function(target) vim.api.nvim_set_current_buf(target.buffer) vim.api.nvim_win_set_cursor(0, { math.min(target.row, vim.api.nvim_buf_line_count(target.buffer)), 0 }) end) local function on_change(action) return function(target) local name = vim.api.nvim_buf_get_name(target.buffer) if not target.hunk then notify('Place the cursor on a change. S and R act on the whole file.') elseif not vim.uv.fs_stat(name) then notify('This file is not on disk yet. S saves it, R discards it.') else action(target.buffer, target.hunk, name, vim.fn.readfile(name)) refresh() end end end key( 's', 'Save this change', on_change(function(buffer, hunk, _, disk) local full = vim.api.nvim_buf_get_lines(buffer, 0, -1, false) local only = vim.list_slice(disk, 1, hunk.old_from) vim.list_extend(only, full, hunk.new_from + 1, hunk.new_from + hunk.new_count) vim.list_extend(only, disk, hunk.old_from + hunk.old_count + 1) set_lines(buffer, only) vim.api.nvim_buf_call(buffer, function() vim.cmd('silent write') end) set_lines(buffer, full) end) ) key( 'r', 'Revert this change', on_change(function(buffer, hunk, _, disk) local original = vim.list_slice(disk, hunk.old_from + 1, hunk.old_from + hunk.old_count) vim.api.nvim_buf_set_lines(buffer, hunk.new_from, hunk.new_from + hunk.new_count, false, original) if vim.deep_equal(vim.api.nvim_buf_get_lines(buffer, 0, -1, false), disk) then vim.bo[buffer].modified = false end end) ) key('S', 'Save this file', function(target) vim.fn.mkdir(vim.fs.dirname(vim.api.nvim_buf_get_name(target.buffer)), 'p') vim.api.nvim_buf_call(target.buffer, function() vim.cmd('silent write') end) refresh() end) key('R', 'Revert this file to disk', function(target) local name = vim.api.nvim_buf_get_name(target.buffer) local question = 'Discard unsaved changes in ' .. vim.fn.fnamemodify(name, ':.') .. '?' if vim.fn.confirm(question, '&Discard\n&Keep', 2) ~= 1 then return end if vim.uv.fs_stat(name) then vim.api.nvim_buf_call(target.buffer, function() vim.cmd('silent edit!') end) else vim.api.nvim_buf_delete(target.buffer, { force = true }) end refresh() end)endreturn function() if not page or not vim.api.nvim_buf_is_valid(page) then create() end if not refresh() then vim.notify('No unsaved changes.', vim.log.levels.INFO, { title = 'pivi' }) return end if vim.api.nvim_get_current_buf() ~= page then origin = vim.api.nvim_get_current_buf() end vim.api.nvim_set_current_buf(page)endneovim/lua/bugabinga/pivi/tools.lua
Addednew file mode 100644+325 / −0 text lines
local set_lines = require 'bugabinga.pivi.buffer'local LIST_LIMIT = 300local function absolute(path) return vim.fs.normalize(vim.fn.fnamemodify(path, ':p'))endlocal function relative(path) return vim.fn.fnamemodify(path, ':.')endlocal function is_workspace(buffer) return vim.bo[buffer].buftype == '' and vim.api.nvim_buf_get_name(buffer) ~= ''endlocal function unsaved() return vim.tbl_filter( function(buffer) return vim.bo[buffer].modified and is_workspace(buffer) end, vim.api.nvim_list_bufs() )endlocal function load(path, create) local name = absolute(path) if not create and vim.fn.bufexists(name) == 0 and not vim.uv.fs_stat(name) then error('No such file or buffer: ' .. path, 0) end local buffer = vim.fn.bufadd(name) local shortmess = vim.o.shortmess vim.o.shortmess = shortmess .. 'A' local loaded, failure = pcall(vim.fn.bufload, buffer) vim.o.shortmess = shortmess if not loaded then error(failure, 0) end return buffer, nameendlocal function limited(lines, limit, what) if #lines <= limit then return table.concat(lines, '\n') end return table.concat(lines, '\n', 1, limit) .. ('\n[%d more %s not shown; narrow the search]'):format(#lines - limit, what)endlocal function unsaved_text(args, done) local name = absolute(args.path) local number = vim.fn.bufnr(name) local known = vim.fn.bufexists(name) == 1 and vim.api.nvim_buf_is_loaded(number) and is_workspace(number) if not known or (not vim.bo[number].modified and vim.uv.fs_stat(name)) then return done(vim.empty_dict()) end local text = table.concat(vim.api.nvim_buf_get_lines(number, 0, -1, false), '\n') done { text = text .. (vim.bo[number].endofline and '\n' or '') }endlocal function set_text(args, done) local number = load(args.path, true) local lines = vim.split(args.content, '\n', { plain = true }) if lines[#lines] == '' then lines[#lines] = nil end set_lines(number, lines) vim.bo[number].buflisted = true done(vim.empty_dict())endlocal SLICE_NS = 10 * 1e9local BLOCKING = '%s blocks the editor. Use await(), system() or sleep() instead.'local function refuse(name) return function() error(BLOCKING:format(name), 2) endendlocal guarded = setmetatable({ wait = refuse('vim.wait'), fn = setmetatable( { system = refuse('vim.fn.system'), systemlist = refuse('vim.fn.systemlist') }, { __index = vim.fn } ), system = function(...) return setmetatable({ wait = refuse('vim.system(...):wait') }, { __index = vim.system(...) }) end,}, { __index = vim })local function nvim_lua(args, done, progress) local chunk, failure = loadstring(args.code, '=nvim_lua') if not chunk then error(failure, 0) end local thread, cancelled local cancels = {} local function resume(...) if cancelled then return end local started = vim.uv.hrtime() debug.sethook(function() if vim.uv.hrtime() - started > SLICE_NS then error('nvim_lua ran for 10 s without yielding and was stopped. Use await(), system() or sleep().', 2) end end, '', 1000000) local results = vim.F.pack_len(coroutine.resume(thread, ...)) debug.sethook() if not results[1] then return done { text = tostring(results[2]), error = true } end if coroutine.status(thread) ~= 'dead' then return end local value = results[2] if type(value) ~= 'string' then local ok, encoded = pcall(vim.json.encode, value) value = ok and encoded or vim.inspect(value) if type(value) == 'table' then value = vim.inspect(value) end end done { text = value } end local function await(start) local settled, cancel = false, nil cancel = start(function(...) if settled then return end settled = true local values = vim.F.pack_len(...) vim.schedule(function() cancels[cancel or false] = nil resume(vim.F.unpack_len(values)) end) end) if type(cancel) == 'function' then cancels[cancel] = true end return coroutine.yield() end local function sleep(milliseconds) return await(function(resolve) local timer = vim.defer_fn(resolve, milliseconds) return function() if not timer:is_closing() then timer:close() end end end) end local function plain(text) return (tostring(text):gsub('\27%[[%d;]*%a', ''))endlocal function system(command, options) options = options or {} local hidden = vim.tbl_map(function(number) return relative(vim.api.nvim_buf_get_name(number)) end, unsaved()) if #hidden > 0 then progress(('[unsaved buffers this command cannot see: %s]\n'):format(table.concat(hidden, ', '))) end return await(function(resolve) local output = { stdout = {}, stderr = {} } local function stream(name) return function(_, data) if not data then return end table.insert(output[name], data) vim.schedule(function() progress(data) end) end end local process, timed_out, killed local function kill(how) killed = killed or how or 'sigterm' pcall(vim.uv.kill, -process.pid, killed) end local seconds = options.timeout or 60 local timer = vim.defer_fn(function() timed_out = true kill('sigterm') vim.defer_fn(function() if timed_out and killed == 'sigterm' then kill('sigkill') end end, 5000) end, seconds * 1000) local argv = type(command) == 'table' and command or { 'sh', '-c', command } local started started, process = pcall(vim.system, argv, { cwd = options.cwd, env = options.env, stdin = options.stdin, text = true, detach = true, stdout = stream('stdout'), stderr = stream('stderr'), }, function(result) vim.schedule(function() if not timer:is_closing() then timer:close() end resolve { code = result.code, signal = result.signal, timed_out = timed_out or false, stdout = plain(table.concat(output.stdout)), stderr = plain(table.concat(output.stderr)), } end) end) if not started then timer:close() error(process, 0) end return function() if not timer:is_closing() then timer:close() end kill() end end) end local environment = { vim = guarded, await = await, sleep = sleep, system = system } jit.off(chunk, true) thread = coroutine.create(setfenv(chunk, setmetatable(environment, { __index = _G }))) resume() return function() cancelled = true for cancel in pairs(cancels) do cancel() end endend-- the file listing and content search tools: they exist so the agent never has to-- open a shell for the two things it does mostlocal EXCLUDED = { ['.git'] = true, ['node_modules'] = true, ['zig-cache'] = true, ['zig-out'] = true, ['.cache'] = true }local function glob_to_pattern(glob) local pattern = glob:gsub('([%^%$%(%)%%%.%[%]%+%-%*%?])', '%%%1'):gsub('%%%*', '[^/]*'):gsub('%%%?', '.') return '^' .. pattern .. '$'endlocal function find_files(args, done) local root = absolute(args.path or vim.fn.getcwd()) local wanted = args.glob and glob_to_pattern(args.glob) or nil local results, limit = {}, math.min(args.limit or 100, 300) local function walk(dir) if #results >= limit then return end for name, type in vim.fs.dir(dir) do if #results >= limit then break end local full = dir .. '/' .. name if type == 'directory' then if not EXCLUDED[name] then walk(full) end elseif not wanted or name:match(wanted) then results[#results + 1] = full end end end walk(root) local stat = vim.uv.fs_stat table.sort(results, function(a, b) local sa, sb = stat(a), stat(b) return (sa and sa.mtime.sec or 0) > (sb and sb.mtime.sec or 0) end) local lines = vim.tbl_map(function(file) return relative(file) end, results) done { text = #lines == 0 and 'No files matched.' or limited(lines, limit, 'files') }endlocal function search_files(args, done) if vim.fn.executable('rg') == 0 then return done { text = 'ripgrep is not installed.', error = true } end local argv = { 'rg', '--line-number', '--column', '--no-heading', '--color', 'never', '--max-count', tostring(args.max or 100) } if args.literal then argv[#argv + 1] = '--fixed-strings' end if args.glob then argv[#argv + 1] = '--glob' argv[#argv + 1] = args.glob end argv[#argv + 1] = args.pattern argv[#argv + 1] = absolute(args.path or vim.fn.getcwd()) vim.system(argv, { text = true }, function(result) -- the callback runs in a fast event context: the reply touches buffers vim.schedule(function() local out = result.stdout or '' if result.code == 1 and out == '' then return done { text = 'No matches.' } end if result.code ~= 0 then return done { text = (result.stderr or ''):gsub('%s+$', ''), error = true } end done { text = limited(vim.split(out:gsub('\n$', ''), '\n', { plain = true }), LIST_LIMIT, 'matches') } end) end)endlocal function save(args, done) local saved = {} for _, path in ipairs(args.paths) do local buffer, name = load(path) vim.fn.mkdir(vim.fs.dirname(name), 'p') vim.api.nvim_buf_call(buffer, function() vim.cmd('silent write!') end) saved[#saved + 1] = relative(name) end done { text = 'Saved ' .. table.concat(saved, ', ') .. '.' }endlocal function diagnostics(args, done) local buffer = args.path and load(args.path) or nil local lines = {} for _, item in ipairs(vim.diagnostic.get(buffer)) do lines[#lines + 1] = ('%s:%d:%d %s %s%s'):format( relative(vim.api.nvim_buf_get_name(item.bufnr)), item.lnum + 1, item.col + 1, vim.diagnostic.severity[item.severity], item.message, item.source and ' [' .. item.source .. ']' or '' ) end table.sort(lines) done { text = #lines == 0 and 'No diagnostics.' or limited(lines, LIST_LIMIT, 'diagnostics') }endlocal tools = { unsaved_text = unsaved_text, set_text = set_text, find = find_files, search = search_files, nvim_lua = nvim_lua, save = save, diagnostics = diagnostics, lsp = require 'bugabinga.pivi.lsp' { load = load, relative = relative, limited = limited },}return function(name, args, reply, progress) local finished = false local function done(result) if finished then return end finished = true for _, buffer in ipairs(unsaved()) do vim.bo[buffer].buflisted = true end reply(true, result) end local ok, cancel = pcall(function() if not tools[name] then error('Unknown tool: ' .. tostring(name), 0) end return tools[name](args, done, progress) end) if not ok then finished = true reply(false, cancel) end return ok and cancel or nilendneovim/lua/bugabinga/pivi/transport.lua
Addednew file mode 100644+93 / −0 text lines
local call = require 'bugabinga.pivi.tools'return function(argv, on_event) local pending, sequence, tail, stderr, stopped = {}, 0, '', '', false local cancels = {} local job, broken local function send(record) if stopped or broken then return false end local ok, bytes = pcall(vim.fn.chansend, job, vim.json.encode(record) .. '\n') return ok and bytes > 0 end local function reply(id, ok, result) local record = { type = 'reply', id = id, ok = ok } if ok then record.result = result else record.error = tostring(result) end send(record) end local function receive(line) local record = vim.json.decode(line, { luanil = { object = true, array = true } }) assert(type(record) == 'table' and type(record.type) == 'string', 'Expected a worker record with a type') if record.type == 'response' then local callback = pending[record.id] pending[record.id] = nil if callback then callback(record.ok, record.ok and record.result or record.error) end elseif record.type == 'tool' then local id = record.id cancels[id] = call(record.name, record.args, function(ok, result) cancels[id] = nil reply(id, ok, result) end, function(text) send({ type = 'progress', id = id, text = text }) end) else if record.type == 'cancel' and cancels[record.id] then cancels[record.id]() end on_event(record) end end job = vim.fn.jobstart(argv, { on_stdout = function(_, data) data[1] = tail .. data[1] tail = table.remove(data) for _, line in ipairs(data) do if broken then break end if line ~= '' then local ok, failure = pcall(receive, line) if not ok then broken = 'Cannot process worker message: ' .. tostring(failure) vim.fn.jobstop(job) end end end end, on_stderr = function(_, data) stderr = (stderr .. table.concat(data, '\n')):sub(-8192) end, on_exit = function(_, code) stopped = true if not broken and tail ~= '' then broken = 'Worker disconnected with an incomplete JSONL record.' end if broken then stderr = broken .. '\n' .. stderr end for _, cancel in pairs(cancels) do cancel() end local failed = pending pending = {} for _, callback in pairs(failed) do callback(false, 'Pivi worker exited (' .. code .. '). ' .. stderr) end on_event({ type = 'exit', code = code, error = stderr, protocol_error = broken ~= nil }) end, }) if job <= 0 then error('Cannot start pivi worker: ' .. argv[1]) end return { reply = reply, request = function(method, params, callback) sequence = sequence + 1 pending[sequence] = callback if not send({ id = sequence, method = method, params = params }) then pending[sequence] = nil callback(false, 'Pivi worker is not connected.') end end, close = function() if stopped then return end pcall(vim.fn.chanclose, job, 'stdin') if not vim.wait(2000, function() return stopped end, 10) then vim.fn.jobstop(job) end end, running = function() return not stopped and not broken end, }endneovim/lua/bugabinga/pivi/view.lua
Addednew file mode 100644+992 / −0 text lines
local namespace = vim.api.nvim_create_namespace('pivi')local HIGHLIGHT = { message = 'PiviHeading', user = 'PiviUserHeading', assistant = 'PiviAssistantHeading', detail = 'PiviTool', error = 'PiviError',}local ACTIONS = { { key = '?', name = 'help', text = 'Contextual binding help' }, { key = 'd', name = 'toggle', text = 'Toggle conversation / draft' }, { key = 'a', name = 'actions', text = 'Actions / attachments' }, { key = 'o', name = 'inspect', text = 'Inspect entry / attachment' }, { key = 'x', name = 'abort', text = 'Stop agent work' }, { key = 'r', name = 'review', text = 'Review unsaved changes' }, { key = 'f', name = 'fork', text = 'Fork at entry', zone = 'entry' }, { key = 's', name = 'submit', text = 'Submit idle draft', zone = 'draft', when = 'idle' }, { key = 't', name = 'steer', text = 'Steer active run', zone = 'draft', when = 'busy' }, { key = 'u', name = 'followUp', text = 'Queue follow-up', zone = 'draft', when = 'busy' },}local BODY = { nvim_lua = { 'code', 'lua' }, codemode = { 'code', 'javascript' }, write = { 'content', '' },}local USER_TITLE = { ['pi.compaction'] = 'compacted', ['pivi.interrupted'] = 'stopped by you' }local FAILURE = { model_error = 'model response failed', no_model = 'model unavailable', faulted = 'agent runtime failed', orphaned = 'task unavailable', interrupted = 'response interrupted', restart_limit = 'restart limit reached', nothing_to_answer = 'nothing to continue', turn_limit = 'tool round limit reached', reset = 'conversation reset', aborted = 'stopped',}local states = {}local range_at, renderlocal function prefix() return vim.g.pivi_prefix or '<leader>p'endlocal function shown(key) return vim.fn.keytrans(vim.keycode(prefix() .. key))endfor name, link in pairs({ PiviUser = 'NormalFloat', PiviUserHeading = 'Question', PiviAssistant = 'Visual', PiviAssistantHeading = 'Title', PiviHeading = 'Title', PiviTool = 'NonText', PiviCode = 'ColorColumn', PiviError = 'ErrorMsg',}) do vim.api.nvim_set_hl(0, name, { link = link, default = true })endlocal function split(text) return vim.split(tostring(text or ''), '\n', { plain = true })endlocal function draft(state) return table.concat(vim.api.nvim_buf_get_lines(state.draft_buffer, 0, -1, false), '\n')endlocal function set_draft(state, text) vim.api.nvim_buf_set_lines(state.draft_buffer, 0, -1, false, split(text)) if state.save_draft then state.save_draft() endendlocal function text_of(content) if type(content) == 'string' then return content end local parts = {} for _, part in ipairs(content or {}) do parts[#parts + 1] = part.text or '[image]' end return table.concat(parts, '\n')endlocal function span(ms) if ms < 1000 then return ms .. 'ms' end local seconds = math.floor(ms / 1000) return seconds < 60 and seconds .. 's' or ('%dm%02ds'):format(seconds / 60, seconds % 60)endlocal function section(lines, title, text, language) if title ~= '' then lines[#lines + 1] = title end if not language then return vim.list_extend(lines, split(text)) end local width = 3 for run in tostring(text):gmatch('`+') do width = math.max(width, #run + 1) end local fence = string.rep('`', width) lines[#lines + 1] = fence .. language vim.list_extend(lines, split(text)) lines[#lines + 1] = fenceend-- the first line of a folded body, so a closed fold still shows what it hideslocal function block(out, title, text, entry, kind, language) local lines = out.lines local range = { first = out.offset + #lines + 1, width = #title, entry = entry, kind = kind, turn = out.turn } section(lines, title, text, language) lines[#lines + 1] = '' range.last = out.offset + #lines out.ranges[#out.ranges + 1] = range return rangeend-- json arrives as one long line: pretty print it, so the transcript can be readlocal function pretty_json(text) local trimmed = vim.trim(text) if trimmed:sub(1, 1) ~= '{' and trimmed:sub(1, 1) ~= '[' then return nil end local ok, value = pcall(vim.json.decode, trimmed) if not ok or type(value) ~= 'table' then return nil end local function render(node, depth) if type(node) ~= 'table' then -- the strings are shown as they are: a decoded newline stays a newline if type(node) == 'string' then return node end return tostring(node) end local keys = vim.tbl_keys(node) table.sort(keys) if #keys == 0 then return '{}' end local list = #keys == #node and keys[1] == 1 local parts = {} for _, key in ipairs(keys) do parts[#parts+1] = list and render(node[key], depth + 1) or ('%s: %s'):format(vim.json.encode(key), render(node[key], depth + 1)) end local indent = (' '):rep(depth + 1) return (list and '[\n' or '{\n') .. indent .. table.concat(parts, ',\n' .. indent) .. '\n' .. (' '):rep(depth) .. (list and ']' or '}') end local rendered = render(value, 0) return renderedendlocal function result_text(message) local diff = message.toolName == 'edit' and type(message.details) == 'table' and message.details.diff local text = text_of(message.content):gsub('<harness>.-</harness>', '') if diff then return text .. '\n' .. diff, 'diff' end local json = pretty_json(text) if json then return json, 'json' end return text, 'text'endlocal function language_of(path) if type(path) ~= 'string' or path == '' then return nil end local filetype = vim.filetype.match { filename = path } if not filetype or filetype == '' then return nil end return vim.treesitter.language.get_lang(filetype) or filetypeend-- agent internals never enter the transcript: they are collected per entry and-- stay reachable through inspectlocal function tool_call(out, part, entry, result) local args = part.arguments local subject = args.path or args.command or args.pattern or args.code local title = 'tool: ' .. part.name if type(subject) == 'string' then local relative = vim.fn.fnamemodify(vim.trim(subject:match('^[^\n]*')), ':.') local head = vim.fn.strcharpart(relative, 0, 80) title = title .. ' ' .. head .. (vim.fn.strchars(head) < vim.fn.strchars(relative) and '…' or '') end local turn = out.turn turn.tools = (turn.tools or 0) + 1 local lines = { title, pretty_json(vim.json.encode(args)) or vim.json.encode(args) } if result then local text = select(1, result_text(result)) lines[#lines + 1] = (result.isError and 'error: ' or 'result: ') .. text if result.isError then turn.failed = (turn.failed or 0) + 1 turn.failed_name = turn.failed_name or part.name end if result.timestamp then turn.finish = result.timestamp end end lines[#lines + 1] = '' local hidden = out.hidden[entry] if not hidden then hidden = {} out.hidden[entry] = hidden end vim.list_extend(hidden, lines)endlocal function user_block(out, title, text, entry, turn) -- the editor context is sent to the model, but it is not part of the -- conversation the person reads local context = text:match('^%[editor: [^\n]*%]\n') if context then text = text:sub(#context + 1) end return block(out, title, text, entry, 'user')endlocal function committed(items) local out = { lines = {}, ranges = {}, hidden = {}, offset = 0, turn = {} } local results, paired = {}, {} for _, item in ipairs(items) do for _, message in ipairs(item.entry and item.entry.model or {}) do if message.role == 'toolResult' and message.toolCallId then results[message.toolCallId] = message end end end -- one quiet line where the agent worked: what it did, how long, what it cost local function status_line(out, entry) local turn = out.turn if turn.statused or not (turn.tools or turn.thoughts or turn.failed) then return end turn.statused = true local parts = { '⟳' } if turn.tools then parts[#parts + 1] = turn.tools .. ' tools' end if turn.thoughts then parts[#parts + 1] = turn.thoughts .. ' thoughts' end if turn.start and turn.finish then parts[#parts + 1] = span(turn.finish - turn.start) end if (turn.cost or 0) > 0 then parts[#parts + 1] = ('$%.3f'):format(turn.cost) end if turn.failed then parts[#parts + 1] = turn.failed .. ' failed' if turn.failed_name then parts[#parts + 1] = '(' .. turn.failed_name .. ')' end end block(out, table.concat(parts, ' '), '', entry, 'status') end for _, item in ipairs(items) do local entry = item.entry if not entry then local hint = item.kind == 'earlier' and '[Earlier history: :Pivi earlier]' or '[Entries not loaded]' vim.list_extend(out.lines, { hint, '' }) end for _, message in ipairs(item.entry and item.entry.model or {}) do if message.role == 'user' then local title = USER_TITLE[entry.kind] if entry.kind == 'pivi.interrupted' then block(out, title, '', entry.id, 'message') elseif title then block(out, title, text_of(message.content), entry.id, 'detail') else out.turn = { start = message.timestamp } user_block(out, '# you', text_of(message.content), entry.id, out.turn) end elseif message.role == 'toolResult' and not paired[message.toolCallId] then local text = select(1, result_text(message)) local lines = { (message.isError and 'error: ' or 'result: ') .. message.toolName, text, '' } local hidden = out.hidden[entry.id] if not hidden then hidden = {} out.hidden[entry.id] = hidden end vim.list_extend(hidden, lines) elseif message.role == 'assistant' then out.last_error = message.stopReason == 'error' and message.errorMessage or nil local turn = out.turn local final = message.stopReason ~= 'error' and message.stopReason ~= 'aborted' and not vim.iter(message.content):any(function(part) return part.type == 'toolCall' end) turn.cost = (turn.cost or 0) + (vim.tbl_get(message, 'usage', 'cost', 'total') or 0) if message.timestamp then turn.finish = message.timestamp + (message.durationMs or 0) end for _, part in ipairs(message.content) do if part.type == 'text' and part.text ~= '' then local turn_titled = turn.titled local title = not turn_titled and '# assistant' or message.stopReason == 'aborted' and 'partial response (interrupted)' or message.stopReason == 'error' and 'partial response (failed)' or '' turn.titled = true if final then status_line(out, entry.id) end block(out, title, part.text, entry.id, 'assistant') elseif part.type == 'thinking' then turn.thoughts = (turn.thoughts or 0) + 1 elseif part.type == 'toolCall' then if part.id then paired[part.id] = true end tool_call(out, part, entry.id, results[part.id]) end end if message.stopReason == 'error' then turn.failed = (turn.failed or 0) + 1 block( out, 'model attempt failed', message.errorMessage or 'Provider returned no error detail.', entry.id, 'error', 'text' ) end end end end return outendlocal function uncommitted(docs, offset, paused, last_error, started) local out = { lines = {}, ranges = {}, offset = offset, turn = {} } local live = docs['pi.live'] local partial = live.generation and live.generation.message local content = partial and partial.content or {} local final = not vim.iter(content):any(function(part) return part.type == 'toolCall' end) -- one live line in the tail: the transcript must not be dead air while work runs local running = vim.iter(live.tools or {}):find(function(tool) return tool.status ~= 'done' end) if running and not paused then local so_far = #(live.tools or {}) local clock = started and span(vim.uv.now() - started) or '' block(out, ('⟳ %d tools · %s · %s'):format(so_far, running.name, clock), '', nil, 'status') end local titled = false for _, part in ipairs(content) do if part.type == 'text' and part.text ~= '' then -- one turn reads as one assistant message: the first part carries the title local title = paused and 'partial response (suspended)' or not titled and '# assistant' or '' titled = true block(out, title, part.text, nil, 'assistant') elseif part.type == 'thinking' then -- the model's scratchpad stays out of the transcript out.turn.thoughts = (out.turn.thoughts or 0) + 1 end end if paused then block( out, 'work suspended', 'No work is running. :Pivi resume restarts retained tasks; :Pivi stop cancels them.\n' .. 'Review existing edits before resuming.', nil, 'message' ) end local retry = not paused and live.generation and live.generation.retry if retry then block(out, 'waiting to retry', retry.error, nil, 'error', 'text') block(out, '', 'Automatic retry scheduled by provider runtime. :Pivi stop cancels waiting.', nil, 'message') end local failure = live.runFailure if failure then local title = FAILURE[failure.reason] or 'run stopped: ' .. failure.reason local detail = failure.detail ~= last_error and failure.detail or nil block(out, title, detail or '', nil, failure.reason == 'aborted' and 'message' or 'error', detail and 'text' or nil) if failure.reason ~= 'aborted' then block( out, '', 'No automatic replay. Check the error, then :Pivi login, :Pivi model, or :Pivi continue.\n' .. 'Existing edits remain in buffers; :Pivi review before continuing.', nil, 'message' ) end end if live.compactionFailure then block(out, 'compaction failed', live.compactionFailure.error, nil, 'error', 'text') block(out, '', 'History retained. Resolve the error, then :Pivi compact to try again.', nil, 'message') end for _, item in ipairs(docs['pi.inbox'] and docs['pi.inbox'].items or {}) do if item.content then user_block(out, 'queued: ' .. item.mode, text_of(item.content), nil, out.turn) end end return outendlocal function splice(buffer, from, to, lines) local old = vim.api.nvim_buf_get_lines(buffer, from, to, false) local first, old_last, new_last = 1, #old, #lines while first <= old_last and first <= new_last and old[first] == lines[first] do first = first + 1 end while old_last >= first and new_last >= first and old[old_last] == lines[new_last] do old_last, new_last = old_last - 1, new_last - 1 end if first > old_last and first > new_last then return end vim.bo[buffer].modifiable = true vim.api.nvim_buf_set_lines(buffer, from + first - 1, from + old_last, false, vim.list_slice(lines, first, new_last)) vim.bo[buffer].modifiable = false return from + first, old_last - first + 1, new_last - first + 1endlocal function adorn(buffer, range) local start = range.first - (range.width == 0 and 1 or 0) local lines = vim.api.nvim_buf_get_lines(buffer, start, range.last, false) local fence, index = nil, 1 while index <= #lines do local line = lines[index] local row = start + index - 1 local run = line:match('^%s*(```+)') or line:match('^%s*(~~~+)') if fence or run then vim.api.nvim_buf_set_extmark(buffer, namespace, row, 0, { line_hl_group = 'PiviCode', priority = 100 }) if not fence then fence = run elseif run and run:sub(1, 1) == fence:sub(1, 1) and #run >= #fence and line:match('^%s*[`~]+%s*$') then fence = nil end end index = index + 1 endendlocal function decorate(state, groups, changed) local buffer = state.buffer local clear_from = changed for _, ranges in ipairs(groups) do for _, range in ipairs(ranges) do if range.last >= changed then if clear_from then vim.api.nvim_buf_clear_namespace(buffer, namespace, math.min(clear_from, range.first) - 1, -1) clear_from = nil end local row = range.first - 1 local line = vim.api.nvim_buf_get_lines(buffer, row, row + 1, false)[1] or '' vim.api.nvim_buf_set_extmark( buffer, namespace, row, 0, { end_col = math.min(range.width, #line), hl_group = HIGHLIGHT[range.kind] } ) if range.kind == 'user' then local region = { end_row = range.last - 1, hl_group = 'PiviUser', hl_eol = true, priority = 90 } vim.api.nvim_buf_set_extmark(buffer, namespace, row, 0, region) local note = vim.api.nvim_buf_get_lines(buffer, row + 1, row + 2, false)[1] or '' if note:match('^%[editor: ') then vim.api.nvim_buf_set_extmark(buffer, namespace, row + 1, 0, { end_col = #note, hl_group = 'PiviTool' }) end elseif range.kind == 'assistant' then local region = { end_row = range.last - 1, hl_group = 'PiviAssistant', hl_eol = true, priority = 90 } vim.api.nvim_buf_set_extmark(buffer, namespace, row, 0, region) adorn(buffer, range) elseif range.kind == 'message' then adorn(buffer, range) end end end end if clear_from then vim.api.nvim_buf_clear_namespace(buffer, namespace, clear_from - 1, -1) endendlocal function winbar(state) local windows = { [state.buffer] = vim.fn.win_findbuf(state.buffer), [state.draft_buffer] = vim.fn.win_findbuf(state.draft_buffer), } if #windows[state.buffer] == 0 and #windows[state.draft_buffer] == 0 then return end local labels = vim.tbl_map(function(attachment) return '+ ' .. attachment.label end, state.attachments) local unsaved = 0 for _, buffer in ipairs(vim.api.nvim_list_bufs()) do if vim.bo[buffer].modified and vim.bo[buffer].buftype == '' then unsaved = unsaved + 1 end end -- one clock for the whole turn: the status, then the time, then the activity local elapsed = state.started and span(vim.uv.now() - state.started) or nil local activity = state.activity or (state.busy and 'working' or nil) local busy_status = state.submitting and 'sending' or state.status .. (elapsed and ' ' .. elapsed or '') .. (activity and ' · ' .. activity or '') local status = state.submitting and 'sending' or state.status local model = state.model == 'no model' and 'loading models…' or state.model local retry = not state.paused and state.view and vim.tbl_get(state.view.docs, 'pi.live', 'generation', 'retry') if retry then local seconds = math.max(0, math.ceil((retry.at - vim.uv.gettimeofday() * 1000) / 1000)) busy_status = 'retry in ' .. seconds .. 's' status = busy_status end local conversation = { 'pivi', busy_status, model } if (state.cost_total or 0) >= 0.01 then conversation[#conversation + 1] = ('$%.2f'):format(state.cost_total) end conversation[#conversation + 1] = unsaved > 0 and unsaved .. ' unsaved' or nil local hint = state.status == 'disconnected' and ':Pivi reconnect' or state.busy and 'CR interrupt+send · C-J queue' or shown('?') .. ' help' local queued = state.view and #(vim.tbl_get(state.view.docs, 'pi.inbox', 'items') or {}) > 0 local draft_ready = vim.api.nvim_buf_is_valid(state.draft_buffer) and not vim.iter(vim.api.nvim_buf_get_lines(state.draft_buffer, 0, -1, false)):all(function(l) return l:match('^%s*$') end) for buffer, parts in pairs({ [state.buffer] = conversation, [state.draft_buffer] = { 'pivi draft', busy_status, model, state.busy and (queued and 'queued · C-J after this turn' or 'CR interrupts+send · C-J after this turn') or draft_ready and 'draft ready · CR sends' or nil, unpack(labels), }, }) do for _, window in ipairs(windows[buffer]) do local visible = vim.list_slice(parts) if buffer == state.buffer then local position = state.windows[window] visible[2] = visible[2] .. ' · ' .. (position and position.following and 'following' or 'reading') end local available = vim.api.nvim_win_get_width(window) - vim.fn.strdisplaywidth(hint) - 3 while #visible > 2 and vim.fn.strdisplaywidth(table.concat(visible, ' · ')) > available do table.remove(visible, 3) end local text = (table.concat(visible, ' · ') .. ' %= ' .. hint):gsub('%%', '%%%%'):gsub('%%%%=', '%%=') if vim.wo[window][0].winbar ~= text then vim.wo[window][0].winbar = text end end endend-- the view of a window, read without switching to it: switching windows marks-- every window for a full redraw, which flickers while the transcript streams.local function position(window) local cursor = vim.api.nvim_win_get_cursor(window) local info = vim.fn.getwininfo(window)[1] if not info then return { lnum = cursor[1], col = cursor[2], topline = cursor[1], leftcol = 0, curswant = cursor[2] } end return { lnum = cursor[1], col = cursor[2], coladd = 0, curswant = cursor[2], topline = info.topline, leftcol = info.leftcol or 0, skipcol = 0, }endlocal function observe(state, window) local current = position(window) local record = state.windows[window] or { following = state.view == nil } if record.view and ( record.view.lnum ~= current.lnum or record.view.col ~= current.col or record.input and not vim.deep_equal(record.view, current) ) then record.following = false end record.view, record.input = current, false state.windows[window] = record return recordendlocal function follow(state, window) window = window or vim.api.nvim_get_current_win() if not vim.api.nvim_win_is_valid(window) or vim.api.nvim_win_get_buf(window) ~= state.buffer then return end local record = observe(state, window) local adjusting = state.adjusting state.adjusting = true local last = vim.api.nvim_buf_line_count(state.buffer) -- touching another window while the user types moves the insert cursor away if window ~= vim.api.nvim_get_current_win() and vim.api.nvim_get_mode().mode:match('^i') then state.adjusting = adjusting return end record.following = true vim.api.nvim_win_set_cursor(window, { last, 0 }) state.adjusting = adjusting record.view = position(window) if not state.adjusting then winbar(state) endendlocal function focus_conversation(state) local window = vim.fn.win_findbuf(state.buffer)[1] if window and window ~= vim.api.nvim_get_current_win() then vim.api.nvim_set_current_win(window) else vim.api.nvim_set_current_buf(state.buffer) end follow(state, window)endlocal function draft_split(state) local existing = vim.fn.win_findbuf(state.draft_buffer)[1] if existing then vim.api.nvim_set_current_win(existing) return existing end local current = vim.api.nvim_get_current_win() local window = vim.api.nvim_win_get_buf(current) == state.buffer and current or vim.fn.win_findbuf(state.buffer)[1] if not window then -- the conversation takes the current window, the draft opens below it vim.api.nvim_set_current_buf(state.buffer) window = vim.api.nvim_get_current_win() end local ratio = tonumber(vim.g.pivi_draft_split_ratio) local vertical = ratio ~= nil and vim.api.nvim_win_get_width(window) > vim.api.nvim_win_get_height(window) * ratio vim.api.nvim_win_call(window, function() vim.cmd(vertical and 'rightbelow vsplit' or 'rightbelow split') end) local opened = vim.api.nvim_get_current_win() vim.api.nvim_win_set_buf(opened, state.draft_buffer) if vertical then vim.api.nvim_win_set_width(opened, math.max(20, math.floor(vim.api.nvim_win_get_width(window) * 0.4))) else -- the draft is where the person composes: it never starves below three lines vim.api.nvim_win_set_height(opened, math.max(3, math.min(12, math.floor(vim.api.nvim_win_get_height(window) * 0.35)))) end vim.api.nvim_set_current_win(opened) return openedendlocal function working(state, busy) if busy == state.active then return end state.active = busy state.started = busy and vim.uv.now() or nil pcall(vim.api.nvim_ui_send, busy and '\027]9;4;3\027\\' or '\027]9;4;0\027\\') if state.timer then state.timer:close() end state.timer = nil if not busy then return end state.timer = vim.uv.new_timer() state.timer:start(1000, 1000, vim.schedule_wrap(function() winbar(state) -- while work runs, the live line in the transcript ticks too if state.busy and state.view then render(state, state.view) end end))endrender = function(state, view) if not vim.api.nvim_buf_is_valid(state.buffer) then return end local fresh = view.items ~= nil local base = fresh and committed(view.items) or state.committed local current = vim.api.nvim_get_current_win() local windows = {} for _, window in ipairs(vim.fn.win_findbuf(state.buffer)) do local record = observe(state, window) windows[window] = { following = record.following, view = vim.deepcopy(record.view) } end local origin = state.committed.ranges[1] if not fresh then view.items = state.view.items end state.committed, state.view = base, view local live = view.docs['pi.live'] local prepend if origin and origin.entry and base.ranges[1] and base.ranges[1].entry ~= origin.entry then for _, range in ipairs(base.ranges) do if range.entry == origin.entry then prepend = range.first - origin.first break end end end state.paused = view.scheduling == 'paused' and (live.run ~= nil or #(live.compactions or {}) > 0) local tail = uncommitted(view.docs, #base.lines, state.paused, base.last_error) state.live = tail.ranges local old_last = vim.api.nvim_buf_line_count(state.buffer) local changed, removed, added local committed_change, tail_change = { nil, 0, 0 }, { nil, 0, 0 } if fresh then -- the committed history only grows: splice it against the old committed -- region, so a new entry does not rewrite the whole transcript local first, gone, grew = splice(state.buffer, 0, #state.committed.lines, base.lines) committed_change = { first, gone or 0, grew or 0 } local tail_first, tail_gone, tail_grew = splice(state.buffer, #base.lines, -1, tail.lines) tail_change = { tail_first, tail_gone or 0, tail_grew or 0 } changed = first or tail_first removed = (gone or 0) + (tail_gone or 0) added = (grew or 0) + (tail_grew or 0) else local tail_first, tail_gone, tail_grew = splice(state.buffer, #base.lines, -1, tail.lines) tail_change = { tail_first, tail_gone or 0, tail_grew or 0 } changed, removed, added = tail_first, tail_gone, tail_grew end if changed then decorate(state, fresh and { base.ranges, tail.ranges } or { tail.ranges }, changed) local last = vim.api.nvim_buf_line_count(state.buffer) local function shifted(row) local function apply(change) local first, gone, grew = change[1], change[2], change[3] if not first then return row end if row >= first + gone then if not (gone == 0 and row == first and row == old_last) then return row + grew - gone end return row elseif row >= first then return math.min(row, first + grew - 1) end return row end if prepend and row >= origin.first then return math.max(1, math.min(row + prepend, last)) end row = apply(committed_change) row = apply(tail_change) return math.max(1, math.min(row, last)) end state.adjusting = true for window, saved in pairs(windows) do if saved.following then follow(state, window) else local old_top = saved.view.topline saved.view.lnum = shifted(saved.view.lnum) saved.view.topline = shifted(saved.view.topline) if old_top > last then saved.view.topline = math.max(1, last - vim.api.nvim_win_get_height(window) + 1) end if window == vim.api.nvim_get_current_win() then vim.fn.winrestview(saved.view) end state.windows[window].view = position(window) end end state.adjusting = false end state.busy = live.run ~= nil local running = vim.iter(live.tools or {}):find(function(tool) return tool.status ~= 'done' end) state.activity = running and running.name or (live.generation and 'thinking' or nil) working(state, (state.busy or #(live.compactions or {}) > 0) and not state.paused) local status = state.stopping and 'stopping' or state.paused and 'suspended' or #(live.compactions or {}) > 0 and 'compacting' or live.generation and live.generation.retry and 'retrying' or state.busy and 'working' or live.runFailure and (live.runFailure.reason == 'aborted' and 'stopped' or 'failed') or live.compactionFailure and 'compaction failed' or 'idle' local model = view.docs['pi.agent'].model model = model and model.provider .. '/' .. model.modelId or 'no model' local cost = 0 for _, usage in pairs(vim.tbl_get(view.docs, 'pi.usage', 'models') or {}) do cost = cost + (vim.tbl_get(usage, 'cost', 'total') or 0) end local raw_cost = cost cost = cost > 0 and ('$%.3f'):format(cost) or nil state.status, state.model, state.cost, state.cost_total = status, model, cost, raw_cost winbar(state)endrange_at = function(state, row) local ranges = state.committed.ranges local low, high = 1, #ranges while low <= high do local middle = math.floor((low + high) / 2) local range = ranges[middle] if not range or not range.first or not range.last then break end if row < range.first then high = middle - 1 elseif row > range.last then low = middle + 1 else return range end end -- the search gives up on a broken range: fall back to a plain walk for _, range in ipairs(ranges) do if range.first and range.last and row >= range.first and row <= range.last then return range end end for _, range in ipairs(state.live) do if range.first and range.last and row >= range.first and row <= range.last then return range end endend-- the fold expression can run while another window is current: fall back to-- the only conversation that is openlocal function context(state) return vim.api.nvim_get_current_buf() == state.draft_buffer and 'draft' or 'entry'endlocal function entry(state) if vim.api.nvim_get_current_buf() ~= state.buffer then return end local range = range_at(state, vim.api.nvim_win_get_cursor(0)[1]) return range and range.entryendlocal function entry_lines(state, id) -- the dialogue comes from the buffer, the agent internals from the hidden log local lines = {} for _, range in ipairs(state.committed.ranges) do if range.entry == id then vim.list_extend(lines, vim.api.nvim_buf_get_lines(state.buffer, range.first - 1, range.last, false)) end end vim.list_extend(lines, state.committed.hidden[id] or {}) return linesendlocal function scratch(kind, lines, filetype) local buffer = vim.api.nvim_create_buf(false, true) vim.api.nvim_buf_set_name(buffer, 'pivi://' .. kind .. '/' .. buffer) vim.api.nvim_buf_set_lines(buffer, 0, -1, false, lines) vim.bo[buffer].filetype = filetype or 'markdown' vim.bo[buffer].bufhidden = 'wipe' vim.bo[buffer].modifiable = false return bufferendlocal function page(kind, lines, filetype) local origin = vim.api.nvim_get_current_buf() local buffer = scratch(kind, lines, filetype) vim.api.nvim_set_current_buf(buffer) vim.keymap.set('n', 'q', function() vim.api.nvim_set_current_buf(origin) end, { buffer = buffer }) return bufferendlocal function float(kind, lines, title) local width = math.max(20, math.min(72, vim.o.columns - 4)) local height = math.max(1, math.min(#lines, vim.o.lines - 6)) local window = vim.api.nvim_open_win(scratch(kind, lines), true, { relative = 'editor', width = width, height = height, row = math.max(0, math.floor((vim.o.lines - height) / 2) - 1), col = math.max(0, math.floor((vim.o.columns - width) / 2)), style = 'minimal', border = 'single', title = title, }) vim.wo[window].wrap = true vim.wo[window].linebreak = true return windowendlocal function help(state, full) local zone = context(state) local lines = { '# Pivi bindings', '' } for _, action in ipairs(ACTIONS) do local applies = (not action.zone or action.zone == zone) and (not action.when or (action.when == 'busy') == state.busy) if full or applies then lines[#lines + 1] = ('%-10s %s'):format(shown(action.key), action.text) end end vim.list_extend(lines, { '', 'gO: outline ]] and [[: next / previous heading' }) vim.list_extend(lines, { '', 'draft: <CR> send (steers while busy) · <C-CR>/<C-J> queue follow-up · Esc in the conversation stops work', }) if zone == 'entry' then lines[#lines + 1] = 'G: follow latest scroll / search / inspect: read without following' end if not full then lines[#lines + 1] = '?: all bindings' end if full then vim.list_extend(lines, { '', '## Commands', '' }) for _, name in ipairs(vim.fn.getcompletion('Pivi ', 'cmdline')) do lines[#lines + 1] = ':Pivi ' .. name end return page('help', lines) end local window = float('keys', lines, 'pivi keys · ' .. zone) local function close() if vim.api.nvim_win_is_valid(window) then vim.api.nvim_win_close(window, true) end end vim.keymap.set('n', '<Esc>', close, { buffer = 0 }) vim.keymap.set('n', 'q', close, { buffer = 0 }) vim.keymap.set('n', '?', function() close() help(state, true) end, { buffer = 0 })endlocal function create(id, dispatch) local names = { buffer = 'pivi://' .. id .. '/conversation', draft_buffer = 'pivi://' .. id .. '/draft' } local existing = states[vim.fn.bufnr(names.buffer)] if existing and vim.api.nvim_buf_is_valid(existing.draft_buffer) then return existing end local state = { attachments = {}, committed = { lines = {}, ranges = {} }, live = {}, windows = {}, busy = false } state.status, state.model = 'starting', 'no model' for field, name in pairs(names) do local buffer = vim.fn.bufnr(name) if buffer == -1 then buffer = vim.api.nvim_create_buf(true, true) vim.api.nvim_buf_set_name(buffer, name) end vim.bo[buffer].buftype = 'nofile' vim.bo[buffer].bufhidden = 'hide' vim.bo[buffer].swapfile = false vim.bo[buffer].filetype = 'markdown' pcall(vim.treesitter.start, buffer, 'markdown') state[field] = buffer vim.api.nvim_create_autocmd('BufWinEnter', { buffer = buffer, callback = function() winbar(state) vim.wo[0][0].wrap = true vim.wo[0][0].linebreak = true vim.wo[0][0].breakindent = true vim.wo[0][0].breakindentopt = 'list:-1' -- the transcript and the draft carry no signs: the column would only eat space vim.wo[0][0].signcolumn = 'no' if field == 'buffer' then vim.wo[0][0].conceallevel = 2 vim.wo[0][0].concealcursor = '' vim.wo[0][0].smoothscroll = true end local window = vim.api.nvim_get_current_win() if state.windows[window] and state.windows[window].following then follow(state, window) else observe(state, window) end end, }) end state.save_draft = require('bugabinga.pivi.draft')(state.draft_buffer, vim.fn.stdpath('state') .. '/pivi/sessions/' .. id) vim.bo[state.buffer].formatlistpat = [[^\s*\d\+[.)]\s\+\|^\s*[-*+]\s\+]] vim.bo[state.buffer].undolevels = -1 vim.bo[state.buffer].modifiable = false states[state.buffer] = state local function navigation() if state.adjusting then return end local changes = vim.v.event.all or {} local resized = (changes.width or 0) ~= 0 or (changes.height or 0) ~= 0 state.adjusting = true for _, window in ipairs(vim.fn.win_findbuf(state.buffer)) do if resized and state.windows[window] and state.windows[window].following then follow(state, window) else observe(state, window) end end state.adjusting = false winbar(state) end local scroll = vim.api.nvim_create_autocmd('WinScrolled', { callback = navigation }) local closed = vim.api.nvim_create_autocmd('WinClosed', { callback = function(event) state.windows[tonumber(event.match)] = nil end, }) vim.api.nvim_create_autocmd('CursorMoved', { buffer = state.buffer, callback = navigation }) vim.api.nvim_create_autocmd('BufWipeout', { buffer = state.buffer, callback = function() working(state, false) vim.api.nvim_del_autocmd(scroll) vim.api.nvim_del_autocmd(closed) states[state.buffer] = nil end, }) for _, action in ipairs(ACTIONS) do local targets = action.zone == 'draft' and { state.draft_buffer } or action.zone == 'entry' and { state.buffer } or { state.buffer, state.draft_buffer } for _, buffer in ipairs(targets) do vim.keymap.set('n', prefix() .. action.key, function() dispatch(state, action.name) end, { buffer = buffer, desc = 'pivi: ' .. action.text, }) end end vim.keymap.set('n', '<CR>', function() dispatch(state, state.busy and 'steer' or 'submit') end, { buffer = state.draft_buffer, desc = 'pivi: send draft (submit, or steer while busy)' }) for _, key in ipairs({ '<C-CR>', '<C-J>' }) do vim.keymap.set('n', key, function() dispatch(state, 'followUp') end, { buffer = state.draft_buffer, desc = 'pivi: queue follow-up', }) end vim.keymap.set('n', '<Esc>', function() if state.busy then dispatch(state, 'abort') end end, { buffer = state.buffer, desc = 'pivi: stop work while busy' }) return stateendvim.on_key(function(key, typed) local state = states[vim.api.nvim_get_current_buf()] if not state or state.adjusting or typed == '' or vim.api.nvim_get_mode().mode ~= 'n' then return end local window = vim.api.nvim_get_current_win() local record = observe(state, window) record.input, record.intent = true, (record.intent or 0) + 1 local intent = record.intent if key == 'G' then vim.schedule(function() if record.intent == intent and vim.api.nvim_win_is_valid(window) and vim.api.nvim_win_get_buf(window) == state.buffer and vim.api.nvim_win_get_cursor(window)[1] == vim.api.nvim_buf_line_count(state.buffer) then follow(state, window) end end) elseif key == 'z' or key == '/' or key == '?' or key == 'v' or key == 'V' or key == vim.keycode('<C-v>') then observe(state, window).following = false vim.schedule(function() if vim.api.nvim_buf_is_valid(state.buffer) then winbar(state) end end) endend, navigation_namespace)return { create = create, prefix = prefix, follow = follow, focus_conversation = focus_conversation, draft_split = draft_split, render = render, winbar = winbar, disconnected = function(state, message) working(state, false) state.ready, state.busy, state.status = false, false, 'disconnected' if message and vim.api.nvim_buf_is_valid(state.buffer) then local offset = vim.api.nvim_buf_line_count(state.buffer) local out = { lines = {}, ranges = {}, offset = offset, turn = {} } block(out, 'worker disconnected', message, nil, 'error', 'text') block(out, '', ':Pivi reconnects. Draft and unsaved buffers remain in this editor.', nil, 'message') local changed = splice(state.buffer, offset, -1, out.lines) vim.list_extend(state.live, out.ranges) if changed then decorate(state, { out.ranges }, changed) end end winbar(state) end, draft = draft, set_draft = set_draft, context = context, entry = entry, entry_lines = entry_lines, page = page, float = float, help = help, fold = fold, foldtext = foldtext,}neovim/lua/bugabinga/sessions.lua
Modified+12 / −0 text lines
auto 'load_session_on_start' { description = 'Load the session for cwd on startup, when nvim starts without arguments', events = 'VimEnter', once = true, command = function() if vim.fn.argc() > 0 then return end local session = encode(vim.uv.cwd()) if file_exists(vim.fs.normalize(sessions .. '/' .. session)) then load_session(session) end end,}neovim/lua/bugabinga/statusline.lua
Modified+9 / −4 text lines
neovim/lua/bugabinga/terminal.lua
Modified+1 / −1 text lines
neovim/lua/bugabinga/treesitter.lua
Modified+91 / −43 text lines
-- TODO: in 0.12 check if this behaviour is builtin on vim.treesitter.start()-- if so, remove my stuff-- checked on 0.12: core only auto-starts treesitter via the bundled ftplugins-- ( $VIMRUNTIME/ftplugin/{lua,markdown,query,help}.lua ). we run with-- 'filetype plugin off', so those never load. this autocmd is required and-- also covers auto-installing missing parsers, which core never does. vim.notify( 'Failed to install treesitter parser: ' .. match, vim.log.levels.ERROR ) vim.notify( 'Failed to install treesitter parser: ' .. lang, vim.log.levels.ERROR ) vim.treesitter.start( data.buf ) vim.schedule( function () if pcall( vim.treesitter.start, data.buf ) then vim.opt_local.foldmethod = 'expr' vim.opt_local.foldexpr = 'v:lua.vim.treesitter.foldexpr()' else -- revision marker lied (e.g. .so wiped out of band): force rebuild once local repair = require 'nvim-treesitter.install'.install( { lang }, { force = true } ) repair:await( function ( _, repaired ) if repaired then vim.schedule( function() pcall( vim.treesitter.start, data.buf ) vim.opt_local.foldmethod = 'expr' vim.opt_local.foldexpr = 'v:lua.vim.treesitter.foldexpr()' end ) end end ) end end )-- add asciidoc parserauto 'install_asciidoc_parser' { description = 'Install asciidoc parser into nvim-treesitter', events = 'User', pattern = 'TSUpdate', command = function () require 'nvim-treesitter.parsers'.asciidoc = { install_info = { url = 'https://github.com/cathaysia/tree-sitter-asciidoc', revision = '5b6ccea9953b939959f447f7bfea699ae6968a99', branch = 'master', -- only needed if different from default branch location = 'tree-sitter-asciidoc', generate = false, generate_from_json = false, queries = 'queries/asciidoc', -- also install queries from given directory }, } end,}-- add d2 parser-- add d2 parser; the .so and queries are installed out of band by puk (puk.parsers.nuon)auto 'install_d2_parser' { description = 'Install d2 parser into nvim-treesitter', events = 'User', pattern = 'TSUpdate', command = function () require 'nvim-treesitter.parsers'.d2 = { install_info = { url = 'https://github.com/ravsii/tree-sitter-d2', revision = 'ffb66ce4c801a1e37ed145ebd5eca1ea8865e00f', branch = 'main', -- only needed if different from default branch generate = true, generate_from_json = true, queries = 'queries', -- also install queries from given directory }, }-- systemd units and podman quadlets are INI-dialect filesvim.treesitter.language.register( 'ini', 'systemd' )-- podman quadlet units get their own semantic filetype, same INI grammarvim.treesitter.language.register( 'ini', 'quadlet' )-- sh files are POSIX-ish, the bash grammar covers themvim.treesitter.language.register( 'bash', 'sh' )-- opentofu files are HCLvim.treesitter.language.register( 'hcl', { 'opentofu', 'opentofu-vars' } )-- nvim calls the gherkin filetype 'cucumber'vim.treesitter.language.register( 'gherkin', 'cucumber' )-- surface treesitter parse errors as ERROR diagnostics in every language;-- refreshed on change/insert-leave/save, so typing stays flicker-freelocal ts_errors = vim.api.nvim_create_namespace 'treesitter-errors'local function collect_errors( node, out ) if node:type() == 'ERROR' or node:missing() then local lnum, col = node:range() out[#out + 1] = { lnum = lnum, col = col, end_lnum = lnum, end_col = col, message = 'syntax error', severity = vim.diagnostic.severity.ERROR, source = 'treesitter' } return end for child in node:iter_children() do collect_errors( child, out ) endendlocal function show_ts_errors( args ) local ok, parser = pcall( vim.treesitter.get_parser, args.buf ) if not ok or not parser then return end local trees = parser:parse() if not trees then return end local tree = trees[1] if not tree then return end local out = {} local root = tree:root() if not root then return end collect_errors( root, out ) vim.diagnostic.set( ts_errors, args.buf, out )endauto 'treesitter_error_diagnostics' { description = 'Report treesitter parse errors as ERROR diagnostics.', events = { 'FileType', 'TextChanged', 'InsertLeave', 'BufWritePost' }, pattern = '*', command = function( args ) vim.schedule( function() show_ts_errors( args ) end )-- this module loads deferred, so the startup file's FileType event has already-- passed: catch up on every loaded buffer oncevim.schedule( function() for _, buf in ipairs( vim.api.nvim_list_bufs() ) do if vim.api.nvim_buf_is_loaded( buf ) then show_ts_errors( { buf = buf } ) end endend )-- runs out of band via puk post-install (headless nvim, editor closed):-- updates nvim-treesitter-managed parsers to the revisions pinned upstream.local function post_install() require 'nvim-treesitter.install'.update():wait()end post_install = post_install,neovim/lua/bugabinga/winbar.lua
Modified+1 / −1 text lines
neovim/lua/std/auto.lua
Modified+1 / −1 text lines
neovim/lua/std/cheatsheet.lua
Deleteddeleted file mode 100644+0 / −51 text lines
local categories = { lsp = 'LSP', fuzzy = 'FZF', files = 'FILE', terminal = 'TERM', editing = 'EDIT', search = 'FIND', session = 'SESS', diff = 'DIFF', operator = 'OP', fun = 'FUN',}local category_patterns = { '^lsp: ', 'lsp', '^fuzzy: ', 'fuzzy', '^files: ', 'files', '^terminal: ', 'terminal', '^editing: ', 'editing', '^search: ', 'search', '^session: ', 'session', '^diff: ', 'diff', '^operator: ', 'operator', '^fun: ', 'fun',}local get_category_icon = function(category) return categories[category] or category:upper()endlocal parse_description = function(desc) if not desc or desc == '' then return 'general', '*no description*' end for i = 1, #category_patterns, 2 do local pattern, category = category_patterns[i], category_patterns[i + 1] if desc:match(pattern) then return category, desc:gsub(pattern, '') end end return 'general', descendreturn { categories = categories, category_patterns = category_patterns, get_category_icon = get_category_icon, parse_description = parse_description,}neovim/lua/std/commentstring.lua
Addednew file mode 100644+83 / −0 text lines
local commentstring = { -- harvested from nvim 0.12 vim.filetype.get_option while ftplugin was still on. -- these are the authoritative builtin values. edit freely. bash = "# %s", c = "// %s", clojure = "; %s", cmake = "# %s", conf = "# %s", cpp = "// %s", css = "/* %s */", dart = "// %s", desktop = "# %s", dockerfile = "# %s", elixir = "# %s", erlang = "% %s", fish = "# %s", gdscript = "# %s", gitcommit = "# %s", gitconfig = "; %s", gleam = "// %s", go = "// %s", graphql = "# %s", hcl = "# %s", html = "<!-- %s -->", java = "// %s", javascript = "// %s", javascriptreact = "// %s", jsonc = "// %s", julia = "# %s", just = "# %s", kotlin = "// %s", lisp = "; %s", lua = "-- %s", make = "# %s", markdown = "<!-- %s -->", nim = "# %s", nu = "# %s", ocaml = "(* %s *)", odin = "// %s", perl = "# %s", php = "/* %s */", proto = "// %s", python = "# %s", qml = "// %s", r = "# %s", roc = "# %s", ruby = "# %s", rust = "// %s", scala = "// %s", scheme = "; %s", scss = "// %s", sh = "# %s", sql = "-- %s", swift = "// %s", systemd = "; %s", terraform = "# %s", tex = "% %s", tmux = "# %s", toml = "# %s", typescript = "// %s", typescriptreact = "// %s", v = "// %s", vim = '"%s', xml = "<!-- %s -->", yaml = "# %s", zig = "// %s", -- nvim had no builtin commentstring for these. added by hand. haskell = "-- %s", ini = "; %s", bibtex = "% %s", -- your custom filetypes ( from options/filetypes.lua ). VERIFY these. d2 = "# %s", vfp = "* %s", -- Visual FoxPro line comment gotmpl = "{{/* %s */}}", opentofu = "# %s", quadlet = "# %s", shtml = "<!-- %s -->", superhtml = "<!-- %s -->",}return commentstringneovim/lua/std/const.lua
Modified+3 / −1 text lines
neovim/lua/std/dbg.lua.bak
Deleteddeleted file mode 100644+0 / −189 text lines
local user_command = require 'std.user_command'local icon = require 'std.icon'local DBG_FILE = vim.fn.stdpath 'state' .. '/bugabinga_config_debug.jsonl'---Debug kinds and their mapped highlight groups and icons.---@type table<string,[string, string]>local DBG_KINDS = { --TODO DEBUG = {}, TRACE = {}, ERROR = {},}---@alias dbg_kind---| 'DEBUG' normal debug event -> use this, when logging debug information---| 'TRACE' function trace event -> use this, when tracing function call flow---| 'ERROR' error event -> use this, when logging unexpected events---Get context information from `debug.traceback()` and other `debug` functions.---Wwhen getting the stacktrace, we need to account for the function call graph inside this `dbg` module.---Either its: `callsite -> metatable -> print_debug -> print_debug_kind -> get_context`.---Or: `callsite -> print_debug_kind -> get_context`.---In both cases we are only interested in callsite to determine file name, the function name and line number.------@return string filename The filename, the calling function resides in.---@return string function_name The name of the function, where `dbg` was called in.---@return integer line_number Line number the calling functions is invoking the `dbg` function at.local function get_context() --TODO local filename = nil local function_name = nil local line_number = nil return filename, function_name, line_numberend--- Encodes debug event to JSON--- @param event table<string, table, string, table, string, string, integer> debug event to log--- @return string json JSON-encoded debug eventlocal function encode( event ) return vim.json.encode( event, { escape_slash = true, } )end--- Decodes debug event from JSON--- @param line string JSON-encoded debug event--- @return table<string, table, string, table, string, string, integer> event debug event to loglocal function decode( line ) return vim.json.decode( line, { luanil = { object = true, array = true, }, } )end--- Writes debug events to the debug file, one per line.------ @see encode--- @param event table<string, table, string, table, string, string, integer> debug event to loglocal function write_to_debug_file( event ) local file, errmsg = io.open( DBG_FILE, 'a+' ) if not file then error( 'Unable to open debug log file `' .. DBG_FILE .. '`: ' .. errmsg ) end local json_line = encode( event ) file:write( json_line ) file:flush() file:close()end---Replaces expressions inside the given `format`, by indexing into `user_data`.------Resolve `format`, by replacing `{<expr>}` inside format string.---`<expr>` is used to index into `user_data`.---e.g.: `user_data = {a = 1, b = 2, c = 3}`---To get `b`: the format expression would be `{b}`.---`{b}` would be replaced by `2` in format string.------e.g.: `user_data = {{a=1},{b=2},{c=3}}`---To index into nested structures, use numbers: `{2.b}`.---`{2.b}` would be replaced by `2` in format string.---Indexing is 1-based, as per usual in lua.---Values are converted by `vim.inspect` to strings.------@see vim.inspect------@param format string Message with optional "{}"-style expressions inside---@param data table Arbitrary data, that can be indexed into, to pick values for the `format` string---@return string formatted_message Message with format expressions resolvedlocal function format_message( format, data ) local formatted_message --TODO return formatted_messageendif vim.g.bugabinga_debug_mode == nil then vim.g.bugabinga_debug_mode = falseendlocal function is_debug_mode() return vim.g.bugabinga_debug_modeend---Log debug message of particular kind.---@param kind dbg_kind kind of event---@param message string message format string---@param ... any arbitrary user data, that can be referenced in message formatlocal function print_debug_kind( kind, message, ... ) if not is_debug_mode() then return end local now = os.date '!*t' local user_data = { ... } local filename, function_name, line_number = get_context() write_to_debug_file { kind = kind, date = now, format = message, data = user_data, filename = filename, fn = function_name, line = line_number, }end---Log a debug event.---@param message string message format string---@param ... any arbitrary user data, that can be referenced in message formatlocal function print_debug( message, ... ) if not is_debug_mode() then return end print_debug_kind( 'DEBUG', message, ... )endlocal function toggle_debug_mode() vim.g.bugabinga_debug_mode = not vim.g.bugabinga_debug_mode vim.notify( 'Toggled debug mode to ' .. tostring( is_debug_mode() ) )end--- Opens the debug file in a special buffer, that is not modifiable.--- It renders the debug events in a table with special functions:--- - filter by type--- - jump to location--- - colors and icons for different kinds--- Filters are a label, e.g. "Filter by kind: " plus a special region after it on one line in the buffer above the table.--- Typing in that region activates the filtering in the table.------ Icons are shown as prefix to kind values in their cells: <icon> <KIND>.--- The table rows are highlighted according to kinds in `DBG_KINDS`.--- Note: table row can be multiline because of formatted messages. Highlighting needs to account for that.------ Pressing enter while the cursor is on a table row, jumps to this events location.------ Debug events are read and decoded from `DBG_FILE` and converted to a table of:--- Kind, Date, Message, Location------ Kind -> debug event kind + icon--- Date -> human readable datetime in hosts timezone--- Message -> formatted message from format string and user data--- Locataion -> combined file name, function name and line numberlocal function open_special_debug_buffer() --TODOend--- Opens the file `DBG_FILE` in a normal neovim bufferlocal function open_raw_debug_file() --TODOenduser_command.Debug 'Toggle global vim config debug mode.' ( toggle_debug_mode )user_command.DebugOpen 'Open special buffer with debug events' ( open_special_debug_buffer )user_command.DebugOpenRaw 'Opens the JSON debug file in normal buffer' ( open_raw_debug_file )return setmetatable( { kind = print_debug_kind, toggle = toggle_debug_mode, get = is_debug_mode, }, { --TODO: refactor usages of this function in other code to new name __call = print_debug, __newindex = function ( ... ) error( 'Assignments are not supported for std.dbg.\n' .. vim.inspect( ... ), 2 ) end, } )neovim/lua/std/dbg/encode.lua
Deleteddeleted file mode 100644+0 / −25 text lines
---Encodes a debug event to JSON.---@param event table debug event---@return string jsonlocal function encode( event ) return vim.json.encode( event, { escape_slash = true, } )end---Decodes a JSON line into a debug event.---@param line string JSON string---@return table eventlocal function decode( line ) return vim.json.decode( line, { luanil = { object = true, array = true, }, } )endreturn { encode = encode, decode = decode,}neovim/lua/std/dbg/file.lua
Deleteddeleted file mode 100644+0 / −125 text lines
local encode = require 'std.dbg.encode'local decode = require 'std.dbg.encode'local DBG_FILE = vim.fn.stdpath 'state' .. '/bugabinga_config_debug.jsonl'---Returns the path to the debug log file.---@return stringlocal function get_path() return vim.g.bugabinga_debug_file_override or DBG_FILEend---Returns the filename, function name, and line number of the caller.---Skips all frames inside std/dbg/* modules.---@return string filename---@return string function_name---@return integer line_numberlocal function get_context() local level = 2 while true do local info = debug.getinfo(level, 'Sln') if not info then break end local src = info.short_src or info.source if src and not src:match 'std/dbg' and not src:match '@std/dbg' then return src, info.name or '', info.currentline or 0 end level = level + 1 end return 'unknown', '', 0end---Appends a debug event as a JSON line to the debug file.---@param event table debug event---@param path string? override pathlocal function write(event, path) local file_path = path or DBG_FILE local dir = vim.fs.dirname(file_path) if dir and dir ~= '' then vim.fn.mkdir(dir, 'p') end local file, errmsg = io.open(file_path, 'a') if not file then error('Unable to open debug log file `' .. file_path .. '`: ' .. tostring(errmsg)) end local json_line = encode.encode(event) file:write(json_line .. '\n') file:flush() file:close()end---Closes the open file descriptor. No-op with io.open.local function close_fd()end---Clears the debug log file by truncating it.local function clear_log() local dir = vim.fs.dirname(DBG_FILE) if dir and dir ~= '' then vim.fn.mkdir(dir, 'p') end local file, errmsg = io.open(DBG_FILE, 'w') if file then file:close() endend---Reads all debug events from a JSONL file.---@param path string? override path (defaults to DBG_FILE)---@return table[] list of decoded eventslocal function read_all(path) local file_path = path or DBG_FILE local file = io.open(file_path, 'r') if not file then return {} end local events = {} for line in file:lines() do if line and line ~= '' then local ok, event = pcall(decode.decode, line) if ok and event then table.insert(events, event) end end end file:close() return eventsend---Reads only new events from the JSONL file, skipping the first `last_count` lines.---Use for incremental updates when tailing a growing file.---@param last_count number skip this many lines before reading new ones---@param path string? override path (defaults to DBG_FILE)---@return table[] new_events list of newly decoded events---@return number new_total total count of events in file after readinglocal function read_new(last_count, path) local file_path = path or DBG_FILE local file = io.open(file_path, 'r') if not file then return {}, 0 end local new_events = {} local current_count = 0 for line in file:lines() do if line and line ~= '' then current_count = current_count + 1 if current_count > last_count then local ok, event = pcall(decode.decode, line) if ok and event then table.insert(new_events, event) end end end end file:close() return new_events, current_countendreturn { get_path = get_path, get_context = get_context, write = write, read_all = read_all, read_new = read_new, close_fd = close_fd, clear_log = clear_log,}neovim/lua/std/dbg/format.lua
Deleteddeleted file mode 100644+0 / −275 text lines
---Debug event format module.---Resolves {0} and {N} and {N.key...} placeholders against wrapped varargs.------## Model------All varargs are wrapped into `wrapped = {...}`. Every placeholder indexes into this.------### Syntax: {0}, {N}, or {N.key.sub...}--- {0} -> vim.inspect(all data)--- {N} -> wrapped[N]--- {N.key} -> wrapped[N].key--- {N.1.key} -> wrapped[N][1].key (numeric into string)--- {N.["key"]} -> wrapped[N]["key"] (bracket = always string key)--- {N.["a.b"]} -> wrapped[N]["a.b"] (key containing dots)--- Mixed bare and bracket: {N.a.["x.y"].z} works as expected------### Grammar (key segments after {N.})--- key_segment := bare_key | '[' quoted_string ']'--- bare_key := [^.[]+ (alphanumeric, underscores, etc.)--- quoted_string := '"' [^"]* '"' | "'" [^']* "'"--- Separator '.' between segments. No whitespace between segments.------### Examples--- dbg('{0}', {a=1, b='bee'}) -> '{ a = 1, b = "bee" }'--- dbg('{1}', 'hello') -> 'hello'--- dbg('{2}', 'a', 'b') -> 'b'--- dbg('{1.name}', {name='hi'}) -> 'hi'--- dbg('{1.1}', {{'nested'}}) -> 'nested'--- dbg('{1.1.name}', {{name='nested'}}) -> 'nested'--- dbg('{2.1.jan.name}', {'x', {jan={name='jan'}}}) -> 'jan'--- dbg('{2.1.jan.age}', {'x', {age=39, {jan={name='jan',age=11}}}}) -> '11'--- dbg('{1.["a.b"]}', { {['a.b'] = 'dots'} }) -> 'dots'--- dbg('{1.["1"]}', { {['1'] = 'str', [1] = 'int'} }) -> 'str' (string key wins)--- dbg('{1.["function"]}', { {['function'] = 'kw'} }) -> 'kw'--- dbg('{1.["hello world"]}', { {['hello world'] = 'hw'} }) -> 'hw'--- dbg('{1.[""]}', { {[''] = 'empty'} }) -> 'empty'------### Rules--- - {0} returns vim.inspect of all data; cannot be followed by keys--- - First key must be numeric (0 or the index into wrapped)--- - Subsequent bare keys are strings unless they parse as integers--- - Bracket keys (["key"]) are ALWAYS string keys — never parsed as numbers--- - This means {1.["2"]} accesses string key "2", while {1.2} accesses integer key 2--- - Indices out of range produce an error--- - Any nil result (missing index or missing chained key) produces an error--- - Table values are rendered via vim.inspect------### Error Suggestions--- - Index off by 1-3: suggests correct index (e.g., {3} with 2 items suggests {2})--- - Wrong key name: suggests closest key using Levenshtein distance (threshold 2)------@param format string format string with placeholders---@param data table varargs list packed as {...}---@return string formatted message---@see vim.inspect---Parses a key expression into segments.---Grammar:--- expression := key_segment ('.' key_segment)*--- key_segment := bare_key | '[' quoted_string ']'--- bare_key := [^.[]+--- quoted_string := '"' [^"]* '"' | "'" [^']* "'"---Returns array of { key = string|number, is_string = boolean }.---Bracket keys are always strings; bare keys are strings unless numeric.---@param inner string---@return tablelocal function parse_keys(inner) local keys = {} local pos = 1 while pos <= #inner do if inner:sub(pos, pos) == '.' then pos = pos + 1 end if pos > #inner then break end local c = inner:sub(pos, pos) if c == '[' then pos = pos + 1 if pos > #inner then error('parse error: unclosed bracket in {' .. inner .. '}') end local quote = inner:sub(pos, pos) if quote ~= '"' and quote ~= "'" then error('parse error: expected quote in {' .. inner .. '}') end pos = pos + 1 local key_start = pos local quote_end = inner:find(quote, pos, true) if not quote_end then error('parse error: unclosed bracket in {' .. inner .. '}') end local key = inner:sub(key_start, quote_end - 1) pos = quote_end + 1 if pos > #inner or inner:sub(pos, pos) ~= ']' then error('parse error: expected ] in {' .. inner .. '}') end pos = pos + 1 keys[#keys + 1] = { key = key, is_string = true } else local key_start = pos while pos <= #inner and inner:sub(pos, pos) ~= '.' and inner:sub(pos, pos) ~= '[' do pos = pos + 1 end local key = inner:sub(key_start, pos - 1) if key == '' then error('parse error: empty key in {' .. inner .. '}') end keys[#keys + 1] = { key = tonumber(key) or key, is_string = false } end end return keysend---Computes Levenshtein edit distance between two strings.---Uses Wagner-Fischer dynamic programming algorithm.---@param a string first string---@param b string second string---@return number edit distance (0 = identical)local function levenshtein(a, b) local m, n = #a, #b if m == 0 then return n end if n == 0 then return m end local prev = {} local curr = {} for j = 0, n do prev[j] = j end for i = 1, m do curr[0] = i for j = 1, n do local cost = a:sub(i, i) == b:sub(j, j) and 0 or 1 curr[j] = math.min(prev[j] + 1, curr[j - 1] + 1, prev[j - 1] + cost) end prev, curr = curr, prev end return prev[n]end---Suggests a similar key from a table based on Levenshtein distance.---Only suggests keys within threshold distance (<= 2).---@param tbl table the table to search---@param wrong_key string the key that was not found---@return string? suggested key or nil if none close enoughlocal function suggest_key(tbl, wrong_key) if type(wrong_key) ~= 'string' then return nil end local best_key, best_dist = nil, math.huge for k in pairs(tbl) do if type(k) == 'string' then local d = levenshtein(k, wrong_key) if d < best_dist then best_key, best_dist = k, d end end end if best_dist <= 2 then return best_key end return nilendlocal function format_message(format, data) vim.validate('format', format, 'string') vim.validate('data', data, 'table') local data_len = #data local result = {} local pos = 1 while pos <= #format do local startbrace, endbrace = format:find('%b{}', pos) if not startbrace then table.insert(result, format:sub(pos)) break end if startbrace > pos then table.insert(result, format:sub(pos, startbrace - 1)) end local match = format:sub(startbrace, endbrace) local inner = match:match('^{%s*(.-)%s*}$') local replacement if not inner or inner == '' then error('Empty {} is not allowed. Use {N} or {N.key...} syntax.') else local keys = parse_keys(inner) local first_key_entry = keys[1] local first_key = first_key_entry.key if first_key_entry.is_string or type(first_key) ~= 'number' then error( 'First key in {' .. inner .. '} must be a numeric index (like {1} or {1.key}). ' .. 'Named keys like {' .. inner .. '} are not supported. Use {1.' .. inner .. '} instead.' ) end local idx = first_key if idx == 0 then if #keys > 1 then error('{0} cannot be followed by keys like {0.key}. Use {0} alone or {N.key} instead.') end if vim.tbl_count(data) == 0 then error('{0} cannot be used on empty data.') end replacement = vim.inspect(data) elseif idx > data_len or idx < 1 then local suggestion = nil if idx > data_len and idx <= data_len + 3 then suggestion = ' (did you mean {' .. (idx - 1) .. '}?)' end error( 'Index ' .. idx .. ' is out of range (have ' .. data_len .. ' items)' .. (suggestion or '') ) else local current = data[idx] local failed_key = nil local parent_table = nil for i = 2, #keys do if current == nil then break end local k = keys[i] local access_key = k.is_string and k.key or tonumber(k.key) or k.key if type(current) == 'table' then local key_exists = false for ek in pairs(current) do if ek == access_key then key_exists = true break end end if not key_exists then failed_key = access_key parent_table = current end end current = current[access_key] end if current == nil then local msg = 'Key not found while resolving {' .. inner .. '}' if failed_key and parent_table then local suggestion = suggest_key(parent_table, failed_key) if suggestion then msg = msg .. " (did you mean '" .. suggestion .. "'?)" end end error(msg) end replacement = type(current) == 'table' and vim.inspect(current) or tostring(current) end end table.insert(result, replacement) pos = endbrace + 1 end return table.concat(result)endreturn setmetatable( { levenshtein = levenshtein }, { __call = function(_, ...) return format_message(...) end })neovim/lua/std/dbg/init.lua
Modified+71 / −73 text lines
---Debug logging facade.---Provides dbg(), dbg.kind(), dbg.toggle(), dbg.get() and user commands.---All debug output goes to the JSONL file at stdpath('state')/bugabinga_config_debug.jsonl.local file = require 'std.dbg.file'local format = require 'std.dbg.format'--- Debug logging facade. Minimal by design: everything goes to one JSONL file.--- File: stdpath('state')/bugabinga_config_debug.jsonl------ API:--- dbg( message, ... ) -- DEBUG level, printf-style ( string.format )--- dbg.kind( kind, message, ... )--- dbg.print( message, ... ) -- DEBUG level, explicit method form--- dbg.get() -- is debug mode on--- dbg.toggle()------ Commands: :DbgModeToggle :DbgOpenFile :DbgClearlocal viewer = require 'std.dbg.viewer'---Toggles debug mode on/off and prints a notification.local function toggle_debug_mode() vim.g.bugabinga_debug_mode = not vim.g.bugabinga_debug_mode vim.notify( 'Toggled debug mode to ' .. tostring( is_debug_mode() ) )-- filename, function name and line of the caller, skipping this module's frames.local function context() local level = 2 while true do local info = debug.getinfo( level, 'Sln' ) if not info then return 'unknown', '', 0 end local source = info.short_src or info.source if source and not source:match 'std/dbg' then return source, info.name or '', info.currentline or 0 end level = level + 1 end---Logs a debug event of the specified kind.---Writes to the debug JSONL file if debug mode is enabled.---@param kind_name string DEBUG, TRACE, or ERROR---@param message string format string with {} or {N} placeholders---@param ... any values to substitute into the format stringlocal function print_debug_kind( kind_name, message, ... ) if not is_debug_mode() then return end local now = os.time() local user_data = { ... } local message = format( message, user_data ) local filename, function_name, line_number = file.get_context() file.write( event, file.get_path() )end---Logs a DEBUG event.---@param _ any ignored (table receiver when called via metatable)---@param message string format string with {} or {N} placeholders---@param ... any values to substitutelocal function print_debug( _, message, ... ) if not is_debug_mode() then return print_debug_kind( 'DEBUG', message, ... )---Opens the raw JSONL debug file in a normal buffer.local function open_raw_debug_file() vim.cmd.edit( file.get_path() )enduser_command.DbgModeToggle 'Toggle global vim config debug mode.' ( toggle )user_command.DbgOpenFile 'Open the JSONL debug file in a buffer' ( function () vim.cmd.edit( path() )end )user_command.DbgClear 'Clear the JSONL debug file' ( function () local handle = io.open( path(), 'w' ) if handle then handle:close() endend )user_command.DbgModeToggle 'Toggle global vim config debug mode.' ( toggle_debug_mode )user_command.DbgViewToggle 'Open or close the debug event viewer' ( toggle_debug_viewer )user_command.DbgOpenFile 'Opens the JSON debug file in normal buffer' ( open_raw_debug_file )user_command.DbgClear 'Clears the JSON debug file' ( file.clear_log )return setmetatable( { kind = print_debug_kind, toggle = toggle_debug_mode, get = is_debug_mode, }, { __call = print_debug, __newindex = function ( ... ) error( 'Assignments are not supported for std.dbg.\n' .. vim.inspect( ... ), 2 ) end, })return setmetatable( { kind = log, print = function ( message, ... ) log( 'DEBUG', message, ... ) end, toggle = toggle, get = enabled,}, { __call = function ( _, message, ... ) log( 'DEBUG', message, ... ) end, __newindex = function ( ... ) error( 'Assignments are not supported for std.dbg.\n' .. vim.inspect( ... ), 2 ) end,} )neovim/lua/std/dbg/init.lua.bak
Deleteddeleted file mode 100644+0 / −69 text lines
local file = require 'std.dbg.file'local kinds = require 'std.dbg.kinds'local format = require 'std.dbg.format'local user_command = require 'std.user_command'if vim.g.bugabinga_debug_mode == nil then vim.g.bugabinga_debug_mode = falseendlocal function is_debug_mode() return vim.g.bugabinga_debug_modeendlocal function toggle_debug_mode() vim.g.bugabinga_debug_mode = not vim.g.bugabinga_debug_mode vim.notify( 'Toggled debug mode to ' .. tostring( is_debug_mode() ) )endlocal function print_debug_kind( kind_name, message, ... ) if not is_debug_mode() then return end local now = os.time() local user_data = { ... } local filename, function_name, line_number = file.get_context() local event = { kind = kind_name, date = now, format = message, data = user_data, filename = filename, fn = function_name, line = line_number, } file.write( event )endlocal function print_debug( message, ... ) if not is_debug_mode() then return end print_debug_kind( 'DEBUG', message, ... )endlocal function open_special_debug_buffer() vim.notify( 'Debug viewer not yet implemented (Stage 2)', vim.log.levels.WARN )endlocal function open_raw_debug_file() vim.cmd.edit( file.get_path() )enduser_command.Debug 'Toggle global vim config debug mode.' ( toggle_debug_mode )user_command.DebugOpen 'Open special buffer with debug events' ( open_special_debug_buffer )user_command.DebugOpenRaw 'Opens the JSON debug file in normal buffer' ( open_raw_debug_file )return setmetatable( { kind = print_debug_kind, toggle = toggle_debug_mode, get = is_debug_mode, }, { __call = print_debug, __newindex = function ( ... ) error( 'Assignments are not supported for std.dbg.\n' .. vim.inspect( ... ), 2 ) end, })neovim/lua/std/dbg/kinds.lua
Deleteddeleted file mode 100644+0 / −48 text lines
local icon = require 'std.icon'---@class DbgKind---@field icon string nerd font icon---@field hl_group string neovim highlight group---@type table<string, DbgKind>local DBG_KINDS = { DEBUG = { icon = icon.search, hl_group = 'DiagnosticInfo' }, TRACE = { icon = icon.event, hl_group = 'DiagnosticHint' }, ERROR = { icon = icon.error, hl_group = 'DiagnosticError' },}---Returns the kind details for a given kind name.---@param kind_name string must be one of DEBUG, TRACE, ERROR---@return DbgKindlocal function get(kind_name) vim.validate('kind_name', kind_name, 'string') local kind = DBG_KINDS[kind_name] if not kind then local available = vim.tbl_keys(DBG_KINDS) error('Unknown debug kind: ' .. kind_name .. '. Available: ' .. vim.inspect(available)) end return kindend---Returns a list of all available kind names.---@return string[]local function list() return vim.tbl_keys(DBG_KINDS)end---Formats a kind name into a display string with icon and name.---@param kind_name string---@return stringlocal function format(kind_name) local kind = get(kind_name) return kind.icon .. ' ' .. kind_nameendreturn { DEBUG = DBG_KINDS.DEBUG, TRACE = DBG_KINDS.TRACE, ERROR = DBG_KINDS.ERROR, get = get, list = list, format = format,}No final newlineneovim/lua/std/dbg/viewer.lua
Deleteddeleted file mode 100644+0 / −680 text lines
---Debug event viewer — special buffer UI for browsing debug events.------## Public API------| Function | Description |---| ----------------------- | ------------------------------------------------ |---| `open()` | Open viewer (reuse existing window if open) |---| `close()` | Close viewer and delete its buffer + watcher |---| `refresh()` | Re-read all events from disk and re-render |---| `is_open()` | Returns `true` if viewer window is valid |---| `jump_to_source(win_id)`| Jump to the source file:line of event at cursor |---| `clear_filters()` | Remove all active filters |---| `filter_by_kind()` | Prompt for kind filter (fk) |---| `filter_by_message()` | Prompt for message filter (fm) |---| `filter_by_location()` | Prompt for filename filter (fl) |---| `filter_by_all()` | Prompt for combined filter (ff) |---| `get_winbar()` | Returns winbar text (used by format string) |------## Keymaps (in viewer buffer)------| Key | Action |---| ----- | -------------------------- |---| `q` | Close viewer |---| `<Esc>` | Close viewer |---| `r` | Refresh events from disk |---| `<CR>` | Jump to source location |---| `ff` | Filter combined (all) |---| `fc` | Clear filters + notify |---| `fk` | Filter by kind |---| `fm` | Filter by message |---| `fl` | Filter by location |------## Layout------- Opens as a **bottom split** (`botright split`), respecting `splitbelow`---- Height is **golden ratio** (~61.8% of screen height)---- Each event renders as a **4-line block**: header, message, location, blank---- Events sorted **newest-first** (by date descending)---- Auto-refreshes via `vim.uv.fs_event` when debug file changes------## Filtering------- Filters use `vim.fn.matchfuzzy` for fuzzy matching---- Multiple filters combine with **AND** logic---- `ff` prompts for combined filter across kind + message + filename---- `fc` clears all filters and shows `vim.notify`---- Active filters displayed in **winbar**---- Event count shown as `filtered/total` when filters active------## Events Structure------Events loaded from `std.dbg.file` (JSONL). Each event:---```lua---{--- kind = "DEBUG" | "TRACE" | "ERROR",--- date = os.time() integer,--- message = formatted string,--- data = { ... }, -- raw user data--- filename = "@source.lua" or "[string ...]",--- fn = "function_name",--- line = 123,---}---```------## Highlights------| Highlight Group | Links To | Applied To |---| ------------------------ | ---------------- | ------------------- |---| `DbgViewerKindIcon` | `Title` | Kind icon in header |---| `DbgViewerKind` | `Comment` | Kind name in header |---| `DbgViewerTime` | `Normal` | Timestamp in header |---| `DbgViewerMessage` | `Comment` | Message lines |---| `DbgViewerLocation` | `Comment` | Location lines |---| (kind-specific) | `DiagnosticInfo/Hint/Error` | Icon backgrounds |------## Internal Architecture------- `H.state` — module-local state:--- ```lua--- {--- buf_id = number,--- win_id = number,--- events = event[],--- filtered_indices = number[] | nil,--- filters = { all = "", kind = "", message = "", filename = "" },--- line_events = table, -- line_idx (1-based) -> event_idx (1-based)--- filtered_count = number, -- how many events currently displayed--- event_count = number, -- total events read from file--- watcher = uv_fs_event | nil,--- highlights = highlight[], -- all active highlights for re-apply on prepend--- }--- ```---- `H.ns_id` — namespace for buffer highlights---- `H.BUF_NAME_PREFIX` — buffer name pattern: `dbgviewer://<buf_id>/debug-events`---- `H.FT` — filetype set on viewer buffer: `DbgViewer`local file = require 'std.dbg.file'local kinds = require 'std.dbg.kinds'local timeago = require 'std.timeago'local map = require 'std.map'local start_watcherlocal on_file_changelocal H = { state = nil,}H.ns_id = vim.api.nvim_create_namespace 'std.dbg.viewer'H.BUF_NAME_PREFIX = 'dbgviewer://'H.FT = 'DbgViewer'local NS_HL = { kind_icon = 'DbgViewerKindIcon', kind_name = 'DbgViewerKind', time = 'DbgViewerTime', message = 'DbgViewerMessage', location = 'DbgViewerLocation',}local KIND_TO_HL = { DEBUG = 'DiagnosticInfo', TRACE = 'DiagnosticHint', ERROR = 'DiagnosticError',}local WINBAR_FORMAT = '%%#%s#%%{v:lua.require("std.dbg.viewer").get_winbar()}%%#Normal#'local FILTER_WINBAR_SPECS = { { key = 'all', prefix = ' all:"', suffix = '"' }, { key = 'kind', prefix = ' kind:', suffix = '' }, { key = 'message', prefix = ' msg:"', suffix = '"' }, { key = 'filename',prefix = ' file:', suffix = '' },}local FILTER_SPECS = { { key = 'all', extract = function(ev) return ev.kind .. ' ' .. ev.message .. ' ' .. sanitize_src(ev.filename) end, }, { key = 'kind', extract = function(ev) return ev.kind end, }, { key = 'message', extract = function(ev) return ev.message end, }, { key = 'filename', extract = function(ev) return sanitize_src(ev.filename) end, },}local function get_kind_hl_group(kind_name) return KIND_TO_HL[kind_name] or 'DiagnosticInfo'endlocal function sanitize_src(src) if not src or src == '' then return 'unknown' end return (src:gsub('^@', ''):gsub('^%[string .+%]$', 'unknown'))endlocal function make_winbar() return string.format(WINBAR_FORMAT, NS_HL.kind_icon)endlocal function get_winbar() if not H.state or not H.state.win_id then return '' end local s = H.state local parts = {} local has_filter = false for _, spec in ipairs(FILTER_WINBAR_SPECS) do local val = s.filters[spec.key] if val and val ~= '' then parts[#parts + 1] = spec.prefix .. val .. spec.suffix has_filter = true end end local filter_str = has_filter and table.concat(parts, '') or '' local count = s.filtered_count or 0 local total = s.events and #s.events or 0 local count_str = count == total and tostring(total) or count .. '/' .. total return ' ' .. kinds.get('DEBUG').icon .. ' Debug [' .. count_str .. ' events]' .. filter_strendlocal function format_event_for_display(event) local kind_info = kinds.get(event.kind) local icon = kind_info.icon local rel_time = timeago.format(event.date) local src = sanitize_src(event.filename) local loc = src .. ':' .. (event.line or '?') local msg = event.message or '(no message)' return { icon = icon, kind_name = event.kind, time = rel_time, message = msg, location = loc, }endlocal function build_lines_and_hl(events) local lines = {} local line_events = {} local highlights = {} if #events == 0 then lines[1] = ' (no debug events)' line_events[1] = nil return lines, line_events, highlights end for ei, event in ipairs(events) do local d = format_event_for_display(event) local header = string.format(' %s %s · %s', d.icon, d.kind_name, d.time) local msg_line = ' ' .. d.message local loc_line = ' ' .. d.location local header_line_idx = #lines + 1 lines[#lines + 1] = header line_events[header_line_idx] = ei highlights[#highlights + 1] = { line = header_line_idx, kind = event.kind, icon_start = 1, icon_end = #d.icon + 1, kind_name_start = #d.icon + 2, kind_name_end = #d.icon + 2 + #d.kind_name, time_start = #header - #d.time, time_end = #header, } local msg_line_idx = #lines + 1 lines[#lines + 1] = msg_line line_events[msg_line_idx] = ei local loc_line_idx = #lines + 1 lines[#lines + 1] = loc_line line_events[loc_line_idx] = ei highlights[#highlights + 1] = { line = loc_line_idx, location = true, } local blank_idx = #lines + 1 lines[#lines + 1] = '' line_events[blank_idx] = nil end return lines, line_events, highlightsendlocal function apply_highlights(buf_id, highlights, events) vim.api.nvim_buf_clear_highlight(buf_id, H.ns_id, 0, -1) for _, hl in ipairs(highlights) do local lnum = hl.line - 1 if hl.location then vim.api.nvim_buf_add_highlight(buf_id, H.ns_id, NS_HL.location, lnum, 0, -1) elseif hl.kind then 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) 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) vim.api.nvim_buf_add_highlight(buf_id, H.ns_id, NS_HL.time, lnum, hl.time_start - 1, hl.time_end - 1) else vim.api.nvim_buf_add_highlight(buf_id, H.ns_id, NS_HL.message, lnum, 0, -1) end endendlocal function create_buf() local buf_id = vim.api.nvim_create_buf(false, true) vim.api.nvim_buf_set_name(buf_id, H.BUF_NAME_PREFIX .. buf_id .. '/debug-events') vim.bo[buf_id].buftype = 'nofile' vim.bo[buf_id].bufhidden = 'wipe' vim.bo[buf_id].buflisted = false vim.bo[buf_id].modifiable = false vim.bo[buf_id].swapfile = false vim.bo[buf_id].filetype = H.FT vim.bo[buf_id].modeline = false return buf_idendlocal function open_win(buf_id) local height = math.max(5, math.floor(0.618 * vim.o.lines)) vim.cmd('botright split') local win_id = vim.api.nvim_get_current_win() vim.api.nvim_win_set_buf(win_id, buf_id) vim.wo[win_id].wrap = true vim.wo[win_id].scrolloff = 0 vim.wo[win_id].cursorline = true vim.wo[win_id].winbar = make_winbar() vim.api.nvim_win_set_height(win_id, height) return win_idendlocal function event_passes_filters(event, filters) for _, spec in ipairs(FILTER_SPECS) do local fval = filters[spec.key] if fval and fval ~= '' then local ftext = spec.extract(event) if #vim.fn.matchfuzzy({ ftext }, fval) == 0 then return false end end end return trueendlocal function compute_filtered_indices(events, filters) if not filters then return nil end local has_any_filter = false for _, spec in ipairs(FILTER_SPECS) do local fval = filters[spec.key] if fval and fval ~= '' then has_any_filter = true break end end if not has_any_filter then return nil end local result = {} for i, ev in ipairs(events) do if event_passes_filters(ev, filters) then result[#result + 1] = i end end return resultendlocal function render() if not H.state or not H.state.buf_id then return end local events = H.state.events or {} local filtered_indices = H.state.filtered_indices local display_events = filtered_indices and (function() local r = {} for _, idx in ipairs(filtered_indices) do r[#r+1] = events[idx] end return r end)() or events local lines, line_events, highlights = build_lines_and_hl(display_events) H.state.line_events = line_events H.state.highlights = highlights H.state.filtered_count = #display_events local was_modifiable = vim.bo[H.state.buf_id].modifiable vim.bo[H.state.buf_id].modifiable = true vim.api.nvim_buf_set_lines(H.state.buf_id, 0, -1, false, lines) vim.bo[H.state.buf_id].modifiable = was_modifiable apply_highlights(H.state.buf_id, highlights, events) if H.state.win_id and vim.api.nvim_win_is_valid(H.state.win_id) then vim.wo[H.state.win_id].winbar = make_winbar() endendlocal function prepend_new_events(new_events) if not H.state or not H.state.buf_id then return end if #new_events == 0 then return end local new_display_events = {} for _, ev in ipairs(new_events) do if event_passes_filters(ev, H.state.filters) then new_display_events[#new_display_events + 1] = ev end end if #new_display_events == 0 then return end local new_lines = {} local new_highlights = {} local new_line_events = {} local base_idx = 1 for ei, event in ipairs(new_display_events) do local d = format_event_for_display(event) local header = string.format(' %s %s · %s', d.icon, d.kind_name, d.time) local msg_line = ' ' .. d.message local loc_line = ' ' .. d.location local header_line_idx = #new_lines + 1 new_lines[#new_lines + 1] = header new_line_events[header_line_idx] = base_idx + ei - 1 new_highlights[#new_highlights + 1] = { line = header_line_idx, kind = event.kind, icon_start = 1, icon_end = #d.icon + 1, kind_name_start = #d.icon + 2, kind_name_end = #d.icon + 2 + #d.kind_name, time_start = #header - #d.time, time_end = #header, } local msg_line_idx = #new_lines + 1 new_lines[#new_lines + 1] = msg_line new_line_events[msg_line_idx] = base_idx + ei - 1 local loc_line_idx = #new_lines + 1 new_lines[#new_lines + 1] = loc_line new_line_events[loc_line_idx] = base_idx + ei - 1 new_highlights[#new_highlights + 1] = { line = loc_line_idx, location = true, } local blank_idx = #new_lines + 1 new_lines[#new_lines + 1] = '' new_line_events[blank_idx] = nil end local was_modifiable = vim.bo[H.state.buf_id].modifiable vim.bo[H.state.buf_id].modifiable = true vim.api.nvim_buf_set_lines(H.state.buf_id, 0, 0, false, new_lines) vim.bo[H.state.buf_id].modifiable = was_modifiable local shift = #new_lines local shifted_line_events = {} for line_idx, event_idx in pairs(H.state.line_events) do shifted_line_events[line_idx + shift] = event_idx + #new_display_events end for line_idx, event_idx in pairs(new_line_events) do shifted_line_events[line_idx] = event_idx end H.state.line_events = shifted_line_events local all_highlights = {} for _, hl in ipairs(H.state.highlights or {}) do all_highlights[#all_highlights + 1] = { line = hl.line + shift, kind = hl.kind, location = hl.location, icon_start = hl.icon_start, icon_end = hl.icon_end, kind_name_start = hl.kind_name_start, kind_name_end = hl.kind_name_end, time_start = hl.time_start, time_end = hl.time_end, } end for _, hl in ipairs(new_highlights) do all_highlights[#all_highlights + 1] = hl end H.state.highlights = all_highlights vim.api.nvim_buf_clear_highlight(H.state.buf_id, H.ns_id, 0, -1) for _, hl in ipairs(all_highlights) do local lnum = hl.line - 1 if hl.location then vim.api.nvim_buf_add_highlight(H.state.buf_id, H.ns_id, NS_HL.location, lnum, 0, -1) elseif hl.kind then 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) 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) 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) else vim.api.nvim_buf_add_highlight(H.state.buf_id, H.ns_id, NS_HL.message, lnum, 0, -1) end end H.state.filtered_count = H.state.filtered_count + #new_display_events if H.state.win_id and vim.api.nvim_win_is_valid(H.state.win_id) then vim.wo[H.state.win_id].winbar = make_winbar() endendlocal function on_file_change() if not H.state then return end local watcher = H.state.watcher if watcher then watcher:stop() H.state.watcher = nil end local new_events, new_total = file.read_new(H.state.event_count) if #new_events == 0 and new_total == H.state.event_count then H.state.watcher = start_watcher() return end local reversed = {} for i = #new_events, 1, -1 do reversed[#reversed + 1] = new_events[i] end new_events = reversed for i = #new_events, 1, -1 do table.insert(H.state.events, 1, new_events[i]) end H.state.event_count = new_total prepend_new_events(new_events) H.state.watcher = start_watcher()endstart_watcher = function() local path = file.get_path() local callback = function(err) if err then return end on_file_change() end local watcher = vim.uv.new_fs_event() watcher:start(path, {}, callback) return watcherendlocal function setup_keymaps(buf_id, win_id) map.normal { keys = 'q', command = close, buffer = buf_id, desc = 'Close debug viewer' } map.normal { keys = '<Esc>', command = close, buffer = buf_id, desc = 'Close debug viewer' } map.normal { keys = 'r', command = refresh, buffer = buf_id, desc = 'Refresh events from disk' } map.normal { keys = '<CR>', command = function() jump_to_source(win_id) end, buffer = buf_id, desc = 'Jump to source location' } map.normal { keys = 'ff', command = function() filter_by_all() end, buffer = buf_id, desc = 'Filter combined (all)' } map.normal { keys = 'fc', command = function() clear_filters() vim.notify('Filters cleared') end, buffer = buf_id, desc = 'Clear filters + notify' } map.normal { keys = 'fk', command = function() filter_by_kind() end, buffer = buf_id, desc = 'Filter by kind' } map.normal { keys = 'fm', command = function() filter_by_message() end, buffer = buf_id, desc = 'Filter by message' } map.normal { keys = 'fl', command = function() filter_by_location() end, buffer = buf_id, desc = 'Filter by location' }endfunction open() if H.state and H.state.win_id and vim.api.nvim_win_is_valid(H.state.win_id) then vim.api.nvim_set_current_win(H.state.win_id) return end local events = file.read_all() for i = 1, math.floor(#events / 2) do events[i], events[#events - i + 1] = events[#events - i + 1], events[i] end local buf_id = create_buf() local win_id = open_win(buf_id) setup_keymaps(buf_id, win_id) local watcher = start_watcher() H.state = { buf_id = buf_id, win_id = win_id, events = events, filtered_indices = nil, filters = { all = '', kind = '', message = '', filename = '' }, line_events = {}, filtered_count = #events, event_count = #events, watcher = watcher, } render()endfunction close() if not H.state then return end if H.state.watcher then H.state.watcher:stop() H.state.watcher = nil end if H.state.win_id and vim.api.nvim_win_is_valid(H.state.win_id) then pcall(vim.api.nvim_win_close, H.state.win_id, true) end if H.state.buf_id and vim.api.nvim_buf_is_valid(H.state.buf_id) then pcall(vim.api.nvim_buf_delete, H.state.buf_id, { force = true }) end H.state = nilendfunction refresh() if not H.state then return end local events = file.read_all() H.state.events = events H.state.event_count = #events H.state.filtered_indices = compute_filtered_indices(events, H.state.filters) render()endfunction is_open() return H.state ~= nil and H.state.win_id ~= nil and vim.api.nvim_win_is_valid(H.state.win_id)endfunction jump_to_source(win_id) if not H.state or not H.state.buf_id then return end local cursor = vim.api.nvim_win_get_cursor(win_id or H.state.win_id) local line_idx = cursor[1] local event_idx = H.state.line_events[line_idx] if not event_idx then event_idx = H.state.line_events[line_idx - 1] end if not event_idx then event_idx = H.state.line_events[line_idx + 1] end if not event_idx then return end local event = H.state.events[event_idx] if not event then return end local path = sanitize_src(event.filename) if path == 'unknown' or path == '' then return end close() vim.cmd.edit(path) if event.line and event.line > 0 then pcall(vim.api.nvim_win_set_cursor, 0, { event.line, 0 }) endendfunction clear_filters() if not H.state then return end H.state.filters = { all = '', kind = '', message = '', filename = '' } H.state.filtered_indices = nil H.state.filtered_count = #H.state.events render()endfunction filter_by_all() vim.ui.input({ prompt = 'Filter (all): ' }, function(value) if value == nil then return end if not H.state then return end H.state.filters.all = value or '' H.state.filtered_indices = compute_filtered_indices(H.state.events, H.state.filters) render() end)endlocal function do_filter(field, prompt_msg) vim.ui.input({ prompt = prompt_msg .. ': ' }, function(value) if value == nil then return end if not H.state then return end H.state.filters[field] = value or '' H.state.filtered_indices = compute_filtered_indices(H.state.events, H.state.filters) render() end)endfunction filter_by_kind() do_filter('kind', 'Filter kind')endfunction filter_by_message() do_filter('message', 'Filter message')endfunction filter_by_location() do_filter('filename', 'Filter location')endreturn { open = open, close = close, refresh = refresh, is_open = is_open, jump_to_source = jump_to_source, clear_filters = clear_filters, filter_by_all = filter_by_all, filter_by_kind = filter_by_kind, filter_by_message = filter_by_message, filter_by_location = filter_by_location, get_winbar = get_winbar, _on_file_change = on_file_change, _get_state = function() return H.state end,}neovim/lua/std/executable.lua
Addednew file mode 100644+4 / −0 text lines
neovim/lua/std/ftoptions.lua
Addednew file mode 100644+99 / −0 text lines
-- per-filetype options harvested from the builtin vimscript ftplugins-- ( nvim 0.12, before the ftplugin kill ) then filtered to pure-data options.-- deliberately dropped: omnifunc ( LSP owns it ), includeexpr ( vimscript/autoload ),-- cinkeys/cinwords ( cindent is off, treesitter indents ).-- commentstring lives in std.commentstring. edit freely.local ftoptions = { ["c"] = { comments = [[sO:* -,mO:* ,exO:*/,s1:/*,mb:*,ex:*/,:///,://]], define = [[^\s*#\s*define]], formatoptions = [[jcroql]], include = [[^\s*#\s*include]], path = [[.,/usr/include,,**]], }, ["cpp"] = { comments = [[sO:* -,mO:* ,exO:*/,s1:/*,mb:*,ex:*/,:///,://]], define = [[^\s*#\s*define]], formatoptions = [[jcroql]], include = [[^\s*#\s*include]], path = [[.,/usr/include,,**]], }, ["css"] = { comments = [[s1:/*,mb:*,ex:*/]], formatoptions = [[jcroql]], include = [[^\s*@import\s\+\%(url(\)\=]], }, ["html"] = { comments = [[s:<!--,m: ,e:-->]], matchpairs = [[(:),{:},[:],<:>]], }, ["java"] = { comments = [[:///,sO:* -,mO:* ,exO:*/,s1:/*,mb:*,ex:*/,://,b:#,:%,:XCOMM,n:>,fb:-,fb:•]], 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*(\)]], formatoptions = [[jcroql]], include = [[\C\m^\s*import\s\+\ze\%(\K\k*\.\)\+\K\k*;]], suffixesadd = [[.java]], }, ["javascript"] = { comments = [[sO:* -,mO:* ,exO:*/,s1:/*,mb:*,ex:*/,://]], 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\>]], formatoptions = [[jcroql]], suffixesadd = [[.js,.jsx,.es,.es6,.cjs,.mjs,.jsm,.vue,.json]], }, ["javascriptreact"] = { comments = [[sO:* -,mO:* ,exO:*/,s1:/*,mb:*,ex:*/,://]], 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\>]], formatoptions = [[jcroql]], suffixesadd = [[.js,.jsx,.es,.es6,.cjs,.mjs,.jsm,.vue,.json]], }, ["json"] = { formatoptions = [[cqj]], }, ["jsonc"] = { comments = [[sO:* -,mO:* ,exO:*/,s1:/*,mb:*,ex:*/,://]], formatoptions = [[cqj]], }, ["ocaml"] = { comments = [[sr:(**,mb: ,ex:*),sr:(* ,mb: ,ex:*)]], formatoptions = [[cqort]], iskeyword = [[@,48-57,_,192-255,-,',`]], }, ["roc"] = { comments = [[:##,:#]], }, ["rust"] = { comments = [[s0:/*!,ex:*/,s1:/*,mb:*,ex:*/,:///,://!,://]], formatoptions = [[croqnlj]], include = [[\v^\s*(pub\s+)?use\s+\zs(\f|:)+]], matchpairs = [[(:),{:},[:],<:>]], suffixesadd = [[.rs]], }, ["scss"] = { comments = [[s1:/*,mb:*,ex:*/,://]], define = [[^\C\v\s*%(\@function|\@mixin|\=)|^\s*%(\$[[:alnum:]-]+:|[%.][:alnum:]-]+\s*%(\{|$))@=]], include = [[^\s*@import\s\+\%(url(\)\=["']\=]], suffixesadd = [[.sass,.scss,.css]], }, ["typescript"] = { comments = [[sO:* -,mO:* ,exO:*/,s1:/*,mb:*,ex:*/,://]], formatoptions = [[jcroql]], iskeyword = [[@,48-57,_,192-255,-,$,#]], suffixesadd = [[.ts,.d.ts,.tsx,.js,.jsx,.cjs,.mjs]], }, ["typescriptreact"] = { comments = [[sO:* -,mO:* ,exO:*/,s1:/*,mb:*,ex:*/,://]], formatoptions = [[jcroql]], iskeyword = [[@,48-57,_,192-255,-,$,#]], suffixesadd = [[.ts,.d.ts,.tsx,.js,.jsx,.cjs,.mjs]], }, ["zig"] = { comments = [[:///,://!,://]], define = [[\v(<fn>|<const>|<var>|^\s*\#\s*define)]], formatoptions = [[jcroql]], include = [[\v(\@import>|\@cInclude>|^\s*\#\s*include)]], iskeyword = [[@,48-57,_,192-255,-,@-@]], suffixesadd = [[.zig,.zir,.zon]], },}return ftoptionsneovim/lua/std/icon.lua
Modified+6 / −4 text lines
start = '',neovim/lua/std/light_up.lua
Modified+3 / −7 text lines
--- @return table groups A map of all highlight group names, mapping to themselves g:match('^([%w@%._]+)%s').--- @return table groups A map of all highlight group names, mapping to themselves.neovim/lua/std/localrc.lua
Deleteddeleted file mode 100644+0 / −29 text lines
local dbg = require 'std.dbg'--- loads given lua file path in current working directory into the current neovim lua runtime.--- @param file_name string path to lua file, that should be loaded--- @param validator function|string|table a validation function, that checks, if the loaded value fulfills your requirements.--- If `validator` is a string or table, then it should contain the allowed types of the value.--- @return any returns the evaluated value of the loaded lua file or `nil`, if it does not exists or did not pass--- validation.return function ( file_name, validator ) local filepath = vim.fn.fnamemodify( file_name, ':p' ) local file = vim.secure.read( filepath ) if not file then return nil end local fn, err = loadstring( file ) if not fn or err then dbg( 'unable to load %s. %s', file_name, err ) return nil end local value = fn() local validator_type = type( validator ) if validator_type == 'string' or validator_type == 'table' then local expected_types = validator_type == 'table' and validator or { validator, } local value_type = type( value ) local is_valid = vim.iter( expected_types ):any( function ( t ) return t == value_type end ) return is_valid and value or nil end return validator( value ) and value or nilendneovim/lua/std/map.lua
Modified+2 / −2 text lines
neovim/lua/std/project.lua
Modified+5 / −7 text lines
---@param path string? The starting path, from where to begin the search. If `nil`, the path of the current buffer is---@param markers table<string,number> List of markers, that define the root, that is searched for.---@param markers { name: string, weight: number }[] List of markers that define the searched root.---@param stop string? The last directory on the path to root, when to stop searching. if `nil`, the users home---@return string? # Directory, that contains the `markers` and lies on the path from `path` to `stop`.--- 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.---@param path string? path to start searching from. If `nil`, then path of current buffer is used.---@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`.---@param markers { name: string, weight: number }[]? list of weighted project markers.neovim/lua/std/puk.lua
Modified+4 / −4 text lines
neovim/lua/std/string.lua
Deleteddeleted file mode 100644+0 / −7 text lines
neovim/lua/std/table/deep_copy.lua
Deleteddeleted file mode 100644+0 / −11 text lines
neovim/lua/std/table/init.lua
Modified+1 / −12 text lines
neovim/lua/std/timeago.lua
Modified+1 / −1 text lines
neovim/pivi/.gitignore
Addednew file mode 100644+1 / −0 text lines
node_modules/neovim/pivi/README.md
Addednew file mode 100644+215 / −0 text lines
# PiviStandalone Neovim agent harness built on Pi Durable 1.5.2.Not a Pi coding-agent SDK/RPC adapter.Old `.system/` pivi documents describe the retired implementation.## Ownership- Durable owns conversations, model requests, tools, queues, compaction, persistence.- Neovim owns workspace buffers, including unsaved content.- File and process access goes through Durable's execution environment, implemented by `env.mjs` (`NeovimExecutionEnv`).- Durable's own `read`, `edit` and `write` run on it unchanged. There is no shell tool.- 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.- Everything else falls through to disk: files without unsaved changes, binary content, paths outside the working directory, temporary files.- Neovim-native tools sit beside it: `save`, `lsp`, `diagnostics`, `nvim_lua`.- `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.- `nvim_lua` runs a Lua chunk inside Neovim with the whole API, as a coroutine. `system(command, options)` starts a program from Neovim, streams its output, and returns code, stdout and stderr without freezing the editor. `await(function(resolve) … end)` suspends until any callback resolves; `sleep(ms)` waits. Programs see saved files only; the output begins with the unsaved buffers they could not see. 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. Globals a chunk assigns stay inside that chunk.- The system prompt forbids moving the user's window, buffer, cursor, or cwd.- No Pi coding-agent tools, config loader, or security sandbox.- Edits are best effort; no revision checks or transactional recovery across editor/worker crashes.## RuntimeNode 22.19+ required.Dependencies and lockfile live here, independently of the installed Pi CLI.```nujust pivi-installjust test-pivi````harness.mjs` owns Durable integration.`env.mjs` owns the execution environment; `tools.mjs` the Neovim-native tools.`credentials.mjs` owns the credential file.`worker.mjs` carries pivi's own JSONL transport over stdin/stdout.`../lua/bugabinga/pivi/` owns Neovim interaction.Transport records are pivi-specific, not Pi coding-agent RPC commands.Streamed view records omit the committed `items` when unchanged.Neovim reuses already rendered committed text.Window options (winbar, folds, wrap) are set window-locally; folding is enabled there even when disabled globally.## Interaction`:Pivi` opens the read-only Markdown conversation in the current window.`:Pivi draft` opens an ordinary editable Markdown draft in that same window.`<leader>pd` toggles conversation ↔ draft without a permanent split.Draft undo is independent of streamed transcript updates.Draft text is saved atomically to `stdpath('state')/pivi/sessions/<id>/draft.txt` and restored with that session.Typing uses a 250 ms save debounce; leaving the draft or accepting a submission flushes immediately.A failed save leaves the draft modified and reports the error; the prior saved copy remains untouched.Repeated submission keys are ignored until the first request is acknowledged or rejected.Submitting from the draft shows the conversation at its end.`G` resumes following; new output stays bottom-aligned.Scrolling, searching, selecting, or opening folds pauses following in that window.The winbar shows `following` or `reading`; each window keeps its own state.Shrinking output never resumes following on its own.Queued steering and follow-up messages appear as `queued:` blocks until placed.Live thinking and tool preparation appear as folded blocks while a turn streams.Finished turns collapse their work into one fold with tool/error totals, elapsed time, and known cost.Visible work stays open while you inspect it; streaming preserves your reading position.Tool results sit inside their call's fold; `zo` opens the work, then individual calls.Markdown tables remain native text so cursor movement, search, selection, and yanking agree.Code blocks use a background; native Markdown conceal, outline, and heading motions remain available.The winbar shows elapsed work and known session cost.OSC 9;4 busy/reset sequences are emitted when Neovim supports `nvim_ui_send`; terminal support is optional.Every submitted prompt starts with an automatic `[editor: cwd · buffer · line · saved state]` note about the most recently used workspace buffer.Buffers the agent modifies become listed, so they show up in the buffer list.`:Pivi compact` on a short conversation reports that there is nothing to compact.## Stopping`<leader>px` or `:Pivi stop` stops the current work; the winbar shows `stopping` until it has.Stop is never queued behind other operations.Programs started with `system` are killed with their whole process group, and the waiting chunk is dropped.A 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.The stopped request stays in the conversation, followed by `stopped by you`; the model is told not to continue it.Queued steering and follow-up messages return to the draft instead of being lost.Stopping while idle does nothing.Closing pivi or Neovim kills commands the agent started.## Failures and recoveryTool failures stay in the transcript; the model can recover without stopping the conversation.Provider backoff shows the provider's error and a retry countdown; `:Pivi stop` cancels waiting.Failed runs show `failed`, not `idle`, with the original error and recovery commands.Quota and authentication messages remain verbatim; pivi does not guess their meaning.Drafts and unsaved editor changes are not cleared by a failed run.`:Pivi login` repairs credentials; `:Pivi model` changes the model.`:Pivi continue` asks before continuing a stopped run from retained history without adding another prompt.Continuation may repeat actions; review existing edits first.`:Pivi resume` resumes interrupted Durable tasks after reconnecting, not a terminal provider failure.Disconnected winbars point to `:Pivi` for reconnecting.Retained work after reconnect shows `suspended`, not `working`; use `:Pivi resume` or `:Pivi stop`.Startup/storage failures and malformed worker records retain diagnostic text instead of resetting the session.Compaction failure keeps history intact; `:Pivi compact` explicitly retries after fixing the cause.## Review`<leader>pr` or `:Pivi review` shows every unsaved change against disk as one diff buffer and fills the quickfix list with the changes.The conversation winbar shows how many buffers are unsaved.Review 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.Saving one change writes the file with just that change applied and leaves the rest unsaved; reverting one change is undoable in its buffer.The review refreshes whenever it is entered, and covers your own unsaved edits as well as the agent's.`<leader>p?` shows the bindings that apply where the cursor is.`?` inside that popup opens the full, searchable binding help.Every pivi key is `vim.g.pivi_prefix` plus one character; the prefix defaults to `<leader>p`.Set `vim.g.pivi_prefix` before pivi loads to move them all, including the global `<prefix>p` that opens pivi.Pivi maps nothing outside that prefix in its conversation and draft buffers.Native `/`, `?`, folds, editing, registers remain available where applicable.Draft actions:- `<CR>` in normal mode sends the draft: submit while idle, steer while busy.- `<C-CR>` or `<C-J>` in the draft queues a follow-up. Insert mode is untouched.- `<Esc>` in the conversation stops work while busy.Prefixed actions (`vim.g.pivi_prefix`, default `<leader>p`):- `gb` in normal mode is the goblin operator: `gb}` sends a motion, `gbG` the rest of the buffer.- `gb` in visual mode sends the selection. `:Pivi goblin` sends the whole current buffer.- `vim.g.pivi_goblin_prompt` overrides the prompt goblin sends with the attachment.- `<leader>ps`: submit while idle.- `<leader>pt`: steer active run.- `<leader>pu`: queue follow-up.- `<leader>pa`: attach/open/remove buffer, file, or diagnostics context.- `<leader>po`: inspect attachment.- `<leader>px`: stop work.- `<leader>pr`: review unsaved changes.Attachments resolve through Neovim at submission time.Attachment labels appear in the draft window's winbar, not as virtual lines.Each attachment is appended to the submitted prompt as a `<buffer number name>...</buffer>` block.Diagnostics attachments are appended as a `<diagnostics ...>...</diagnostics>` block of `line:col SEVERITY message` lines.Files are loaded as buffers before attachment.Conversation actions:- `<leader>po`: inspect entry in a detail buffer.- `<leader>pf`: fork at committed entry under cursor. On a prompt: new conversation holds the history before it, prompt returns as draft; refused while the draft is not empty.- `za`: native tool/thinking/result fold.Compaction summaries appear in the conversation as a folded `compacted` block.Commands are `attach`, `close`, `compact`, `continue`, `draft`, `earlier`, `fork`, `help`, `login`, `logout`, `model`, `new`, `resume`, `review`, `show`, `stop`.`new` and `fork` reject active work rather than silently interrupting it.`resume` explicitly resumes interrupted Durable tasks after the editor reconnects.## Models`:Pivi model` selects an available model.`:Pivi model provider/model-id` selects directly.Default runtime uses pi-ai built-in providers.A provider is usable through a stored sign-in or through its environment variables.`:Pivi model` lists only usable models; with none, it leads straight into sign-in.Normal Pi coding-agent providers, authentication files, settings, extensions, skills, and templates are not automatically loaded.No model requests happen merely by opening pivi; `:Pivi model` refreshes provider model catalogs.## Sign-in`:Pivi login [provider]` signs in; `:Pivi logout [provider]` removes a stored sign-in.The provider picker shows each provider's state: `●` signed in, `◐` ready through environment, `○` not set up.Providers offering both ask whether to use an account or an API key.API keys are typed into a masked prompt.Account sign-in shows a panel inside Neovim and opens the browser.Panel keys: `o` open browser, `y` copy link or device code, `p` paste a code by hand, `q` or `<Esc>` cancel.Closing the panel cancels the sign-in.After a first sign-in without a chosen model, the model picker opens for that provider.Credentials live in `stdpath('state')/pivi/auth.json`, mode 0600, shared by all pivi sessions.Writes are atomic and serialized across Neovim instances through a lock file, so token refresh cannot lose updates.Pi's own `~/.pi/agent/auth.json` is never read or written; sign in once per provider in pivi.`vim.g.pivi_node` optionally selects the Node executable.`vim.g.pivi_config` optionally names an absolute `.mjs` config path.Its default export is a function, sync or async, receiving `{ credentials }` and returning `{ models, extensions }`.Pass `credentials` to your own Models collection to keep sign-in working.`models` is a pi-ai Models collection; extension contributions currently use Durable's registry format.This bootstrap seam is not yet a stable pivi extension API.## Storage```textstdpath('state')/pivi/sessions/<PiviSession>/session.sqlite```One pivi session owns one Durable storage, containing multiple conversations and one active conversation reference.Cwd does not determine identity.`vim.g.PiviSession` is restored with Neovim session globals after pivi has been opened.No ShaDa dependency.Only one worker should open a given pivi session for writing.Closing/reopening the worker preserves draft buffers in the running Neovim instance.Draft text is recovered from its separate file, not SQLite.Unsaved workspace buffers and attachment selections are not recovered by pivi after Neovim exits.Abrupt termination can lose draft edits from the debounce interval.Old Pi coding-agent session files are neither migrated nor deleted.## Verification`just test-pivi` runs offline Durable tests, real editor/worker integration tests, and driven native-input tests.The input test types a draft while a deterministic provider streams, checks undo/redo against unchanged transcript, toggles buffers, then repeats.No external model calls are required.## Not implemented yetNative 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`.No claim of legacy feature parity.neovim/pivi/credentials.mjs
Addednew file mode 100644+73 / −0 text lines
import { mkdir, open, readFile, rename, rm, stat, writeFile } from 'node:fs/promises';import { dirname } from 'node:path';import { setTimeout as sleep } from 'node:timers/promises';const STALE_LOCK_MS = 60_000;export function fileCredentials(path) { const lock = `${path}.lock`; let queue = Promise.resolve(); async function load() { try { return JSON.parse(await readFile(path, 'utf8')); } catch (error) { if (error.code === 'ENOENT') return {}; throw error; } } async function save(all) { const temporary = `${path}.${process.pid}.tmp`; await writeFile(temporary, JSON.stringify(all, null, 2), { mode: 0o600 }); await rename(temporary, path); } async function acquire() { await mkdir(dirname(path), { recursive: true }); for (;;) { try { await (await open(lock, 'wx')).close(); return; } catch (error) { if (error.code !== 'EEXIST') throw error; const age = Date.now() - (await stat(lock).catch(() => ({ mtimeMs: 0 }))).mtimeMs; if (age > STALE_LOCK_MS) await rm(lock, { force: true }); else await sleep(50); } } } function exclusive(task) { const result = queue.then(async () => { await acquire(); try { return await task(await load()); } finally { await rm(lock, { force: true }); } }); queue = result.catch(() => {}); return result; } return { async read(provider) { return (await load())[provider]; }, async list() { return Object.entries(await load()).map(([providerId, credential]) => ({ providerId, type: credential.type })); }, modify(provider, change) { return exclusive(async (all) => { const next = await change(all[provider]); if (next === undefined) return all[provider]; await save({ ...all, [provider]: next }); return next; }); }, delete(provider) { return exclusive(async ({ [provider]: removed, ...rest }) => { if (removed !== undefined) await save(rest); }); }, };}neovim/pivi/env.mjs
Addednew file mode 100644+79 / −0 text lines
import { mkdtemp, rm, writeFile } from 'node:fs/promises';import { tmpdir } from 'node:os';import { basename, join, relative, resolve } from 'node:path';import { err, FileError, ok } from '@earendil-works/pi-durable/env';import { NodeExecutionEnv } from '@earendil-works/pi-durable/env/node';export class NeovimExecutionEnv extends NodeExecutionEnv { #editor; constructor({ cwd, editor }) { super({ cwd }); this.id = 'pivi-neovim'; this.#editor = editor; } async #unsaved(path, context) { return (await this.#editor('unsaved_text', { path: resolve(this.cwd, path) }, context))?.text; } async readTextFile(path, context) { const text = await this.#unsaved(path, context); return text === undefined ? super.readTextFile(path, context) : ok(text); } async readBinaryFile(path, context) { const text = await this.#unsaved(path, context); return text === undefined ? super.readBinaryFile(path, context) : ok(new TextEncoder().encode(text)); } async exists(path, context) { const onDisk = await super.exists(path, context); if (onDisk.ok && onDisk.value) return onDisk; return (await this.#unsaved(path, context)) === undefined ? onDisk : ok(true); } async fileInfo(path, context) { const text = await this.#unsaved(path, context); if (text === undefined) return super.fileInfo(path, context); const absolute = resolve(this.cwd, path); const size = Buffer.byteLength(text); return ok({ name: basename(absolute), path: absolute, kind: 'file', size, mtimeMs: Date.now() }); } async openBinaryReader(path, options, context) { const text = await this.#unsaved(path, context); if (text === undefined) return super.openBinaryReader(path, options, context); const directory = await mkdtemp(join(tmpdir(), 'pivi-buffer-')); const discard = () => rm(directory, { recursive: true, force: true }); const snapshot = join(directory, basename(path)); await writeFile(snapshot, text); const opened = await super.openBinaryReader(snapshot, options, context); if (!opened.ok) { await discard(); return opened; } const reader = opened.value; return ok({ info: (inner) => reader.info(inner), read: (offset, length, inner) => reader.read(offset, length, inner), scanLines: (range, inner) => reader.scanLines(range, inner), async close(inner) { await reader.close(inner); await discard(); }, }); } async writeFile(path, content, context) { const absolute = resolve(this.cwd, path); const workspace = !relative(this.cwd, absolute).startsWith('..'); if (typeof content !== 'string' || !workspace) return super.writeFile(path, content, context); try { await this.#editor('set_text', { path: absolute, content }, context); return ok(undefined); } catch (error) { return err(new FileError('unknown', error.message, absolute)); } }}neovim/pivi/harness.mjs
Addednew file mode 100644+195 / −0 text lines
import { readFile, writeFile } from 'node:fs/promises';import { BACKGROUND_CONTEXT as context } from '@earendil-works/chord/context';import { InMemoryCredentialStore } from '@earendil-works/pi-ai';import { builtinModels } from '@earendil-works/pi-ai/providers/all';import { CodemodeSandbox } from '@earendil-works/pi-codemode';import { Harness, LiveDoc, ConversationTranscript, createRegistry, defineDoc, defineExtension,} from '@earendil-works/pi-durable';import { createCodemodeExtension } from '@earendil-works/pi-durable/codemode';import { createEditTool, createReadTool, createWriteTool } from '@earendil-works/pi-durable/tools';import { openNodeSqliteStorage } from '@earendil-works/pi-durable/storage/sqlite/node';import { NeovimExecutionEnv } from './env.mjs';import { neovim } from './tools.mjs';const Session = defineDoc({ kind: 'pivi.session', version: 1, scope: 'session', initial: () => ({ active: null }), checkpointWhen: () => true,});const SUBMISSION = { submit: { whenBusy: 'reject' }, steer: { whenBusy: 'steer', whenIdle: 'reject' }, followUp: { whenBusy: 'followUp', whenIdle: 'reject' },};export async function openPivi({ database, editor, interact, onView, onReport, onNotice, cwd = process.cwd(), modelFile, credentials = new InMemoryCredentialStore(), models = builtinModels({ credentials }), extensions = [],}) { const storage = await openNodeSqliteStorage(database); const sandbox = new CodemodeSandbox(); let harness; try { const registry = createRegistry(); const files = defineExtension({ name: 'pivi.files', tools: [createReadTool(), createEditTool(), createWriteTool()], }); for (const extension of [files, neovim(editor), createCodemodeExtension({ sandbox }), ...extensions]) { registry.install(extension); } const environment = new NeovimExecutionEnv({ cwd, editor }); harness = await Harness.open(storage, { models, registry, onReport, env: () => environment }, context); let conversation; let transcript; let watch; let login; const show = async (view) => onView?.({ ...transcript.merge(view), scheduling: (await harness.inspect(context)).scheduling, }); async function activate(next) { await watch?.stop(); conversation = next; transcript = new ConversationTranscript((query, limit, callContext) => next.entries(query, limit, undefined, callContext)); await harness.commit(async (tx) => { (await tx.doc(Session)).active = next.id; }, context); watch = await next.watch(context); await show(watch.value); watch.start(async (call) => { if (call.kind === 'value') await show(call.value); }); } async function requireIdle() { const live = await harness.snapshot(LiveDoc, conversation.id, context); if (live?.run || live?.compactions?.length) throw new Error('Stop active work before changing conversation.'); } const active = (await harness.snapshot(Session, context))?.active; await activate((active != null && await harness.conversation(active, context)) || await harness.root(context)); // A new session keeps the model the last one used, when the provider still offers it. if (modelFile && !(await conversation.agent(context)).model) { try { const saved = JSON.parse(await readFile(modelFile, 'utf8')); if (models.getModel(saved.provider, saved.modelId)) { await conversation.configure({ model: saved }, context); } } catch { // No usable saved model: pick one with :Pivi model. } } return { harness, get conversation() { return conversation; }, async close() { await watch.stop(); await harness.close(context); await sandbox.close(); }, commands: { async submit({ content, mode = 'submit' }) { if (!Object.hasOwn(SUBMISSION, mode)) throw new Error(`Unknown submission mode: ${mode}`); if (!(await conversation.agent(context)).model) throw new Error('Choose a model with :Pivi model first.'); const submission = await conversation.submit({ type: 'input', content, ...SUBMISSION[mode] }, context); return { id: submission.id }; }, async models() { await models.refresh(); return (await models.getAvailable()).map(({ provider, id }) => ({ provider, modelId: id })); }, async configure({ model }) { if (!models.getModel(model.provider, model.modelId)) throw new Error('Unknown model.'); await conversation.configure({ model }, context); if (modelFile) await writeFile(modelFile, JSON.stringify(model), 'utf8').catch(() => {}); }, async compact({ instructions }) { const task = await conversation.compact(instructions || undefined, context); harness.waitForTask(task, context).then(({ state: { outcome } }) => { const { entryId, submissionId } = outcome.result ?? {}; if (outcome.status === 'completed' && !entryId && !submissionId) { onNotice?.('Nothing to compact yet: the conversation is still short.'); } }, () => {}); }, async earlier() { const current = watch.value; const view = await transcript.loadEarlier(context); if (view.items === current.items || view.items?.length === current.items?.length) { onNotice?.('No earlier entries: the transcript already starts here.'); } await onView?.({ ...view, scheduling: (await harness.inspect(context)).scheduling }); }, async resume() { const { tasks } = await harness.inspect(context); harness.resume(); if (!tasks.length) onNotice?.('Nothing suspended in this session to resume.'); await show(watch.value); }, async continue() { await requireIdle(); const live = await harness.snapshot(LiveDoc, conversation.id, context); if (!live?.runFailure) throw new Error('No stopped run to continue. Write a new draft instead.'); await conversation.submit({ type: 'continue' }, context); }, async new() { await requireIdle(); const { model } = await conversation.agent(context); const options = { ownership: { kind: 'ownerless' }, agent: { model } }; await activate(await harness.createConversation(options, context)); }, async fork({ entry }) { await requireIdle(); await activate(await conversation.fork(entry, { ownership: { kind: 'ownerless' } }, context)); }, }, immediate: { async abort() { const running = (await harness.snapshot(LiveDoc, conversation.id, context))?.run !== undefined; await conversation.abort(context); if (!running) return; const message = { role: 'user', content: [{ type: 'text', text: '[interrupted]' }], timestamp: Date.now() }; const entry = { kind: 'pivi.interrupted', data: null, model: [message] }; await conversation.submit({ type: 'write', entry }, context); }, async providers() { const stored = new Map((await credentials.list()).map(({ providerId, type }) => [providerId, type])); return Promise.all(models.getProviders().map(async ({ id, name, auth }) => ({ id, name, stored: stored.get(id), source: (await models.checkAuth(id).catch(() => undefined))?.source, methods: [ auth.oauth && { type: 'oauth', label: auth.oauth.loginLabel ?? auth.oauth.name }, auth.apiKey?.login && { type: 'api_key', label: auth.apiKey.name }, ].filter(Boolean), }))); }, async login({ provider, method }) { if (login) throw new Error('Another sign-in is in progress.'); login = new AbortController(); try { const { signal } = login; const prompt = (request) => interact.prompt({ ...request, signal: request.signal ? AbortSignal.any([request.signal, signal]) : signal, }); await models.login(provider, method, { signal, prompt, notify: interact.notify }); await models.refresh({ providers: [provider] }); } finally { login = undefined; } }, async cancel() { login?.abort(); }, async logout({ provider }) { await models.logout(provider); }, }, }; } catch (error) { await sandbox.close(); await (harness ?? storage).close(context); throw error; }}neovim/pivi/package-lock.json
Addednew file mode 100644+1236 / −0 text lines
{ "name": "pivi", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "pivi", "dependencies": { "@earendil-works/chord": "1.5.2", "@earendil-works/pi-ai": "1.5.2", "@earendil-works/pi-codemode": "1.5.2", "@earendil-works/pi-durable": "1.5.2", "@earendil-works/pi-schema": "1.5.2" }, "engines": { "node": ">=22.19.0" } }, "node_modules/@anthropic-ai/sdk": { "version": "0.129.0", "resolved": "https://registry.npmjs.org/@anthropic-ai/sdk/-/sdk-0.129.0.tgz", "integrity": "sha512-MH7LB20kNpGLUpPTe2OG5XvL/KhX8HUO9XyBaFjgFk6TLS4Xjt0VPIuMKywe7POKKPslX+QxSlVok9e+8kG5Nw==", "license": "MIT", "dependencies": { "json-schema-to-ts": "^3.1.1", "standardwebhooks": "^1.0.0" }, "bin": { "anthropic-ai-sdk": "bin/cli" }, "peerDependencies": { "zod": "^3.25.0 || ^4.0.0" }, "peerDependenciesMeta": { "zod": { "optional": true } } }, "node_modules/@aws-sdk/client-bedrock-runtime": { "version": "3.1127.0", "resolved": "https://registry.npmjs.org/@aws-sdk/client-bedrock-runtime/-/client-bedrock-runtime-3.1127.0.tgz", "integrity": "sha512-IDl/lrPb90aH+pZFHGNDmgH9nAUQj5PlZH1sJ3w7RikctyjHSnY3oNjZhrLoaBoQn/rNK0zsP6OHEqEhj2tdLA==", "license": "Apache-2.0", "dependencies": { "@aws-sdk/core": "^3.977.9", "@aws-sdk/credential-provider-node": "^3.972.82", "@aws-sdk/eventstream-handler-node": "^3.972.34", "@aws-sdk/middleware-eventstream": "^3.972.29", "@aws-sdk/middleware-websocket": "^3.972.52", "@aws-sdk/token-providers": "3.1127.0", "@aws-sdk/types": "^3.974.5", "@smithy/core": "^3.33.3", "@smithy/fetch-http-handler": "^5.7.2", "@smithy/node-http-handler": "^4.11.3", "@smithy/types": "^4.17.2", "tslib": "^2.6.2" }, "engines": { "node": ">=20.0.0" } }, "node_modules/@aws-sdk/core": { "version": "3.981.0", "resolved": "https://registry.npmjs.org/@aws-sdk/core/-/core-3.981.0.tgz", "integrity": "sha512-Mnu7gaDrC5UCdyH8uLxLfB2eWbjE/HbjKX1U1J2VQxG3TTATUDObW2wU3I8iH3e9YH5NN2CY6w1mlAIe2XJ3jg==", "license": "Apache-2.0", "dependencies": { "@aws-sdk/types": "^3.975.1", "@aws-sdk/xml-builder": "^3.972.43", "@aws/lambda-invoke-store": "^0.3.0", "@smithy/core": "^3.40.0", "@smithy/signature-v4": "^5.7.5", "@smithy/types": "^4.20.0", "bowser": "^2.11.0", "tslib": "^2.6.2" }, "engines": { "node": ">=20.0.0" } }, "node_modules/@aws-sdk/credential-provider-env": { "version": "3.972.84", "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-env/-/credential-provider-env-3.972.84.tgz", "integrity": "sha512-akZJetiMVeLRHsKzYh3LamDCo74ZUCeo0XoyRKMEMZT5qP7ReM6LhpioBCyuqKP5Vav5gEOeCmaQV0VVQr1Meg==", "license": "Apache-2.0", "dependencies": { "@aws-sdk/core": "^3.981.0", "@aws-sdk/types": "^3.975.1", "@smithy/core": "^3.40.0", "@smithy/types": "^4.20.0", "tslib": "^2.6.2" }, "engines": { "node": ">=20.0.0" } }, "node_modules/@aws-sdk/credential-provider-http": { "version": "3.972.86", "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-http/-/credential-provider-http-3.972.86.tgz", "integrity": "sha512-U4mHaDRPWAn63yhl7FXIzbppNmW1F+4dSLeuiUpej2v3Xb6rGwvayEJ8SdlrdMV+/mZtd+GStTEP2HqurEzXtw==", "license": "Apache-2.0", "dependencies": { "@aws-sdk/core": "^3.981.0", "@aws-sdk/types": "^3.975.1", "@smithy/core": "^3.40.0", "@smithy/fetch-http-handler": "^5.8.1", "@smithy/node-http-handler": "^4.14.2", "@smithy/types": "^4.20.0", "tslib": "^2.6.2" }, "engines": { "node": ">=20.0.0" } }, "node_modules/@aws-sdk/credential-provider-http/node_modules/@smithy/node-http-handler": { "version": "4.14.2", "resolved": "https://registry.npmjs.org/@smithy/node-http-handler/-/node-http-handler-4.14.2.tgz", "integrity": "sha512-i1uORV1v3qBqP43ayRKzIdm1q5x14tf8N4Dd06/QUX1Szm6VxHMrTsu20X5E63UFsaNZCRjI4SXG0jDmqYa+3w==", "license": "Apache-2.0", "dependencies": { "@smithy/core": "^3.39.0", "@smithy/types": "^4.20.0", "tslib": "^2.6.2" }, "engines": { "node": ">=18.0.0" } }, "node_modules/@aws-sdk/credential-provider-ini": { "version": "3.973.30", "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-ini/-/credential-provider-ini-3.973.30.tgz", "integrity": "sha512-r6r6499GWoGN943NA5YEhBEQ6TEOGTf7tTOBhHd/zw0UbNvSzd1/zPCNcDkPmRarA+e24X7KgxutqxjoWcskBg==", "license": "Apache-2.0", "dependencies": { "@aws-sdk/core": "^3.981.0", "@aws-sdk/credential-provider-env": "^3.972.84", "@aws-sdk/credential-provider-http": "^3.972.86", "@aws-sdk/credential-provider-login": "^3.972.92", "@aws-sdk/credential-provider-process": "^3.972.84", "@aws-sdk/credential-provider-sso": "^3.973.28", "@aws-sdk/credential-provider-web-identity": "^3.972.90", "@aws-sdk/nested-clients": "^3.998.3", "@aws-sdk/types": "^3.975.1", "@smithy/core": "^3.40.0", "@smithy/credential-provider-imds": "^4.5.2", "@smithy/types": "^4.20.0", "tslib": "^2.6.2" }, "engines": { "node": ">=20.0.0" } }, "node_modules/@aws-sdk/credential-provider-login": { "version": "3.972.92", "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-login/-/credential-provider-login-3.972.92.tgz", "integrity": "sha512-96bcp9Pe/Xd60OEwncZ+kAQTQSu+fJnpUGz1qE6ghF5jnETmrk8XMU86mIP3lolvnCgR61XbZ+Ht6hdBjiQOmQ==", "license": "Apache-2.0", "dependencies": { "@aws-sdk/core": "^3.981.0", "@aws-sdk/nested-clients": "^3.998.3", "@aws-sdk/types": "^3.975.1", "@smithy/core": "^3.40.0", "@smithy/types": "^4.20.0", "tslib": "^2.6.2" }, "engines": { "node": ">=20.0.0" } }, "node_modules/@aws-sdk/credential-provider-node": { "version": "3.972.97", "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-node/-/credential-provider-node-3.972.97.tgz", "integrity": "sha512-E4a0IXXJVsIdo/K9roX4JAEfI0JJr7KTPymkbKgETRDqEcLygE4ZlLTe24+7Qkh8Dl5YpnPd+Tt0DOPJDFXIwA==", "license": "Apache-2.0", "dependencies": { "@aws-sdk/credential-provider-env": "^3.972.84", "@aws-sdk/credential-provider-http": "^3.972.86", "@aws-sdk/credential-provider-ini": "^3.973.30", "@aws-sdk/credential-provider-process": "^3.972.84", "@aws-sdk/credential-provider-sso": "^3.973.28", "@aws-sdk/credential-provider-web-identity": "^3.972.90", "@aws-sdk/types": "^3.975.1", "@smithy/core": "^3.40.0", "@smithy/credential-provider-imds": "^4.5.2", "@smithy/types": "^4.20.0", "tslib": "^2.6.2" }, "engines": { "node": ">=20.0.0" } }, "node_modules/@aws-sdk/credential-provider-process": { "version": "3.972.84", "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-process/-/credential-provider-process-3.972.84.tgz", "integrity": "sha512-199C6OpNejd0nq9GFAkEFIKids1FL0R6LJtL9c1OTiDOXki7S1OduuPxW4+hE0LwndcYJ7YHOuYTlqScfpCocA==", "license": "Apache-2.0", "dependencies": { "@aws-sdk/core": "^3.981.0", "@aws-sdk/types": "^3.975.1", "@smithy/core": "^3.40.0", "@smithy/types": "^4.20.0", "tslib": "^2.6.2" }, "engines": { "node": ">=20.0.0" } }, "node_modules/@aws-sdk/credential-provider-sso": { "version": "3.973.28", "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-sso/-/credential-provider-sso-3.973.28.tgz", "integrity": "sha512-bGg7wH8wVDJQIcJggO9lg1ZYbG7l+PbLwHuM3Bi/e1TlCZhU712JS1W3tdRpyptdJD1UGyhBNGO/YrhrQCHKbg==", "license": "Apache-2.0", "dependencies": { "@aws-sdk/core": "^3.981.0", "@aws-sdk/nested-clients": "^3.998.3", "@aws-sdk/token-providers": "3.1166.0", "@aws-sdk/types": "^3.975.1", "@smithy/core": "^3.40.0", "@smithy/types": "^4.20.0", "tslib": "^2.6.2" }, "engines": { "node": ">=20.0.0" } }, "node_modules/@aws-sdk/credential-provider-sso/node_modules/@aws-sdk/token-providers": { "version": "3.1166.0", "resolved": "https://registry.npmjs.org/@aws-sdk/token-providers/-/token-providers-3.1166.0.tgz", "integrity": "sha512-ngJ8mxXqtQ9mnp7QV6TWKJCxkpjVfPWxKQSc2FYhCyCfOVFIGdFv7P+/RqVffFrJAorwBPpktnv32gNlcEgF4g==", "license": "Apache-2.0", "dependencies": { "@aws-sdk/core": "^3.981.0", "@aws-sdk/nested-clients": "^3.998.3", "@aws-sdk/types": "^3.975.1", "@smithy/core": "^3.40.0", "@smithy/types": "^4.20.0", "tslib": "^2.6.2" }, "engines": { "node": ">=20.0.0" } }, "node_modules/@aws-sdk/credential-provider-web-identity": { "version": "3.972.90", "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-web-identity/-/credential-provider-web-identity-3.972.90.tgz", "integrity": "sha512-duLeE3xlf0viHeH+1RM4z5duR3b32BCZTWVMu+MbxFPjQBxy7hmIGEqt5hekuFPRuXoyhMovjNl+PNNsb5oiGQ==", "license": "Apache-2.0", "dependencies": { "@aws-sdk/core": "^3.981.0", "@aws-sdk/nested-clients": "^3.998.3", "@aws-sdk/types": "^3.975.1", "@smithy/core": "^3.40.0", "@smithy/types": "^4.20.0", "tslib": "^2.6.2" }, "engines": { "node": ">=20.0.0" } }, "node_modules/@aws-sdk/eventstream-handler-node": { "version": "3.972.42", "resolved": "https://registry.npmjs.org/@aws-sdk/eventstream-handler-node/-/eventstream-handler-node-3.972.42.tgz", "integrity": "sha512-YVB1wrpE1WF8NvMpaRyhwm9XBYl3HTbPNEIgybi0b0XpmBrJ7Y3Y/drbxh9qAVMbR+0hcwM63GPWzhOVRuerfg==", "license": "Apache-2.0", "dependencies": { "@aws-sdk/types": "^3.975.1", "@smithy/core": "^3.40.0", "@smithy/types": "^4.20.0", "tslib": "^2.6.2" }, "engines": { "node": ">=20.0.0" } }, "node_modules/@aws-sdk/middleware-eventstream": { "version": "3.972.38", "resolved": "https://registry.npmjs.org/@aws-sdk/middleware-eventstream/-/middleware-eventstream-3.972.38.tgz", "integrity": "sha512-4K6FDz2BxH3rve8Hw/8uApWXKCuKKMeYKzY23PoiGqUBWaA23eAy+GzW9aoG3Cm7HqgYzqkljl3ECJRJCxGs7g==", "license": "Apache-2.0", "dependencies": { "@aws-sdk/types": "^3.975.1", "@smithy/core": "^3.40.0", "@smithy/types": "^4.20.0", "tslib": "^2.6.2" }, "engines": { "node": ">=20.0.0" } }, "node_modules/@aws-sdk/middleware-websocket": { "version": "3.972.66", "resolved": "https://registry.npmjs.org/@aws-sdk/middleware-websocket/-/middleware-websocket-3.972.66.tgz", "integrity": "sha512-feGNDB15ZgqX4DTsUykkgj7d8hzfzx03v80EIyRA1FTbsbAJQKxYB50kRbrrpE5WeFaWhgk+p5YHlsoyXrI2/g==", "license": "Apache-2.0", "dependencies": { "@aws-sdk/core": "^3.981.0", "@aws-sdk/types": "^3.975.1", "@smithy/core": "^3.40.0", "@smithy/fetch-http-handler": "^5.8.1", "@smithy/signature-v4": "^5.7.5", "@smithy/types": "^4.20.0", "tslib": "^2.6.2" }, "engines": { "node": ">= 14.0.0" } }, "node_modules/@aws-sdk/nested-clients": { "version": "3.998.3", "resolved": "https://registry.npmjs.org/@aws-sdk/nested-clients/-/nested-clients-3.998.3.tgz", "integrity": "sha512-acHTTzMB13CU6dU4sxABYExMI3PQM2zStWH2MiUwJp/7QKTrLg2f7mbzSXoegW2kYOk2tdqQYagsZrWB8Xv7eA==", "license": "Apache-2.0", "dependencies": { "@aws-sdk/core": "^3.981.0", "@aws-sdk/signature-v4-multi-region": "^3.996.52", "@aws-sdk/types": "^3.975.1", "@smithy/core": "^3.40.0", "@smithy/fetch-http-handler": "^5.8.1", "@smithy/node-http-handler": "^4.14.2", "@smithy/types": "^4.20.0", "tslib": "^2.6.2" }, "engines": { "node": ">=20.0.0" } }, "node_modules/@aws-sdk/nested-clients/node_modules/@smithy/node-http-handler": { "version": "4.14.2", "resolved": "https://registry.npmjs.org/@smithy/node-http-handler/-/node-http-handler-4.14.2.tgz", "integrity": "sha512-i1uORV1v3qBqP43ayRKzIdm1q5x14tf8N4Dd06/QUX1Szm6VxHMrTsu20X5E63UFsaNZCRjI4SXG0jDmqYa+3w==", "license": "Apache-2.0", "dependencies": { "@smithy/core": "^3.39.0", "@smithy/types": "^4.20.0", "tslib": "^2.6.2" }, "engines": { "node": ">=18.0.0" } }, "node_modules/@aws-sdk/signature-v4-multi-region": { "version": "3.996.52", "resolved": "https://registry.npmjs.org/@aws-sdk/signature-v4-multi-region/-/signature-v4-multi-region-3.996.52.tgz", "integrity": "sha512-6W6SjGc8OXUhMzNxU1X922ghD+PP1XvzmCk5Scui0jaYsLezycMYR1RaLp5xTIOUrhTXyb4DnAbPr3fBgmdnzg==", "license": "Apache-2.0", "dependencies": { "@aws-sdk/types": "^3.975.1", "@smithy/signature-v4": "^5.7.5", "@smithy/types": "^4.20.0", "tslib": "^2.6.2" }, "engines": { "node": ">=20.0.0" } }, "node_modules/@aws-sdk/token-providers": { "version": "3.1127.0", "resolved": "https://registry.npmjs.org/@aws-sdk/token-providers/-/token-providers-3.1127.0.tgz", "integrity": "sha512-Dv2TMWBshJ+tF6ahs2Sy5bh4Iabsd4GAQqVvE9XZmYmnoaVbpS2QKIKE/HRacc7bTtbjEEvP+laGzHvHlf1CiQ==", "license": "Apache-2.0", "dependencies": { "@aws-sdk/core": "^3.977.9", "@aws-sdk/nested-clients": "^3.997.44", "@aws-sdk/types": "^3.974.5", "@smithy/core": "^3.33.3", "@smithy/types": "^4.17.2", "tslib": "^2.6.2" }, "engines": { "node": ">=20.0.0" } }, "node_modules/@aws-sdk/types": { "version": "3.975.1", "resolved": "https://registry.npmjs.org/@aws-sdk/types/-/types-3.975.1.tgz", "integrity": "sha512-7rGxUkCB2QPoQOeJmonmAICTN2zrH+fpmi1p4Iwu72lnxNaMhOgqcbpyddifnM1DBb19TWQ1u6z/XjkaFNEDWw==", "license": "Apache-2.0", "dependencies": { "@smithy/types": "^4.20.0", "tslib": "^2.6.2" }, "engines": { "node": ">=20.0.0" } }, "node_modules/@aws-sdk/xml-builder": { "version": "3.972.43", "resolved": "https://registry.npmjs.org/@aws-sdk/xml-builder/-/xml-builder-3.972.43.tgz", "integrity": "sha512-rG8QVx4DOrJWptsogu1Aq+CDsnPKaBrAlJpKLxrJrIDXAq1ElnW0yQjjBnlWSXll0cDakCG6UDvaqwz0A9d9Og==", "license": "Apache-2.0", "dependencies": { "@smithy/types": "^4.20.0", "tslib": "^2.6.2" }, "engines": { "node": ">=20.0.0" } }, "node_modules/@aws/lambda-invoke-store": { "version": "0.3.0", "resolved": "https://registry.npmjs.org/@aws/lambda-invoke-store/-/lambda-invoke-store-0.3.0.tgz", "integrity": "sha512-sl4Bm6yiMNYrZKkqqDFWN0UfnWhlS8ivKxrYl+6t0gCLrqr8y3B2IqZZbFRkfaVVp7C/baApyh71P+LeE1A2sQ==", "license": "Apache-2.0", "engines": { "node": ">=18.0.0" } }, "node_modules/@babel/runtime": { "version": "7.29.14", "resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.29.14.tgz", "integrity": "sha512-Y5tqevQaUAZhhj82BpYMNC1ssvLQTVAfwKdm8iy8qwmhvC2/CpcAu8OC+QEtjM7pMk7knx83u1Qj8gzkicyelw==", "license": "MIT", "engines": { "node": ">=6.9.0" } }, "node_modules/@earendil-works/chord": { "version": "1.5.2", "resolved": "https://registry.npmjs.org/@earendil-works/chord/-/chord-1.5.2.tgz", "integrity": "sha512-3g088g7qVXL2cpRAKWjj9za6RLls9FBnuUo5c0hBZ0xCftBQjae0opS+34M22vdXTVE7BNqkRG/FPc9BsM7eEg==", "license": "MIT", "dependencies": { "@earendil-works/pi-schema": "1.5.2", "@earendil-works/pi-telemetry": "1.5.2" }, "engines": { "node": ">=22.19.0" }, "peerDependencies": { "esbuild": "0.28.2", "react": "19.3.0", "ws": "8.21.0" }, "peerDependenciesMeta": { "esbuild": { "optional": true }, "react": { "optional": true }, "ws": { "optional": true } } }, "node_modules/@earendil-works/pi-ai": { "version": "1.5.2", "resolved": "https://registry.npmjs.org/@earendil-works/pi-ai/-/pi-ai-1.5.2.tgz", "integrity": "sha512-2tWPSnV3qzfiDIY3aWluBag3vC++Vs+VsXt/UquSU5onPMohPih72FUhIhaqmDdMYubOgB3Byl9uF4Vk40JLvQ==", "license": "MIT", "dependencies": { "@anthropic-ai/sdk": "0.129.0", "@aws-sdk/client-bedrock-runtime": "3.1127.0", "@earendil-works/pi-schema": "1.5.2", "@earendil-works/pi-telemetry": "1.5.2", "@google/genai": "2.21.0", "@smithy/node-http-handler": "4.12.1", "http-proxy-agent": "9.1.0", "https-proxy-agent": "9.1.0", "openai": "7.19.0", "partial-json": "0.1.7" }, "bin": { "pi-ai": "dist/cli.js" }, "engines": { "node": ">=22.19.0" } }, "node_modules/@earendil-works/pi-codemode": { "version": "1.5.2", "resolved": "https://registry.npmjs.org/@earendil-works/pi-codemode/-/pi-codemode-1.5.2.tgz", "integrity": "sha512-HoZQ40a9RgdZ1VgmrX6x8887cNXedaRJT1l+Ie5YRIMK4gY7v0EpsiNqf6dmixrKylZlTgUSyR+vE8xhjfkr+w==", "license": "MIT", "dependencies": { "quickjs-wasi": "3.6.2" }, "engines": { "node": ">=22.19.0" } }, "node_modules/@earendil-works/pi-durable": { "version": "1.5.2", "resolved": "https://registry.npmjs.org/@earendil-works/pi-durable/-/pi-durable-1.5.2.tgz", "integrity": "sha512-zDB3anbI/yD0IG+VVY+g5tU+c5XOVqQAFwLkXRMiqZb4p/afWro0voZtLNoRAWcDA2r73kvmH6kKin9Ka8l55g==", "license": "MIT", "dependencies": { "@earendil-works/chord": "1.5.2", "@earendil-works/pi-ai": "1.5.2", "@earendil-works/pi-codemode": "1.5.2", "@earendil-works/pi-schema": "1.5.2", "@earendil-works/pi-telemetry": "1.5.2", "@silvia-odwyer/photon": "0.3.3", "diff": "8.0.4" }, "engines": { "node": ">=22.19.0" } }, "node_modules/@earendil-works/pi-schema": { "version": "1.5.2", "resolved": "https://registry.npmjs.org/@earendil-works/pi-schema/-/pi-schema-1.5.2.tgz", "integrity": "sha512-hJoyCXWUhsSrXY5wJo2Q4kHXUsR51pNhkJHAMkWRwVMLDRtMDPkKNaa+JlVRVqTw1hjdSxcVVaFLSDbKlaTXEQ==", "license": "MIT", "engines": { "node": ">=22.19.0" } }, "node_modules/@earendil-works/pi-telemetry": { "version": "1.5.2", "resolved": "https://registry.npmjs.org/@earendil-works/pi-telemetry/-/pi-telemetry-1.5.2.tgz", "integrity": "sha512-m+cumjIqNh1aMISi/9ttcG3ZOwIdriPbz/eMyWmRMJCGa/WcgY1RX4lrb7HvsHhSfI/JUeBESA4nOCr8C3y5ow==", "license": "MIT", "engines": { "node": ">=22.19.0" } }, "node_modules/@google/genai": { "version": "2.21.0", "resolved": "https://registry.npmjs.org/@google/genai/-/genai-2.21.0.tgz", "integrity": "sha512-+PDtco2/Z0ONdzCGekCoCT+O1VJS9xJQNN4XzQpXG/t3El/SWWMkCWlFRO1KmivOHPa4Q0VjUYu1HBKCZ/v33Q==", "hasInstallScript": true, "license": "Apache-2.0", "dependencies": { "google-auth-library": "^10.3.0", "p-retry": "^4.6.2", "protobufjs": "^7.5.4", "ws": "^8.18.0" }, "engines": { "node": ">=20.0.0" }, "peerDependencies": { "@modelcontextprotocol/sdk": "^1.25.2" }, "peerDependenciesMeta": { "@modelcontextprotocol/sdk": { "optional": true } } }, "node_modules/@protobufjs/aspromise": { "version": "1.1.2", "resolved": "https://registry.npmjs.org/@protobufjs/aspromise/-/aspromise-1.1.2.tgz", "integrity": "sha512-j+gKExEuLmKwvz3OgROXtrJ2UG2x8Ch2YZUxahh+s1F2HZ+wAceUNLkvy6zKCPVRkU++ZWQrdxsUeQXmcg4uoQ==", "license": "BSD-3-Clause" }, "node_modules/@protobufjs/base64": { "version": "1.1.2", "resolved": "https://registry.npmjs.org/@protobufjs/base64/-/base64-1.1.2.tgz", "integrity": "sha512-AZkcAA5vnN/v4PDqKyMR5lx7hZttPDgClv83E//FMNhR2TMcLUhfRUBHCmSl0oi9zMgDDqRUJkSxO3wm85+XLg==", "license": "BSD-3-Clause" }, "node_modules/@protobufjs/codegen": { "version": "2.0.5", "resolved": "https://registry.npmjs.org/@protobufjs/codegen/-/codegen-2.0.5.tgz", "integrity": "sha512-zgXFLzW3Ap33e6d0Wlj4MGIm6Ce8O89n/apUaGNB/jx+hw+ruWEp7EwGUshdLKVRCxZW12fp9r40E1mQrf/34g==", "license": "BSD-3-Clause" }, "node_modules/@protobufjs/eventemitter": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/@protobufjs/eventemitter/-/eventemitter-1.1.1.tgz", "integrity": "sha512-vW1GmwMZNnL+gMRaovlh9yZX74kc+TTU3FObkkurpMaRtBfLP3ldjS9KQWlwZgraRE0+dheEEoAxdzcJQ8eXZg==", "license": "BSD-3-Clause" }, "node_modules/@protobufjs/fetch": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/@protobufjs/fetch/-/fetch-1.1.1.tgz", "integrity": "sha512-GpptLrs57adMSuHi3VNj0mAF8dwh36LMaYF6XyJ6JMWlVsc+t42tm1HSEDmOs3A8fC9yyeisgLhsTVQokOZ0zw==", "license": "BSD-3-Clause", "dependencies": { "@protobufjs/aspromise": "^1.1.1" } }, "node_modules/@protobufjs/float": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/@protobufjs/float/-/float-1.0.2.tgz", "integrity": "sha512-Ddb+kVXlXst9d+R9PfTIxh1EdNkgoRe5tOX6t01f1lYWOvJnSPDBlG241QLzcyPdoNTsblLUdujGSE4RzrTZGQ==", "license": "BSD-3-Clause" }, "node_modules/@protobufjs/path": { "version": "1.1.2", "resolved": "https://registry.npmjs.org/@protobufjs/path/-/path-1.1.2.tgz", "integrity": "sha512-6JOcJ5Tm08dOHAbdR3GrvP+yUUfkjG5ePsHYczMFLq3ZmMkAD98cDgcT2iA1lJ9NVwFd4tH/iSSoe44YWkltEA==", "license": "BSD-3-Clause" }, "node_modules/@protobufjs/pool": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/@protobufjs/pool/-/pool-1.1.0.tgz", "integrity": "sha512-0kELaGSIDBKvcgS4zkjz1PeddatrjYcmMWOlAuAPwAeccUrPHdUqo/J6LiymHHEiJT5NrF1UVwxY14f+fy4WQw==", "license": "BSD-3-Clause" }, "node_modules/@protobufjs/utf8": { "version": "1.1.2", "resolved": "https://registry.npmjs.org/@protobufjs/utf8/-/utf8-1.1.2.tgz", "integrity": "sha512-b1UQwcEZ4yCnMCD8DAL1VlbvBJE9/IX4FTIp7BG1xYpf29SLazLSrqUkj4w7Y5y7cCVP6E5tcqqcI0xemPkHug==", "license": "BSD-3-Clause" }, "node_modules/@silvia-odwyer/photon": { "version": "0.3.3", "resolved": "https://registry.npmjs.org/@silvia-odwyer/photon/-/photon-0.3.3.tgz", "integrity": "sha512-8BhUjEch4slwRe8uXnaA4vcA5uiiOTT90UMsxulOj2gN98X1p0q9Z4Ysk4DkD05uNgbR9XoSqtZ37w+33w4QKQ==", "license": "Apache-2.0" }, "node_modules/@smithy/core": { "version": "3.40.0", "resolved": "https://registry.npmjs.org/@smithy/core/-/core-3.40.0.tgz", "integrity": "sha512-DssGno52pzZ5m6RlDtyKuBIpZNPg9pqgs0CnNDKz9IatxCsmvNmJNn5Zn6rf77MthZo9wf89OvZFhTY/RwxhxQ==", "license": "Apache-2.0", "dependencies": { "@smithy/types": "^4.20.0", "tslib": "^2.6.2" }, "engines": { "node": ">=18.0.0" } }, "node_modules/@smithy/credential-provider-imds": { "version": "4.5.2", "resolved": "https://registry.npmjs.org/@smithy/credential-provider-imds/-/credential-provider-imds-4.5.2.tgz", "integrity": "sha512-A9uSdn72ozbRUSit0eib0TW7nXuNPlaeM0zcGkJ+nE6tFcSDbnmtwoxbTCFBukVQcszDAyvsd7+rTduPTXpygg==", "license": "Apache-2.0", "dependencies": { "@smithy/core": "^3.33.2", "@smithy/types": "^4.17.2", "tslib": "^2.6.2" }, "engines": { "node": ">=18.0.0" } }, "node_modules/@smithy/fetch-http-handler": { "version": "5.8.1", "resolved": "https://registry.npmjs.org/@smithy/fetch-http-handler/-/fetch-http-handler-5.8.1.tgz", "integrity": "sha512-h8BdMUrUBhMhMaeK7QqAdINRZezCGuYOCpcOZZ1ewxbHST9rdTd09xwNpvLTYfzDRehxQiReK4SKbdYZxBA+ew==", "license": "Apache-2.0", "dependencies": { "@smithy/core": "^3.39.0", "@smithy/types": "^4.20.0", "tslib": "^2.6.2" }, "engines": { "node": ">=18.0.0" } }, "node_modules/@smithy/node-http-handler": { "version": "4.12.1", "resolved": "https://registry.npmjs.org/@smithy/node-http-handler/-/node-http-handler-4.12.1.tgz", "integrity": "sha512-ThMkboGeONWXAelq9FvGsuJC4rOi+qyC4/zhUF58xYpxUg5sQKx2VXZYJmtNjr4dSuBJ1HeJXETQILCz3wOHvw==", "license": "Apache-2.0", "dependencies": { "@smithy/core": "^3.33.3", "@smithy/types": "^4.18.0", "tslib": "^2.6.2" }, "engines": { "node": ">=18.0.0" } }, "node_modules/@smithy/signature-v4": { "version": "5.7.5", "resolved": "https://registry.npmjs.org/@smithy/signature-v4/-/signature-v4-5.7.5.tgz", "integrity": "sha512-WPjdr5oWOk1LArpI4pavu+fSo+/evi0Re1olxGvqwuZopd4gYR1UGCi+Soyn/IjmafqbWs+ZC+3AKxJS3ZpwUg==", "license": "Apache-2.0", "dependencies": { "@smithy/core": "^3.38.0", "@smithy/types": "^4.19.0", "tslib": "^2.6.2" }, "engines": { "node": ">=18.0.0" } }, "node_modules/@smithy/types": { "version": "4.20.0", "resolved": "https://registry.npmjs.org/@smithy/types/-/types-4.20.0.tgz", "integrity": "sha512-lCA6QG22dPk9ecHbv91jDQZsmtPUjdS1aE2Il6NNPqe7DrYc0dZQi6DhcESk2KYXH2sp5xbAcGdYMZDFnuzA2A==", "license": "Apache-2.0", "dependencies": { "tslib": "^2.6.2" }, "engines": { "node": ">=18.0.0" } }, "node_modules/@stablelib/base64": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/@stablelib/base64/-/base64-1.0.1.tgz", "integrity": "sha512-1bnPQqSxSuc3Ii6MhBysoWCg58j97aUjuCSZrGSmDxNqtytIi0k8utUenAwTZN4V5mXXYGsVUI9zeBqy+jBOSQ==", "license": "MIT" }, "node_modules/@types/node": { "version": "26.6.6", "resolved": "https://registry.npmjs.org/@types/node/-/node-26.6.6.tgz", "integrity": "sha512-MzQj+8Kx3XI40OmUAE6Qoh58ZMNstNNMwn2nfd3qWsfe7nDNSqJNzes4njhz6AHwrSHOffSLwXU6yb474Q4aog==", "license": "MIT", "dependencies": { "undici-types": "~8.9.0" } }, "node_modules/@types/retry": { "version": "0.12.0", "resolved": "https://registry.npmjs.org/@types/retry/-/retry-0.12.0.tgz", "integrity": "sha512-wWKOClTTiizcZhXnPY4wikVAwmdYHp8q6DmC+EJUzAMsycb7HB32Kh9RN4+0gExjmPmZSAQjgURXIGATPegAvA==", "license": "MIT" }, "node_modules/agent-base": { "version": "9.0.0", "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-9.0.0.tgz", "integrity": "sha512-TQf59BsZnytt8GdJKLPfUZ54g/iaUL2OWDSFCCvMOhsHduDQxO8xC4PNeyIkVcA5KwL2phPSv0douC0fgWzmnA==", "license": "MIT", "engines": { "node": ">= 20" } }, "node_modules/base64-js": { "version": "1.5.1", "resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz", "integrity": "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==", "funding": [ { "type": "github", "url": "https://github.com/sponsors/feross" }, { "type": "patreon", "url": "https://www.patreon.com/feross" }, { "type": "consulting", "url": "https://feross.org/support" } ], "license": "MIT" }, "node_modules/bignumber.js": { "version": "9.3.1", "resolved": "https://registry.npmjs.org/bignumber.js/-/bignumber.js-9.3.1.tgz", "integrity": "sha512-Ko0uX15oIUS7wJ3Rb30Fs6SkVbLmPBAKdlm7q9+ak9bbIeFf0MwuBsQV6z7+X768/cHsfg+WlysDWJcmthjsjQ==", "license": "MIT", "engines": { "node": "*" } }, "node_modules/bowser": { "version": "2.15.0", "resolved": "https://registry.npmjs.org/bowser/-/bowser-2.15.0.tgz", "integrity": "sha512-xic6KSZglg/I4ymp45fdM4GWfYpBK79Fxd/TOvJktlaPgQqqDxvmGwOPZl2V0dyeS3Lj5c180bLhXF43iyAjZQ==", "license": "MIT" }, "node_modules/buffer-equal-constant-time": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/buffer-equal-constant-time/-/buffer-equal-constant-time-1.0.1.tgz", "integrity": "sha512-zRpUiDwd/xk6ADqPMATG8vc9VPrkck7T07OIx0gnjmJAnHnTVXNQG3vfvWNuiZIkwu9KrKdA1iJKfsfTVxE6NA==", "license": "BSD-3-Clause" }, "node_modules/data-uri-to-buffer": { "version": "4.0.1", "resolved": "https://registry.npmjs.org/data-uri-to-buffer/-/data-uri-to-buffer-4.0.1.tgz", "integrity": "sha512-0R9ikRb668HB7QDxT1vkpuUBtqc53YyAwMwGeUFKRojY/NWKvdZ+9UYtRfGmhqNbRkTSVpMbmyhXipFFv2cb/A==", "license": "MIT", "engines": { "node": ">= 12" } }, "node_modules/debug": { "version": "4.4.3", "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", "license": "MIT", "dependencies": { "ms": "^2.1.3" }, "engines": { "node": ">=6.0" }, "peerDependenciesMeta": { "supports-color": { "optional": true } } }, "node_modules/diff": { "version": "8.0.4", "resolved": "https://registry.npmjs.org/diff/-/diff-8.0.4.tgz", "integrity": "sha512-DPi0FmjiSU5EvQV0++GFDOJ9ASQUVFh5kD+OzOnYdi7n3Wpm9hWWGfB/O2blfHcMVTL5WkQXSnRiK9makhrcnw==", "license": "BSD-3-Clause", "engines": { "node": ">=0.3.1" } }, "node_modules/ecdsa-sig-formatter": { "version": "1.0.11", "resolved": "https://registry.npmjs.org/ecdsa-sig-formatter/-/ecdsa-sig-formatter-1.0.11.tgz", "integrity": "sha512-nagl3RYrbNv6kQkeJIpt6NJZy8twLB/2vtz6yN9Z4vRKHN4/QZJIEbqohALSgwKdnksuY3k5Addp5lg8sVoVcQ==", "license": "Apache-2.0", "dependencies": { "safe-buffer": "^5.0.1" } }, "node_modules/extend": { "version": "3.0.2", "resolved": "https://registry.npmjs.org/extend/-/extend-3.0.2.tgz", "integrity": "sha512-fjquC59cD7CyW6urNXK0FBufkZcoiGG80wTuPujX590cB5Ttln20E2UB4S/WARVqhXffZl2LNgS+gQdPIIim/g==", "license": "MIT" }, "node_modules/fast-sha256": { "version": "1.3.0", "resolved": "https://registry.npmjs.org/fast-sha256/-/fast-sha256-1.3.0.tgz", "integrity": "sha512-n11RGP/lrWEFI/bWdygLxhI+pVeo1ZYIVwvvPkW7azl/rOy+F3HYRZ2K5zeE9mmkhQppyv9sQFx0JM9UabnpPQ==", "license": "Unlicense" }, "node_modules/fetch-blob": { "version": "3.2.0", "resolved": "https://registry.npmjs.org/fetch-blob/-/fetch-blob-3.2.0.tgz", "integrity": "sha512-7yAQpD2UMJzLi1Dqv7qFYnPbaPx7ZfFK6PiIxQ4PfkGPyNyl2Ugx+a/umUonmKqjhM4DnfbMvdX6otXq83soQQ==", "funding": [ { "type": "github", "url": "https://github.com/sponsors/jimmywarting" }, { "type": "paypal", "url": "https://paypal.me/jimmywarting" } ], "license": "MIT", "dependencies": { "node-domexception": "^1.0.0", "web-streams-polyfill": "^3.0.3" }, "engines": { "node": "^12.20 || >= 14.13" } }, "node_modules/formdata-polyfill": { "version": "4.0.10", "resolved": "https://registry.npmjs.org/formdata-polyfill/-/formdata-polyfill-4.0.10.tgz", "integrity": "sha512-buewHzMvYL29jdeQTVILecSaZKnt/RJWjoZCF5OW60Z67/GmSLBkOFM7qh1PI3zFNtJbaZL5eQu1vLfazOwj4g==", "license": "MIT", "dependencies": { "fetch-blob": "^3.1.2" }, "engines": { "node": ">=12.20.0" } }, "node_modules/gaxios": { "version": "7.3.1", "resolved": "https://registry.npmjs.org/gaxios/-/gaxios-7.3.1.tgz", "integrity": "sha512-kB3rzJV7d9juLZh8/56QTXCwQfxyhdOMdyYk1HdQKFtF8TJTDTZQJtixWIwXdE9Jji91mC41DUNpjleo4L4eAQ==", "license": "Apache-2.0", "dependencies": { "extend": "^3.0.2", "https-proxy-agent": "^7.0.1", "node-fetch": "^3.3.2" }, "engines": { "node": ">=18" } }, "node_modules/gaxios/node_modules/agent-base": { "version": "7.1.4", "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-7.1.4.tgz", "integrity": "sha512-MnA+YT8fwfJPgBx3m60MNqakm30XOkyIoH1y6huTQvC0PwZG7ki8NacLBcrPbNoo8vEZy7Jpuk7+jMO+CUovTQ==", "license": "MIT", "engines": { "node": ">= 14" } }, "node_modules/gaxios/node_modules/https-proxy-agent": { "version": "7.0.6", "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-7.0.6.tgz", "integrity": "sha512-vK9P5/iUfdl95AI+JVyUuIcVtd4ofvtrOr3HNtM2yxC9bnMbEdp3x01OhQNnjb8IJYi38VlTE3mBXwcfvywuSw==", "license": "MIT", "dependencies": { "agent-base": "^7.1.2", "debug": "4" }, "engines": { "node": ">= 14" } }, "node_modules/gcp-metadata": { "version": "8.1.2", "resolved": "https://registry.npmjs.org/gcp-metadata/-/gcp-metadata-8.1.2.tgz", "integrity": "sha512-zV/5HKTfCeKWnxG0Dmrw51hEWFGfcF2xiXqcA3+J90WDuP0SvoiSO5ORvcBsifmx/FoIjgQN3oNOGaQ5PhLFkg==", "license": "Apache-2.0", "dependencies": { "gaxios": "^7.0.0", "google-logging-utils": "^1.0.0", "json-bigint": "^1.0.0" }, "engines": { "node": ">=18" } }, "node_modules/google-auth-library": { "version": "10.9.1", "resolved": "https://registry.npmjs.org/google-auth-library/-/google-auth-library-10.9.1.tgz", "integrity": "sha512-i1ydyHrqcIxXkWh/uBmVkzCvIuq5yiK2ATndIe5XxKholrG/MTYP9xGYka4sQhrbIAgGjL2B6NOE7rFaiF3fXw==", "license": "Apache-2.0", "dependencies": { "base64-js": "^1.3.0", "ecdsa-sig-formatter": "^1.0.11", "gaxios": "^7.1.4", "gcp-metadata": "8.1.2", "google-logging-utils": "1.1.3", "jws": "^4.0.0" }, "engines": { "node": ">=18" } }, "node_modules/google-logging-utils": { "version": "1.1.3", "resolved": "https://registry.npmjs.org/google-logging-utils/-/google-logging-utils-1.1.3.tgz", "integrity": "sha512-eAmLkjDjAFCVXg7A1unxHsLf961m6y17QFqXqAXGj/gVkKFrEICfStRfwUlGNfeCEjNRa32JEWOUTlYXPyyKvA==", "license": "Apache-2.0", "engines": { "node": ">=14" } }, "node_modules/http-proxy-agent": { "version": "9.1.0", "resolved": "https://registry.npmjs.org/http-proxy-agent/-/http-proxy-agent-9.1.0.tgz", "integrity": "sha512-2NxoveTT58mjYT4n3RPTEfCZGLMbidoO8XEieXfpSYxu+PQJ1qpx4ypwH6N+uF9twBPIvRRgvkvW5HUTYWENig==", "license": "MIT", "dependencies": { "agent-base": "9.0.0", "debug": "^4.3.4", "proxy-agent-negotiate": "1.1.0" }, "engines": { "node": ">= 20" } }, "node_modules/https-proxy-agent": { "version": "9.1.0", "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-9.1.0.tgz", "integrity": "sha512-ag87y7cJJ9/3+GxFr8Oy4O5faDsGRGnBGsJj/YjOSsSx/5eadKLYTMPlzuR6obgoCDDm0abAAZitXXQkMOPSpA==", "license": "MIT", "dependencies": { "agent-base": "9.0.0", "debug": "^4.3.4", "proxy-agent-negotiate": "1.1.0" }, "engines": { "node": ">= 20" } }, "node_modules/json-bigint": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/json-bigint/-/json-bigint-1.0.0.tgz", "integrity": "sha512-SiPv/8VpZuWbvLSMtTDU8hEfrZWg/mH/nV/b4o0CYbSxu1UIQPLdwKOCIyLQX+VIPO5vrLX3i8qtqFyhdPSUSQ==", "license": "MIT", "dependencies": { "bignumber.js": "^9.0.0" } }, "node_modules/json-schema-to-ts": { "version": "3.1.1", "resolved": "https://registry.npmjs.org/json-schema-to-ts/-/json-schema-to-ts-3.1.1.tgz", "integrity": "sha512-+DWg8jCJG2TEnpy7kOm/7/AxaYoaRbjVB4LFZLySZlWn8exGs3A4OLJR966cVvU26N7X9TWxl+Jsw7dzAqKT6g==", "license": "MIT", "dependencies": { "@babel/runtime": "^7.18.3", "ts-algebra": "^2.0.0" }, "engines": { "node": ">=16" } }, "node_modules/jwa": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/jwa/-/jwa-2.0.1.tgz", "integrity": "sha512-hRF04fqJIP8Abbkq5NKGN0Bbr3JxlQ+qhZufXVr0DvujKy93ZCbXZMHDL4EOtodSbCWxOqR8MS1tXA5hwqCXDg==", "license": "MIT", "dependencies": { "buffer-equal-constant-time": "^1.0.1", "ecdsa-sig-formatter": "1.0.11", "safe-buffer": "^5.0.1" } }, "node_modules/jws": { "version": "4.0.1", "resolved": "https://registry.npmjs.org/jws/-/jws-4.0.1.tgz", "integrity": "sha512-EKI/M/yqPncGUUh44xz0PxSidXFr/+r0pA70+gIYhjv+et7yxM+s29Y+VGDkovRofQem0fs7Uvf4+YmAdyRduA==", "license": "MIT", "dependencies": { "jwa": "^2.0.1", "safe-buffer": "^5.0.1" } }, "node_modules/long": { "version": "5.3.2", "resolved": "https://registry.npmjs.org/long/-/long-5.3.2.tgz", "integrity": "sha512-mNAgZ1GmyNhD7AuqnTG3/VQ26o760+ZYBPKjPvugO8+nLbYfX6TVpJPseBvopbdY+qpZ/lKUnmEc1LeZYS3QAA==", "license": "Apache-2.0" }, "node_modules/ms": { "version": "2.1.3", "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", "license": "MIT" }, "node_modules/node-domexception": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/node-domexception/-/node-domexception-1.0.0.tgz", "integrity": "sha512-/jKZoMpw0F8GRwl4/eLROPA3cfcXtLApP0QzLmUT/HuPCZWyB7IY9ZrMeKw2O/nFIqPQB3PVM9aYm0F312AXDQ==", "deprecated": "Use your platform's native DOMException instead", "funding": [ { "type": "github", "url": "https://github.com/sponsors/jimmywarting" }, { "type": "github", "url": "https://paypal.me/jimmywarting" } ], "license": "MIT", "engines": { "node": ">=10.5.0" } }, "node_modules/node-fetch": { "version": "3.3.2", "resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-3.3.2.tgz", "integrity": "sha512-dRB78srN/l6gqWulah9SrxeYnxeddIG30+GOqK/9OlLVyLg3HPnr6SqOWTWOXKRwC2eGYCkZ59NNuSgvSrpgOA==", "license": "MIT", "dependencies": { "data-uri-to-buffer": "^4.0.0", "fetch-blob": "^3.1.4", "formdata-polyfill": "^4.0.10" }, "engines": { "node": "^12.20.0 || ^14.13.1 || >=16.0.0" }, "funding": { "type": "opencollective", "url": "https://opencollective.com/node-fetch" } }, "node_modules/openai": { "version": "7.19.0", "resolved": "https://registry.npmjs.org/openai/-/openai-7.19.0.tgz", "integrity": "sha512-MX2s3u2L5racTO0CC/SWpCOasJQBCJrqLKXK+l82cAhdeF8mPMBEe/gxMm0ZFa2xpKpOFLRjxv5afYEZbBXmbQ==", "license": "Apache-2.0", "engines": { "node": ">=22.0.0" }, "peerDependencies": { "@aws-sdk/credential-provider-node": ">=3.972.0 <4", "@smithy/hash-node": ">=4.3.0 <5", "@smithy/signature-v4": ">=5.4.0 <6", "undici": ">=5 <9", "ws": "^8.21.0", "zod": "^3.25 || ^4.0" }, "peerDependenciesMeta": { "@aws-sdk/credential-provider-node": { "optional": true }, "@smithy/hash-node": { "optional": true }, "@smithy/signature-v4": { "optional": true }, "undici": { "optional": true }, "ws": { "optional": true }, "zod": { "optional": true } } }, "node_modules/p-retry": { "version": "4.6.2", "resolved": "https://registry.npmjs.org/p-retry/-/p-retry-4.6.2.tgz", "integrity": "sha512-312Id396EbJdvRONlngUx0NydfrIQ5lsYu0znKVUzVvArzEIt08V1qhtyESbGVd1FGX7UKtiFp5uwKZdM8wIuQ==", "license": "MIT", "dependencies": { "@types/retry": "0.12.0", "retry": "^0.13.1" }, "engines": { "node": ">=8" } }, "node_modules/partial-json": { "version": "0.1.7", "resolved": "https://registry.npmjs.org/partial-json/-/partial-json-0.1.7.tgz", "integrity": "sha512-Njv/59hHaokb/hRUjce3Hdv12wd60MtM9Z5Olmn+nehe0QDAsRtRbJPvJ0Z91TusF0SuZRIvnM+S4l6EIP8leA==", "license": "MIT" }, "node_modules/protobufjs": { "version": "7.6.6", "resolved": "https://registry.npmjs.org/protobufjs/-/protobufjs-7.6.6.tgz", "integrity": "sha512-dYDWdjSl5RNb7SgPxGQcRU+GtvP7s2fpkrY0r432PcOIaZ0/rBcxEZnQN67iJhFuQiVw754JDoPruPCNdGsbjg==", "hasInstallScript": true, "license": "BSD-3-Clause", "dependencies": { "@protobufjs/aspromise": "^1.1.2", "@protobufjs/base64": "^1.1.2", "@protobufjs/codegen": "^2.0.5", "@protobufjs/eventemitter": "^1.1.1", "@protobufjs/fetch": "^1.1.1", "@protobufjs/float": "^1.0.2", "@protobufjs/path": "^1.1.2", "@protobufjs/pool": "^1.1.0", "@protobufjs/utf8": "^1.1.1", "@types/node": ">=13.7.0", "long": "^5.3.2" }, "engines": { "node": ">=12.0.0" } }, "node_modules/proxy-agent-negotiate": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/proxy-agent-negotiate/-/proxy-agent-negotiate-1.1.0.tgz", "integrity": "sha512-N8IBcM3UgCVzz2L2Lqv8DVntDnnC8/hiV4nEDUPkqq72TPUgYWjQc+bdZlBPZK9LzPAvOY//gAt0S0DApoOXWQ==", "license": "MIT", "engines": { "node": ">= 20" }, "peerDependencies": { "kerberos": "^2.0.0" }, "peerDependenciesMeta": { "kerberos": { "optional": true } } }, "node_modules/quickjs-wasi": { "version": "3.6.2", "resolved": "https://registry.npmjs.org/quickjs-wasi/-/quickjs-wasi-3.6.2.tgz", "integrity": "sha512-FCqGtGOrMgzUiIrMNMA2YnsOxCNwo31dzqXvclXUC6xeT35NJLKXQJsvbeCTjvoFAwZgEAPg8U6+KAPDGXn8Mg==", "license": "MIT" }, "node_modules/retry": { "version": "0.13.1", "resolved": "https://registry.npmjs.org/retry/-/retry-0.13.1.tgz", "integrity": "sha512-XQBQ3I8W1Cge0Seh+6gjj03LbmRFWuoszgK9ooCpwYIrhhoO80pfq4cUkU5DkknwfOfFteRwlZ56PYOGYyFWdg==", "license": "MIT", "engines": { "node": ">= 4" } }, "node_modules/safe-buffer": { "version": "5.2.1", "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz", "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==", "funding": [ { "type": "github", "url": "https://github.com/sponsors/feross" }, { "type": "patreon", "url": "https://www.patreon.com/feross" }, { "type": "consulting", "url": "https://feross.org/support" } ], "license": "MIT" }, "node_modules/standardwebhooks": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/standardwebhooks/-/standardwebhooks-1.1.1.tgz", "integrity": "sha512-bCbX9ZEyFkWPsRz7Bl3NuQUJohmwGSev/yhr7vhaGPlc4AfIrspIRa6cPTBuI1ItmrTDJ4d/S2hCsfe4+vQGnQ==", "license": "MIT", "dependencies": { "@stablelib/base64": "^1.0.0", "fast-sha256": "^1.3.0" } }, "node_modules/ts-algebra": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/ts-algebra/-/ts-algebra-2.0.0.tgz", "integrity": "sha512-FPAhNPFMrkwz76P7cdjdmiShwMynZYN6SgOujD1urY4oNm80Ou9oMdmbR45LotcKOXoy7wSmHkRFE6Mxbrhefw==", "license": "MIT" }, "node_modules/tslib": { "version": "2.9.1", "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.9.1.tgz", "integrity": "sha512-a4Ux9VKuIMHsOS7ENbEq6hK2ZGYIT27Rtl0E4eD9KqwxhKiQeMZE/9xb3IdYwWaSOyIBQLExhQgXDTYoiCxnWA==", "license": "0BSD" }, "node_modules/undici-types": { "version": "8.9.0", "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-8.9.0.tgz", "integrity": "sha512-KTDyRTYX8sWmKXAikPHHSyc63CRPETMctyjKFupcC6OBLXT3xsN0e9aF7m+mIXutFWpUXuedtowG7iLOzp0kQg==", "license": "MIT" }, "node_modules/web-streams-polyfill": { "version": "3.3.3", "resolved": "https://registry.npmjs.org/web-streams-polyfill/-/web-streams-polyfill-3.3.3.tgz", "integrity": "sha512-d2JWLCivmZYTSIoge9MsgFCZrt571BikcWGYkjC1khllbTeDlGqZ2D8vD8E/lJa8WGWbb7Plm8/XJYV7IJHZZw==", "license": "MIT", "engines": { "node": ">= 8" } }, "node_modules/ws": { "version": "8.21.0", "resolved": "https://registry.npmjs.org/ws/-/ws-8.21.0.tgz", "integrity": "sha512-Vsp28b7DRcimFQvrqu2Wek3z1iYxDCWqHYB8Qsnk/S4RfaCQzPGPyBNuVjJV3cd6UiKtUtp6sNM77gWvzcCH+g==", "license": "MIT", "engines": { "node": ">=10.0.0" }, "peerDependencies": { "bufferutil": "^4.0.1", "utf-8-validate": ">=5.0.2" }, "peerDependenciesMeta": { "bufferutil": { "optional": true }, "utf-8-validate": { "optional": true } } } }}neovim/pivi/package.json
Addednew file mode 100644+18 / −0 text lines
{ "name": "pivi", "private": true, "type": "module", "engines": { "node": ">=22.19.0" }, "scripts": { "test": "node --test test/*.test.mjs" }, "dependencies": { "@earendil-works/pi-durable": "1.5.2", "@earendil-works/pi-ai": "1.5.2", "@earendil-works/pi-codemode": "1.5.2", "@earendil-works/pi-schema": "1.5.2", "@earendil-works/chord": "1.5.2" }}neovim/pivi/test/credentials.test.mjs
Addednew file mode 100644+49 / −0 text lines
import assert from 'node:assert/strict';import { mkdtemp, readFile, rm, stat } from 'node:fs/promises';import { tmpdir } from 'node:os';import { join } from 'node:path';import test from 'node:test';import { fileCredentials } from '../credentials.mjs';async function temporary(t) { const directory = await mkdtemp(join(tmpdir(), 'pivi-auth-')); t.after(() => rm(directory, { recursive: true, force: true })); return join(directory, 'state', 'auth.json');}test('credentials persist privately and are visible to another store on the same file', async (t) => { const path = await temporary(t); const store = fileCredentials(path); assert.equal(await store.read('a'), undefined); assert.deepEqual(await store.list(), []); await store.modify('a', async () => ({ type: 'api_key', key: 'secret' })); assert.equal((await stat(path)).mode & 0o777, 0o600); const other = fileCredentials(path); assert.deepEqual(await other.read('a'), { type: 'api_key', key: 'secret' }); assert.deepEqual(await other.list(), [{ providerId: 'a', type: 'api_key' }]); assert.deepEqual(await other.modify('a', async () => undefined), { type: 'api_key', key: 'secret' }); await other.delete('a'); assert.equal(await store.read('a'), undefined); assert.deepEqual(JSON.parse(await readFile(path, 'utf8')), {});});test('concurrent writers through separate stores never lose an update', async (t) => { const path = await temporary(t); const stores = [fileCredentials(path), fileCredentials(path), fileCredentials(path)]; const bump = (store) => store.modify('counter', async (current) => { await new Promise((resolve) => setTimeout(resolve, 2)); return { type: 'api_key', key: String(Number(current?.key ?? 0) + 1) }; }); await Promise.all(Array.from({ length: 30 }, (_, index) => bump(stores[index % stores.length]))); assert.equal((await stores[0].read('counter')).key, '30');});test('a failing change leaves the stored credential and the lock untouched', async (t) => { const path = await temporary(t); const store = fileCredentials(path); await store.modify('a', async () => ({ type: 'api_key', key: 'kept' })); await assert.rejects(store.modify('a', async () => { throw new Error('refresh failed'); }), /refresh failed/); assert.equal((await store.read('a')).key, 'kept'); await store.modify('a', async () => ({ type: 'api_key', key: 'next' })); assert.equal((await store.read('a')).key, 'next');});neovim/pivi/test/editor_config.mjs
Addednew file mode 100644+45 / −0 text lines
import { createModels } from '@earendil-works/pi-ai/models';import { fauxProvider, fauxAssistantMessage, fauxToolCall } from '@earendil-works/pi-ai/providers/faux';import { gatedProvider } from './gated.mjs';export default function ({ credentials }) { const faux = fauxProvider({ provider: 'pivi-test', models: [{ id: 'editor' }, { id: 'recovered' }], tokensPerSecond: Number(process.env.PIVI_TEST_STREAMING) || Infinity, }); const models = createModels({ credentials }); models.setProvider(faux.provider); models.setProvider(gatedProvider()); const respond = (transcript, options, state, model) => { if (model.id === 'recovered') return fauxAssistantMessage('Recovered without resubmitting the prompt'); const last = transcript.messages.at(-1); if (last?.role === 'toolResult') { return fauxAssistantMessage('Observed live editor: ' + last.content.map((item) => item.text ?? '').join('')); } const text = typeof last?.content === 'string' ? last.content : JSON.stringify(last?.content); if (text?.includes('worker-crash')) process.exit(23); if (text?.includes('provider-throttled')) { return fauxAssistantMessage('', { stopReason: 'error', errorMessage: '429 rate limit exceeded: retry later' }); } if (text?.includes('provider-denied')) { return fauxAssistantMessage('Partial response retained', { stopReason: 'error', errorMessage: '401 invalid_api_key: test credential rejected', }); } if (text?.includes('broken-tool')) { return fauxAssistantMessage(fauxToolCall('nvim_lua', { code: 'error("fixture tool failed")' }), { stopReason: 'toolUse', }); } if (text?.includes('slow')) { const call = fauxToolCall('nvim_lua', { code: 'return system("sleep 33.3; echo never")' }); return fauxAssistantMessage(call, { stopReason: 'toolUse' }); } const code = text?.includes('mutate') ? 'vim.api.nvim_buf_set_lines(vim.g.pivi_test_buffer, 0, 1, false, {"agent edit"}); return "edited"' : 'return table.concat(vim.api.nvim_buf_get_lines(vim.g.pivi_test_buffer, 0, -1, false), "\\n")'; return fauxAssistantMessage(fauxToolCall('nvim_lua', { code }), { stopReason: 'toolUse' }); }; faux.setResponses(Array(100).fill(respond)); return { models };}neovim/pivi/test/gated.mjs
Addednew file mode 100644+30 / −0 text lines
import { fauxProvider } from '@earendil-works/pi-ai/providers/faux';export function gatedProvider() { const { provider } = fauxProvider({ provider: 'gated', models: [{ id: 'locked' }] }); return { ...provider, name: 'Gated Test', auth: { apiKey: { name: 'Gated API key', login: async (interaction) => ({ type: 'api_key', key: await interaction.prompt({ type: 'secret', message: 'Gated API key' }), }), resolve: async ({ credential }) => credential?.key ? { auth: { apiKey: credential.key }, source: 'stored key' } : undefined, }, oauth: { name: 'Gated account', async login(interaction) { interaction.notify({ type: 'auth_url', url: 'https://example.test/authorize?state=1' }); const code = await interaction.prompt({ type: 'manual_code', message: 'Paste the code' }); return { type: 'oauth', access: code, refresh: 'refresh', expires: Date.now() + 3_600_000 }; }, refresh: async (credential) => credential, toAuth: async (credential) => ({ apiKey: credential.access }), }, }, };}neovim/pivi/test/harness.test.mjs
Addednew file mode 100644+237 / −0 text lines
import assert from 'node:assert/strict';import { existsSync } from 'node:fs';import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';import { tmpdir } from 'node:os';import { join } from 'node:path';import test from 'node:test';import { BACKGROUND_CONTEXT as context } from '@earendil-works/chord/context';import { createModels } from '@earendil-works/pi-ai/models';import { LiveDoc } from '@earendil-works/pi-durable';import { fauxProvider, fauxAssistantMessage, fauxToolCall } from '@earendil-works/pi-ai/providers/faux';import { fileCredentials } from '../credentials.mjs';import { openPivi } from '../harness.mjs';import { gatedProvider } from './gated.mjs';async function fixture(t, editor = async () => ({ text: 'unsaved buffer' }), cwd = undefined) { const directory = await mkdtemp(join(tmpdir(), 'pivi-test-')); const faux = fauxProvider({ models: [{ id: 'test' }], tokensPerSecond: Infinity }); const models = createModels(); models.setProvider(faux.provider); let runtime; const reopen = async () => { runtime = await openPivi({ database: join(directory, 'session.sqlite'), models, editor, cwd }); return runtime; }; t.after(async () => { if (runtime) await runtime.close(); await rm(directory, { recursive: true, force: true }); }); await reopen(); const model = faux.getModel(); await runtime.commands.configure({ model: { provider: model.provider, modelId: model.id } }); return { runtime, faux, reopen };}test('only editor tools and codemode are enabled; direct editor effects reach model', async (t) => { const codes = []; const editor = async (name, { code }) => { codes.push([name, code]); return { text: 'unsaved' }; }; const { runtime, faux } = await fixture(t, editor); const agent = await runtime.conversation.agent(context); assert.deepEqual(agent.tools.map((tool) => tool.name).sort(), [ 'codemode', 'diagnostics', 'edit', 'lsp', 'nvim_lua', 'read', 'save', 'write', ]); faux.setResponses([ fauxAssistantMessage( fauxToolCall('nvim_lua', { code: 'return vim.api.nvim_get_current_buf()' }), { stopReason: 'toolUse' }, ), fauxAssistantMessage('Read unsaved content.'), ]); const accepted = await runtime.commands.submit({ content: 'Inspect buffer' }); await runtime.conversation.waitForIdle(context); const settled = await (await runtime.harness.submission(accepted.id, context)).wait(context); assert.equal(settled.status, 'done'); assert.equal(codes.length, 1); const transcript = await runtime.conversation.context(context); assert.ok(transcript.messages.some((message) => message.role === 'toolResult' && message.content.some((block) => block.text === 'unsaved')));});test('failed compaction retains history and clears its failure only after a successful retry', async (t) => { const { runtime, faux } = await fixture(t); await runtime.conversation.configure({ compaction: { keepRecentTokens: 10, reserveTokens: 128 } }, context); faux.setResponses([fauxAssistantMessage('first answer '.repeat(40)), fauxAssistantMessage('second answer '.repeat(40))]); for (const content of ['first prompt', 'second prompt']) { await runtime.commands.submit({ content }); await runtime.conversation.waitForIdle(context); } const before = (await runtime.conversation.context(context)).entries; faux.setResponses([fauxAssistantMessage('', { stopReason: 'error', errorMessage: '401 compaction credential rejected' })]); let task = await runtime.conversation.compact(undefined, context); await runtime.harness.waitForTask(task, context); let live = await runtime.harness.snapshot(LiveDoc, runtime.conversation.id, context); assert.match(live.compactionFailure.error, /401 compaction credential rejected/); assert.deepEqual((await runtime.conversation.context(context)).entries, before); faux.setResponses([fauxAssistantMessage('Summary of first exchange.')]); task = await runtime.conversation.compact(undefined, context); await runtime.harness.waitForTask(task, context); live = await runtime.harness.snapshot(LiveDoc, runtime.conversation.id, context); assert.equal(live.compactionFailure, undefined); assert.ok((await runtime.conversation.context(context)).entries.some((entry) => entry.kind === 'pi.compaction'));});test('codemode invokes same editor capability', async (t) => { let calls = 0; const { runtime, faux } = await fixture(t, async () => { calls++; return { text: 'live' }; }); faux.setResponses([ fauxAssistantMessage( fauxToolCall('codemode', { code: 'text(await tools.nvim_lua({code: "return 42"}));' }), { stopReason: 'toolUse' }, ), fauxAssistantMessage('Done.'), ]); await runtime.commands.submit({ content: 'Inspect through codemode' }); await runtime.conversation.waitForIdle(context); assert.equal(calls, 1); const { messages } = await runtime.conversation.context(context); const result = messages.find((message) => message.role === 'toolResult'); assert.equal(result.isError, false);});test('new and fork stay in same storage; active conversation survives reopen', async (t) => { const { runtime, faux, reopen } = await fixture(t); faux.setResponses([fauxAssistantMessage('First answer.')]); await runtime.commands.submit({ content: 'First question' }); await runtime.conversation.waitForIdle(context); const first = runtime.conversation.id; const { entries } = await runtime.conversation.context(context); const user = entries.find((entry) => entry.kind === 'pi.user'); await runtime.commands.fork({ entry: user.id }); const fork = runtime.conversation.id; assert.notEqual(fork, first); assert.equal((await runtime.conversation.context(context)).messages.at(-1).role, 'user'); await runtime.close(); const restored = await reopen(); assert.equal(restored.conversation.id, fork); await restored.commands.new(); assert.notEqual(restored.conversation.id, fork); assert.equal((await restored.conversation.context(context)).messages.length, 0);});test('sign-in unlocks a provider, survives reopen, can be cancelled, and sign-out locks it again', async (t) => { const directory = await mkdtemp(join(tmpdir(), 'pivi-test-')); const credentials = fileCredentials(join(directory, 'auth.json')); const models = createModels({ credentials }); models.setProvider(gatedProvider()); const events = []; let prompts = 0; const interact = { notify: (event) => events.push(event.type), prompt: ({ type, signal }) => { prompts++; if (type === 'secret') return Promise.resolve('secret-key'); return new Promise((_, reject) => signal.addEventListener('abort', () => reject(new Error('cancelled')))); }, }; const database = join(directory, 'session.sqlite'); const open = () => openPivi({ database, credentials, models, interact, editor() {} }); let runtime = await open(); t.after(async () => { await runtime.close(); await rm(directory, { recursive: true, force: true }); }); const gated = async () => (await runtime.immediate.providers()).find((provider) => provider.id === 'gated'); assert.deepEqual((await gated()).methods.map((method) => method.type), ['oauth', 'api_key']); assert.equal((await gated()).stored, undefined); assert.deepEqual(await runtime.commands.models(), []); const pending = runtime.immediate.login({ provider: 'gated', method: 'oauth' }); await assert.rejects(runtime.immediate.login({ provider: 'gated', method: 'api_key' }), /in progress/); while (prompts === 0) await new Promise((resolve) => setTimeout(resolve, 5)); await runtime.immediate.cancel(); await assert.rejects(pending); assert.deepEqual(events, ['auth_url']); assert.equal((await gated()).stored, undefined); await runtime.immediate.login({ provider: 'gated', method: 'api_key' }); assert.equal((await gated()).stored, 'api_key'); assert.equal((await gated()).source, 'stored key'); assert.deepEqual(await runtime.commands.models(), [{ provider: 'gated', modelId: 'locked' }]); await runtime.close(); runtime = await open(); assert.deepEqual(await runtime.commands.models(), [{ provider: 'gated', modelId: 'locked' }]); await runtime.immediate.logout({ provider: 'gated' }); assert.deepEqual(await runtime.commands.models(), []);});test('stop cancels a running tool, marks the request interrupted, and leaves the conversation usable', async (t) => { let cancelled = false; const hang = (signal) => new Promise((_, reject) => { signal.addEventListener('abort', () => { cancelled = true; reject(new Error('cancelled')); }); }); const editor = (name, _args, { abortSignal }) => (name === 'nvim_lua' ? hang(abortSignal) : Promise.resolve({})); const { runtime, faux } = await fixture(t, editor); const texts = async () => (await runtime.conversation.context(context)).messages .filter((message) => message.role === 'user') .map((message) => (typeof message.content === 'string' ? message.content : message.content[0].text)); await runtime.immediate.abort(); assert.deepEqual(await texts(), []); faux.setResponses([ fauxAssistantMessage(fauxToolCall('nvim_lua', { code: 'return system("sleep 600")' }), { stopReason: 'toolUse' }), fauxAssistantMessage('Fresh answer.'), ]); await runtime.commands.submit({ content: 'Run something slow' }); while (!(await runtime.harness.snapshot(LiveDoc, runtime.conversation.id, context))?.tools?.length) { await new Promise((resolve) => setTimeout(resolve, 5)); } const started = Date.now(); await runtime.immediate.abort(); assert.ok(Date.now() - started < 1000); assert.equal(cancelled, true); assert.deepEqual(await texts(), ['Run something slow', '[interrupted]']); assert.equal((await runtime.harness.snapshot(LiveDoc, runtime.conversation.id, context)).run, undefined); const next = await runtime.commands.submit({ content: 'Something else' }); const settled = await (await runtime.harness.submission(next.id, context)).wait(context); assert.equal(settled.status, 'done');});test('stock file tools act on editor buffers, not disk', async (t) => { const project = await mkdtemp(join(tmpdir(), 'pivi-project-')); t.after(() => rm(project, { recursive: true, force: true })); await writeFile(join(project, 'a.txt'), 'on disk\n'); const buffers = new Map([[join(project, 'a.txt'), 'unsaved in editor\n']]); const editor = async (name, args) => { if (name === 'unsaved_text') return buffers.has(args.path) ? { text: buffers.get(args.path) } : {}; if (name === 'set_text') buffers.set(args.path, args.content); return {}; }; const { runtime, faux } = await fixture(t, editor, project); const call = (name, args) => fauxAssistantMessage(fauxToolCall(name, args), { stopReason: 'toolUse' }); faux.setResponses([ call('read', { path: 'a.txt' }), call('edit', { path: 'a.txt', edits: [{ oldText: 'unsaved', newText: 'edited' }] }), call('write', { path: 'new/b.txt', content: 'brand new\n' }), fauxAssistantMessage('Done.'), ]); await runtime.commands.submit({ content: 'Work on the files' }); await runtime.conversation.waitForIdle(context); const results = (await runtime.conversation.context(context)).messages .filter((message) => message.role === 'toolResult') .map((message) => [message.isError, message.content.map((part) => part.text).join('')]); assert.deepEqual(results.map(([failed]) => failed), [false, false, false]); assert.match(results[0][1], /unsaved in editor/); assert.equal(buffers.get(join(project, 'a.txt')), 'edited in editor\n'); assert.equal(buffers.get(join(project, 'new/b.txt')), 'brand new\n'); assert.equal(await readFile(join(project, 'a.txt'), 'utf8'), 'on disk\n'); assert.equal(existsSync(join(project, 'new/b.txt')), false);});test('missing model rejects before admitting user input', async (t) => { const { runtime } = await fixture(t); await runtime.conversation.configure({ model: null }, context); await assert.rejects(runtime.commands.submit({ content: 'Keep this draft' }), /Choose a model/); assert.equal((await runtime.conversation.context(context)).messages.length, 0);});neovim/pivi/tools.mjs
Addednew file mode 100644+119 / −0 text lines
import { defineExtension, defineTool, section } from '@earendil-works/pi-durable';import { arr, bool, num, obj, oneOf, opt, str } from '@earendil-works/pi-schema';const GUIDE = `You are pivi, a coding agent living inside the user's running Neovim.Buffers are the truth. A buffer may hold unsaved changes that its file on disk lacks.- read, edit and write work on Neovim buffers: they see unsaved changes, and what they change stays unsaved and undoable.- nvim_lua runs Lua inside the editor with the whole vim API. It is also how you run programs: local r = system('nvim -l check.lua') returns code, stdout and stderr without freezing the editor. Programs see saved files only; the output names the unsaved buffers they could not see.- save writes buffers to disk. Save only when the user asks or a command must see your change, and say that you saved.- lsp asks the language server: definitions, references, hover, symbols, rename. It sees unsaved changes. Prefer it over text search for code navigation.- find lists files, search searches file contents - both without a shell. Reach for nvim_lua's system() only when a real program must run (git, a build, a script); never for listing or searching files.- diagnostics lists what the language servers report.The editor belongs to the user. Do not change their window, current buffer, cursor, working directory, options,registers or global Lua state unless they ask. To point at code, name the file and line.Each user message starts with an automatic [editor: ...] note saying where the user is. Use it; never repeat it.A message "[interrupted]" means the user stopped the request before it. Do not continue that request unless asked.Do not claim execution or verification you did not perform.You run inside pivi, a Neovim plugin whose source lives in this repository: lua/bugabinga/pivi/ (editor side)and pivi/ (worker, tests, README). When asked to change pivi itself, read those files first - bindings are listedin view.lua (ACTIONS), commands in init.lua. You can edit pivi while it runs; changes to lua/ take effect afterthe user runs :PiviReload, changes to pivi/*.mjs on the same reload (the worker restarts with it). Ask the userto reload between turns - reloading mid-request breaks the running agent turn.`;const path = (description) => str({ description: `${description} (relative to the working directory, or absolute)` });const TOOLS = [ { name: 'find', description: 'List files by glob, newest first, without a shell. Use this instead of ls or find: ' + 'it excludes .git, node_modules and build output, and returns paths relative to the working directory.', parameters: obj({ glob: opt(str({ description: 'Glob for the file name, e.g. "*.lua" or "*.spec.ts"; default all files' })), path: opt(path('Directory to search, default the working directory')), limit: opt(num({ description: 'Maximum number of files, default 100' })), }), }, { name: 'search', description: 'Search file contents with ripgrep, without a shell. Use this instead of grep or rg on the command ' + 'line: it sees saved files only (name the unsaved buffers in your reasoning), never touches unsaved ones, ' + 'and returns path:line:col matches with the source line.', parameters: obj({ pattern: str({ description: 'Regular expression (or literal text with literal: true)' }), literal: opt(bool({ description: 'Match the pattern as literal text, not a regular expression' })), path: opt(path('File or directory to search, default the working directory')), glob: opt(str({ description: 'Restrict to file names matching this glob, e.g. "*.lua"' })), max: opt(num({ description: 'Maximum number of matches, default 100' })), }), }, { name: 'save', description: 'Write the named buffers to disk, creating parent directories.', executionMode: 'sequential', parameters: obj({ paths: arr(path('Buffer to save')) }), }, { name: 'lsp', description: 'Ask the language server attached in Neovim. It sees unsaved changes. ' + 'Locations come back as path:line:col with the source line. rename edits buffers and leaves them unsaved.', executionMode: 'sequential', parameters: obj({ operation: oneOf([ 'definition', 'references', 'implementation', 'type_definition', 'hover', 'rename', 'symbols', 'workspace_symbols', ], { description: 'symbols outlines one file; workspace_symbols searches the project by name' }), path: opt(path('File; required except for workspace_symbols')), line: opt(num({ description: 'Line of the symbol, 1-indexed; required for position operations' })), symbol: opt(str({ description: 'The symbol text as written on that line, to locate the column' })), newName: opt(str({ description: 'New name, for rename' })), query: opt(str({ description: 'Name to search, for workspace_symbols' })), }), }, { name: 'diagnostics', description: 'List diagnostics (errors, warnings) that Neovim holds, for one file or for all loaded buffers. ' + 'They come from language servers and can lag behind fresh edits.', parameters: obj({ path: opt(path('File to check, default all loaded buffers')) }), }, { name: 'nvim_lua', description: 'Run a Lua chunk inside the live Neovim and get its return value back. The full vim API, vim.uv and ' + 'plugins are available. The chunk runs as a coroutine, so it can wait without freezing the editor:\n' + '- system(command, { cwd, stdin, timeout }) runs a shell command string or an argv table, streams its ' + 'output, and returns { code, signal, timed_out, stdout, stderr }. Programs see saved files only.\n' + '- await(function(resolve) ... end) suspends until resolve(value) is called from any callback and returns ' + 'that value; return a function from the starter to be run if the user stops the request.\n' + '- sleep(milliseconds).\n' + 'Blocking calls are refused: vim.wait, vim.system(...):wait(), vim.fn.system. ' + 'A chunk that computes for 10 s without yielding is stopped. ' + 'system() closes stdin and kills the whole process group on timeout (default 60 s; pass a shorter one when you can). ' + 'Never put multiline code on a command line - write a script file and run it (nvim -l script.lua); ' + 'a program stuck at an interactive prompt blocks until the timeout kills it. ' + 'Ex commands: vim.api.nvim_exec2(command, { output = true }).output', executionMode: 'sequential', outputLimits: { retain: 'tail' }, parameters: obj({ code: str({ description: 'Lua chunk; return a compact JSON-compatible value' }) }), },];export const neovim = (editor) => defineExtension({ name: 'pivi.neovim', sections: [section('pivi', () => GUIDE)], tools: TOOLS.map((tool) => defineTool({ ...tool, async execute(args, api, callContext) { const result = await editor(tool.name, args, callContext, (text) => api.output(text)); const output = result?.text === undefined ? undefined : [{ type: 'text', text: result.text }]; return { ...(output && { output }), isError: result?.error === true }; }, })),});neovim/pivi/worker.mjs
Addednew file mode 100644+105 / −0 text lines
import { mkdir } from 'node:fs/promises';import { dirname, join } from 'node:path';import { pathToFileURL } from 'node:url';import { fileCredentials } from './credentials.mjs';import { openPivi } from './harness.mjs';const [database, authentication, config] = process.argv.slice(2);if (!database || !authentication) throw new Error('Session database and credential file paths are required.');const send = (record) => new Promise((done) => process.stdout.write(JSON.stringify(record) + '\n', done));const pending = new Map();let sequence = 0;let closing = false;function ask(record, signal, onProgress) { return new Promise((resolve, reject) => { if (closing || signal?.aborted) return reject(new Error('Neovim request cancelled.')); const id = ++sequence; const abort = () => { send({ type: 'cancel', id }); finish(false, 'Neovim request cancelled.'); }; const finish = (ok, result) => { pending.delete(id); signal?.removeEventListener('abort', abort); ok ? resolve(result) : reject(new Error(result)); }; pending.set(id, { finish, onProgress }); signal?.addEventListener('abort', abort, { once: true }); send({ ...record, id }); });}let shown;function show({ items, ...view }) { if (items !== shown) view.items = shown = items; return send({ type: 'view', view });}await mkdir(dirname(database), { recursive: true });const credentials = fileCredentials(authentication);const modelsFile = join(dirname(authentication), 'models.json');const options = config ? await (await import(pathToFileURL(config).href)).default({ credentials }) : {};const runtime = await openPivi({ ...options, database, credentials, modelFile: modelsFile, onView: show, editor: (name, args, context, onProgress) => ask({ type: 'tool', name, args }, context.abortSignal, onProgress), interact: { prompt: ({ signal, ...prompt }) => ask({ type: 'prompt', prompt }, signal), notify: (event) => send({ type: 'auth', event }), }, onNotice: (message) => send({ type: 'notice', message }), onReport: (report) => send({ type: 'report', error: String(report.error ?? report.kind) }),});runtime.harness.closed.then((end) => { if (end.kind !== 'failed') return; console.error(end.error); process.exit(1);});await send({ type: 'ready' });async function respond({ id, method, params = {} }, operations) { try { await send({ type: 'response', id, ok: true, result: (await operations[method](params)) ?? null }); } catch (error) { await send({ type: 'response', id, ok: false, error: error.message }); }}let commands = Promise.resolve();function receive(line) { const record = JSON.parse(line); if (record.type === 'reply') { pending.get(record.id)?.finish(record.ok, record.ok ? record.result : record.error); } else if (record.type === 'progress') { pending.get(record.id)?.onProgress?.(record.text); } else if (Object.hasOwn(runtime.immediate, record.method)) { respond(record, runtime.immediate); } else if (Object.hasOwn(runtime.commands, record.method)) { commands = commands.then(() => respond(record, runtime.commands)); } else { send({ type: 'response', id: record.id, ok: false, error: `Unknown pivi operation: ${record.method}` }); }}let tail = '';process.stdin.setEncoding('utf8');process.stdin.on('data', (chunk) => { const lines = (tail + chunk).split('\n'); tail = lines.pop(); for (const line of lines) if (line) receive(line);});async function shutdown() { if (closing) return; closing = true; for (const { finish } of [...pending.values()]) finish(false, 'Neovim disconnected.'); await runtime.immediate.cancel(); await commands; await runtime.close(); await new Promise((flushed) => process.stdout.write('', flushed)); process.stdin.destroy();}process.stdin.on('end', shutdown);process.on('SIGTERM', shutdown);neovim/puk.nu
Modified+328 / −61 text lines
let tar_command = if $nu.os-info.name == 'windows' { [$env.SystemRoot System32 tar.exe] | path join} else { 'tar' }let compiler = if $nu.os-info.name == 'android' and ($env.TERMUX_VERSION? != null) { 'clang' } else { 'zig' }def require-compiler [] { if (which $compiler | is-empty) { let name = if $compiler == 'clang' { 'Clang' } else { 'Zig' } error make { msg: $"puk requires ($name) in PATH." } }}def refuse-running-neovim [] { let processes = ps | where { |process| let name = $process.name | path basename | str lowercase $name in [ 'nvim' 'nvim.exe' ] } if not ($processes | is-empty) { let pids = $processes.pid | each { into string } | str join ', ' [ $"Error: Neovim is running, PIDs: ($pids). Plugin installation stopped." 'Why: updating Treesitter parsers while Neovim holds parser DLLs can leave stale files and break health checks.' 'Action: close every Neovim instance, then rerun `just puk`.' ] | str join (char nl) | print --stderr exit 1 }} let data_path = nvim --headless --clean +'lua print(vim.fn.stdpath "data")' +q | complete | get stderr let cache_path = nvim --headless --clean +'lua print(vim.fn.stdpath "cache")' +q | complete | get stderr require-compiler refuse-running-neovim 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) if $paths_result.exit_code != 0 { error make { msg: $"Neovim path lookup failed: ($paths_result.stderr)" } } let paths = $paths_result.stdout | from json let data_path = $paths.data let cache_path = $paths.cache let plugin_specs = open puk.plugins.nuon let total = $plugin_specs | length print $"Installing plugins from puk.plugins.nuon. total: ($total)" let errors = $plugin_specs | par-each { install-spec $in $plugins_path $cache_path } | flatten let site_path = [ $data_path site ] | path join let base = $env.PWD let plugin_specs = (open ($base | path join puk.plugins.nuon) | collect) let parser_specs = (open ($base | path join puk.parsers.nuon) | collect) if (not ($parser_specs | is-empty)) and ((which tree-sitter | is-empty)) { print "puk.parsers.nuon declares parsers but the tree-sitter CLI is not in PATH." print "Install tree-sitter-cli (>= 0.26) first." exit 1 } let all_specs = ($plugin_specs | append $parser_specs) let total = $all_specs | length print $"Installing plugins and parsers from puk.*.nuon. total: ($total)" let pending_hooks = $plugin_specs | where { |spec| ($spec.post_install? | default null) != null and not (plugin-is-installed $spec $plugins_path) } let plugin_errors = $plugin_specs | par-each { install-spec $in $plugins_path $site_path $cache_path } | flatten let hook_errors = $pending_hooks | where { |spec| $spec.name not-in $plugin_errors.name } | each { |spec| finish-plugin $spec $plugins_path } | flatten let parser_errors = $parser_specs | each { install-spec $in $plugins_path $site_path $cache_path } | flatten let errors = ($plugin_errors | append $hook_errors | append $parser_errors) let updated = $plugin_specs | return $spec.commit let expected = $plugin_specs | each { |spec| (make-archive-path $spec $cache_path | path basename) } glob $"($cache_path)/*.tar.gz" | each { |path| glob $"($cache_path | str replace --all '\' '/')/*.tar.gz" | each { |path| let partial_path = mktemp --tmpdir-path $cache_path 'puk-download.XXXXXX' http get --raw --max-time 5sec $url | save $archive_path } catch { print $"Download of ($spec.name) timed out, retrying..." http get --raw --max-time 10sec $url | save $archive_path try { http get --raw --max-time 5sec $url | save --force $partial_path } catch { print $"Download of ($spec.name) failed, retrying..." http get --raw --max-time 10sec $url | save --force $partial_path } let checked = (run-external $tar_command '--list' '--file' $partial_path | complete) if $checked.exit_code != 0 { error make { msg: $"($spec.name): invalid archive: ($checked.stderr)" } } mv $partial_path $archive_path $archive_path } finally { if ($partial_path | path exists) { rm $partial_path } $archive_path}def tree-hash [dir: path] { glob $"($dir | str replace --all '\' '/')/**/*" | where { |f| ($f | path type) == file } | each { |f| { rel: ($f | path relative-to $dir), h: (open --raw $f | hash sha256) } }}def diff-hashes [base: path, hashes: list, label: string, name: string] { let now = (tree-hash $base) $hashes | each { |x| let y = ($now | where rel == $x.rel) 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 { '' } } | where { |s| $s != '' } # hopefully strip-componets works on win32 as well print $archive_path $tmp_path tar --extract --file $archive_path --directory $tmp_path --strip-components=1 if $spec.build != null { print $"Build step for plugin ($spec.name) detected! Executing now..." cd $tmp_path run-external $spec.build.0 ...($spec.build | slice 1.. ) try { let extracted = (run-external $tar_command '--extract' '--file' $archive_path '--directory' $tmp_path '--strip-components=1' | complete) if $extracted.exit_code != 0 { error make { msg: $"($spec.name): extraction failed: ($extracted.stderr)" } } if $spec.build != null { print $"Build step for plugin ($spec.name) detected! Executing now..." run-nu-in-dir $tmp_path $spec.build } $tmp_path } catch { |e| rm --recursive $tmp_path error make { msg: $e.msg } $tmp_pathlet allowed_shared_lib_type = match ( sys host | get name ) { $name if $name =~ 'Windows' => { 'dll' }, $name if $name =~ 'Linux' => { 'so' }, $name if $name =~ 'NixOS' => { 'so' }, $name if $name =~ 'Mac' => { 'dylib' }, $name if $name =~ 'Pixel' => { 'so' }, _ => { error make { msg: 'unknown operating system' } }, cd $folder_path glob $"**/*.{($filetypes | str join ',')}" --exclude $exclusions | path relative-to (pwd) | par-each { | file | let rebased_parent = [$tmp_path ($file | path dirname | to text)] | path join 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) } }) $copied | each { | entry | let rebased_parent = [$tmp_path ($entry.rel | path dirname)] | path joindef install-spec [ spec: record # a plugin to install plugins_path: path # folder to install plugins intodef run-nu-in-dir [ dir: path command: string] { cd $dir let result = (run-external $nu.current-exe '--no-config-file' '--commands' $command | complete) print --no-newline $result.stdout print --stderr --no-newline $result.stderr if $result.exit_code != 0 { error make { msg: $"Build failed with exit code ($result.exit_code)" } }}# the tree-sitter CLI compiles parsers with cc-rs, which takes only the program# name from the CC env var and drops everything after it. 'zig cc' therefore# needs a wrapper script, to carry the subcommand into the compiler call.def make-compiler-wrapper [ cache_path: path # folder to cache the compiler wrapper into] { let is_windows = ($nu.os-info.name == 'windows') let wrapper = if $is_windows { [$cache_path 'puk-zig-cc.cmd'] | path join } else { [$cache_path 'puk-zig-cc.sh'] | path join } let script = if $is_windows { ['@zig cc %*'] } else { ['#!/bin/sh', 'exec zig cc "$@"'] } $script | save --force $wrapper if not $is_windows { run-external chmod '+x' $wrapper } $wrapper}def install-spec-parser [ spec: record # a parser to install site_path: path # nvim site dir (parsers/queries install root) let parser_so = [$site_path parser $"($spec.name).so"] | path join let pin_path = [$site_path parser $".($spec.name).commit.puk"] | path join let queries_target = [$site_path queries $spec.name] | path join let has_queries = ($spec.queries? | default null) != null let queries_ready = if $has_queries { (glob $"($queries_target | str replace --all '\' '/')/*.scm" | length) > 0 } else { true } if ($parser_so | path type) == file and $queries_ready and ($pin_path | path type) == file and ((open --raw $pin_path | str trim) == $spec.commit) { return [] } try { print $"Downloading parser ($spec.name)..." let archive_path = download-plugin $spec $cache_path print $"Unpacking parser ($spec.name)..." let unpacked_path = unpack-plugin-archive { name: $spec.name, build: null } $archive_path try { let root = if ($spec.location? | default null) != null { [$unpacked_path $spec.location] | path join } else { $unpacked_path } let source_ready = if $spec.generate { ($root | path join src grammar.json | path exists) or ($root | path join grammar.js | path exists) } else { $root | path join src parser.c | path exists } if not $source_ready { error make { msg: $"($spec.name): tarball is missing parser source or grammar" } } if $spec.generate { print $"Generating parser ($spec.name)..." let grammar = if ($root | path join src grammar.json | path exists) { $root | path join src grammar.json } else { $root | path join grammar.js } let gen = (tree-sitter generate $grammar '--output' ($root | path join src) | complete) if $gen.exit_code != 0 { error make { msg: $"($spec.name): tree-sitter generate failed: ($gen.stderr)" } } } print $"Compiling parser ($spec.name)..." let so_tmp = ($root | path join $"($spec.name).so") let compiler_env = { CC: (if $compiler == 'clang' { 'clang' } else { (make-compiler-wrapper $cache_path) }), CRATE_CC_NO_DEFAULTS: '1', CFLAGS: (if $nu.os-info.name == 'windows' { $"-target ($nu.os-info.arch)-windows-gnu -O2" } else { '-O2 -fPIC' }) } let built = with-env $compiler_env { tree-sitter build '--output' $so_tmp $root | complete } if $built.exit_code != 0 { error make { msg: $"($spec.name): tree-sitter build failed: ($built.stderr)" } } if not ($so_tmp | path exists) { error make { msg: $"($spec.name): compile produced no .so" } } let staged_queries = [$unpacked_path '.puk-queries'] | path join if $has_queries { let queries = glob $"([$root $spec.queries] | path join | str replace --all '\' '/')/*.scm" if ($queries | is-empty) { error make { msg: $"($spec.name): no .scm queries found" } } mkdir $staged_queries $queries | each { |f| cp $f $staged_queries } | ignore } mkdir ($site_path | path join parser) let old_parser = [$unpacked_path '.puk-old-parser'] | path join let old_queries = [$unpacked_path '.puk-old-queries'] | path join let old_pin = if ($pin_path | path type) == file { open --raw $pin_path } else { null } if ($parser_so | path exists) { cp $parser_so $old_parser } mut queries_replaced = false let failure = try { if $has_queries { mkdir ($queries_target | path dirname) if ($queries_target | path exists) { mv $queries_target $old_queries } $queries_replaced = true mv $staged_queries $queries_target } cp --force $so_tmp $parser_so $spec.commit | save --force $pin_path null } catch { |e| $e } if $failure != null { if ($old_parser | path exists) { cp --force $old_parser $parser_so } else if ($parser_so | path exists) { rm $parser_so } if $queries_replaced { if ($queries_target | path exists) { rm --recursive $queries_target } if ($old_queries | path exists) { mv $old_queries $queries_target } } if $old_pin != null { $old_pin | save --force $pin_path } else if ($pin_path | path type) == file { rm $pin_path } error make { msg: $failure.msg } } print $"Parser ($spec.name) installed into ($parser_so)!" [] } finally { rm --recursive $unpacked_path } } catch { |e| print $"FAILED parser ($spec.name): ($e.msg)" return [{ name: $spec.name, error: $e.msg }] }}def install-spec [ spec: record # a plugin or parser to install plugins_path: path # folder to install plugins into site_path: path # nvim site dir (parser install root) cache_path: path # folder to cache downloaded archives into] { if ($spec.generate? != null) { return (install-spec-parser $spec $site_path $cache_path) } print $"Installing ($spec.name)..." let installed_plugin_path = install-plugin $spec $unpacked_path $plugins_path print $"Plugin ($spec.name) installed into ($installed_plugin_path)!" return [] try { print $"Installing ($spec.name)..." let installed_plugin_path = install-plugin $spec $unpacked_path $plugins_path if ($spec.post_install? | default null) == null { $spec.commit | save --force (make-commit-file-path $installed_plugin_path) } print $"Plugin ($spec.name) installed into ($installed_plugin_path)!" [] } finally { rm --recursive $unpacked_path }def finish-plugin [spec: record, plugins_path: path] { try { print $"Running post-install for ($spec.name)..." let commands = $spec.post_install | each { |cmd| $cmd | to json --raw } | str join ', ' 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 let result = (nvim --headless -c $script +qa | complete) print --no-newline $result.stdout print --stderr --no-newline $result.stderr if $result.exit_code != 0 { error make { msg: $"($spec.name) post-install failed with exit code ($result.exit_code)" } } $spec.commit | save --force (make-commit-file-path (make-plugin-path $spec $plugins_path)) [] } catch { |e| [{ name: $spec.name, error: $e.msg }] }}neovim/puk.parsers.nuon
Addednew file mode 100644+6 / −0 text lines
[ [name, source, repo, branch, commit, generate, queries, location]; ["d2", github, "ravsii/tree-sitter-d2", main, "7bba28221d8c466d28b725124494bf89219326fd", true, queries, null], [gherkin, github, binhtddev/tree-sitter-gherkin, main, "6bd665dd7d4159c63c0b7a9f69d784f3315328c1", false, null, null], [asciidoc, github, cathaysia/tree-sitter-asciidoc, master, "882e43173427b831cd0d98ab3525501bed6ea214", false, queries, tree-sitter-asciidoc]]No final newlineneovim/puk.plugins.nuon
Modified+35 / −39 text lines
[nvim-treesitter-textobjects, github, nvim-treesitter/nvim-treesitter-textobjects, main, "851e865342e5a4cb1ae23d31caf6e991e1c99f1e", null], [nvim-ts-autotag, github, windwp/nvim-ts-autotag, main, "88c1453db4ba7dd24131086fe51fdf74e587d275", null], [oil, github, "stevearc/oil.nvim", master, "0fcc83805ad11cf714a949c98c605ed717e0b83e", null], [nvim-surround, github, kylechui/nvim-surround, main, "9291040de8cd8a4439eb64c441e8d5d2bf884a5a", null], [conform, github, "stevearc/conform.nvim", master, "dca1a190aa85f9065979ef35802fb77131911106", null], [plenary, github, "nvim-lua/plenary.nvim", master, "74b06c6c75e4eeb3108ec01852001636d85a932b", null], ["mini.splitjoin", github, "echasnovski/mini.splitjoin", main, "8bd5a3d581b9f3dd3bc91fe495e210b8b0ee981d", null], ["mini.pick", github, "echasnovski/mini.pick", main, "437d44eb57312f23e6b931704694fc294922cd88", null], ["mini.extra", github, "echasnovski/mini.extra", main, "bc4e872500fd6d2ce252604e0ffa100f64f02280", null], ["mini.hipatterns", github, "echasnovski/mini.hipatterns", main, "9eff319bbe66adfaf781a0d0e174baa08ba94909", null], ["mini.clue", github, "echasnovski/mini.clue", main, "43bd6cf1c3ccdea46d403c32dbc4629fa6afa09d", null], ["mini.bracketed", github, "echasnovski/mini.bracketed", main, "efb969a6a9583a5d48bfbe36363769351e38f967", null], ["mini.diff", github, "echasnovski/mini.diff", main, "ab11575a6c147ecfba894d676d0c93e855021d34", null], ["mini.jump2d", github, "echasnovski/mini.jump2d", main, "c0df3170873b712b61951781aeee9942a92ba1f1", null], ["mini.move", github, "echasnovski/mini.move", main, "74d140143b1bb905c3d0aebcfc2f216fd237080e", null], ["mini.icons", github, "echasnovski/mini.icons", main, "bac6317300e205335df425296570d84322730067", null], [nvim-autopairs, github, windwp/nvim-autopairs, master, "59bce2eef357189c3305e25bc6dd2d138c1683f5", null], [specs, github, "cxwx/specs.nvim", main, "4a2f6f71eaa054a9355a2f424b4723e68f7ce22c", null], [rulebook, github, chrisgrieser/nvim-rulebook, main, "083dd66b498bc142386a7c96dddab73acbf4ec20", null], [profile, github, "stevearc/profile.nvim", master, "30433d7513f0d14665c1cfcea501c90f8a63e003", null], [grug-far, github, "MagicDuck/grug-far.nvim", main, "21790e59dd0109a92a70cb874dd002af186314f5", null], [incline, github, "b0o/incline.nvim", main, "8b54c59bcb23366645ae10edca6edfb9d3a0853e", null], [dap, github, mfussenegger/nvim-dap, master, "45a69eba683a2c448dd9ecfc4de89511f0646b5f", null], [dapui, github, rcarriga/nvim-dap-ui, master, "1a66cabaa4a4da0be107d5eda6d57242f0fe7e49", null], [nio, github, nvim-neotest/nvim-nio, master, "21f5324bfac14e22ba26553caf69ec76ae8a7662", null], [dap-disasm, github, Jorenar/nvim-dap-disasm, master, "1119f3f2b22e411adcd123cdcf6d0425b61a31a7", null], [nvim-dap-virtual-text, github, theHamsta/nvim-dap-virtual-text, master, "fbdb48c2ed45f4a8293d0d483f7730d24467ccb6", null], ["mini.notify", github, "echasnovski/mini.notify", main, "9e68ab0a54f90567b4fec2de22c851dba8480439", null]] [nvim-treesitter-textobjects, github, nvim-treesitter/nvim-treesitter-textobjects, main, "5c7b0263797dfd1bd6202f2b219f3b53a80b2187", null, null], [nvim-ts-autotag, github, windwp/nvim-ts-autotag, main, "d7220b55e16ed3c04e88086256def5d282429493", null, null], [oil, github, "stevearc/oil.nvim", master, "d3733d933833a0e59b813ecec99341527adf0c28", null, null], [nvim-surround, github, kylechui/nvim-surround, main, "8b47db616ef658b8fc27e61db2896aa2f40134de", null, null], [otter, github, "jmbuhr/otter.nvim", main, "6f05811621460eca983bf2cd877e63c59a40720e", null, null], [conform, github, "stevearc/conform.nvim", master, "016802de402556da54c36bd7359b441266b01cdd", null, null], [plenary, github, "nvim-lua/plenary.nvim", master, "74b06c6c75e4eeb3108ec01852001636d85a932b", null, null], [wezterm-types, github, "DrKJeff16/wezterm-types", main, "1e6a0b7ac2206b197c741240743e981af37ce292", null, null], ["mini.splitjoin", github, "echasnovski/mini.splitjoin", main, "ea8c7d0e7d0ab184e8e82b88a777e50277eba744", null, null], ["mini.pick", github, "echasnovski/mini.pick", main, "406d41308e58486ea5c3352f5821c4cd9992af65", null, null], ["mini.extra", github, "echasnovski/mini.extra", main, "8ed483ebaea4610c4b5e7b0fcc28854225946ddd", null, null], ["mini.hipatterns", github, "echasnovski/mini.hipatterns", main, "7a79e5f000beb530ade0fa9faec70f01469dbcb3", null, null], ["mini.clue", github, "echasnovski/mini.clue", main, "c8f246f080d4a7907990199151464978b43c9406", null, null], ["mini.bracketed", github, "echasnovski/mini.bracketed", main, "ee8888fe7eda8a187bd2bfa0a992213451745ecd", null, null], ["mini.diff", github, "echasnovski/mini.diff", main, "91d6ce4b7f400439fe761f01a58280f2c0f99c01", null, null], ["mini.jump2d", github, "echasnovski/mini.jump2d", main, "6b451bfa93a801f5d0d4118a62298a178050a46f", null, null], ["mini.move", github, "echasnovski/mini.move", main, "24d9bb2af6b6f747205fb5da0ec51a7d621077d7", null, null], ["mini.icons", github, "echasnovski/mini.icons", main, "fc90b3925a2a68282be06e28cfe0cbb366c75dad", null, null], [nvim-autopairs, github, windwp/nvim-autopairs, master, "3172f40c16563db871a58f20d205c710ad782311", null, null], ["mini.animate", github, "echasnovski/mini.animate", main, "74d003a30c0c37c23015032516237c8cad09af9f", null, null], [rulebook, github, chrisgrieser/nvim-rulebook, main, "0572382adde2eb03bde68da23c2aaac3577f503a", null, null], [profile, github, "stevearc/profile.nvim", master, "30433d7513f0d14665c1cfcea501c90f8a63e003", null, null], [grug-far, github, "MagicDuck/grug-far.nvim", main, "91b7e58b6ffc6ddad5acb7a7c1df21257724449e", null, null], [incline, github, "b0o/incline.nvim", main, "debd628e9395f7a9da57bdc31ce75ca6b40a880b", null, null], [dap, github, mfussenegger/nvim-dap, master, "cfa2d58f4537aca6ca83e2de1a0d9f1491121264", null, null], [dapui, github, rcarriga/nvim-dap-ui, master, "cc9dd33aade7f20bae414d0cba163bc60d4d4b43", null, null], [nio, github, nvim-neotest/nvim-nio, master, "edcc181a875301dd21840189aa2f2f9ad69fc172", null, null], [dap-disasm, github, Jorenar/nvim-dap-disasm, master, "44c6eb0ec369962316b3d7c35d109be66666c6c1", null, null], [nvim-dap-virtual-text, github, theHamsta/nvim-dap-virtual-text, master, "fbdb48c2ed45f4a8293d0d483f7730d24467ccb6", null, null], ["mini.notify", github, "echasnovski/mini.notify", main, "7e89272723320a059d46faa3b67cf8220675bf21", null, null]]No final newlineneovim/queries/gherkin/highlights.scm
Addednew file mode 100644+25 / −0 text lines
(feature_line (feature_kw) @keyword)(feature_line (context) @title)(scenario_line (scenario_kw) @keyword)(scenario_outline_line (scenario_outline_kw) @keyword)(scenario_line (context) @title)(scenario_outline_line (context) @title)(rule_line (rule_kw) @keyword)(rule_line (context) @title)(background_line (background_kw) @keyword)(background_line (context) @title)(examples_line (examples_kw) @keyword)(given_line (given_kw) @keyword)(when_line (when_kw) @keyword)(then_line (then_kw) @keyword)(and_line (and_kw) @keyword)(but_line (but_kw) @keyword)(tags (tag) @tag)(comment) @comment @spell(doc_string) @stringneovim/sample_files/A.prg
Modified+4 / −4 text lines
neovim/sample_files/test.container
Addednew file mode 100644+2 / −0 text lines
neovim/sample_files/test.dockerfile
Addednew file mode 100644+2 / −0 text lines
neovim/sample_files/test.feature
Addednew file mode 100644+42 / −0 text lines
# language: en# Canonical Gherkin constructs from the cucumber.io reference — used to# validate the tree-sitter-gherkin parser against real syntax.Feature: Beverages Users can pay for beverages and receive change Step definitions live in the drink service Background: Given a customer named "barry" And a coffee named "espresso" priced at 2 @golden @smoke Scenario: Buying a coffee Given barry has bought an "espresso" When barry drinks the espresso Then barry should be "happy" Scenario Outline: Free refills Given the season is <season> When barry orders a <drink> Then barry pays <price> Examples: | season | drink | price | | summer | iced latte | 3 | | winter | espresso | 2 | Rule: Happy hour discounts apply @happy-hour Scenario: Discounted espresso between 16:00 and 17:00 Given the time is "16:30" When barry orders an espresso Then the receipt contains: """ espresso 1.00 discount -1.00 """ And the price list looks like: | drink | price | | espresso | 1 |neovim/sample_files/test.go
Addednew file mode 100644+7 / −0 text lines
neovim/sample_files/test.java
Addednew file mode 100644+5 / −0 text lines
neovim/sample_files/test.jsonc
Addednew file mode 100644+4 / −0 text lines
neovim/sample_files/test.just
Addednew file mode 100644+2 / −0 text lines
neovim/sample_files/test.kdl
Modified+1 / −1 text lines
neovim/sample_files/test.lua
Addednew file mode 100644+2 / −0 text lines
neovim/sample_files/test.nu
Addednew file mode 100644+2 / −0 text lines
neovim/sample_files/test.proto
Addednew file mode 100644+5 / −0 text lines
neovim/sample_files/test.py
Addednew file mode 100644+2 / −0 text lines
neovim/sample_files/test.rs
Addednew file mode 100644+3 / −0 text lines
neovim/sample_files/test.service
Addednew file mode 100644+6 / −0 text lines
neovim/sample_files/test.sh
Addednew file mode 100644+2 / −0 text lines
neovim/sample_files/test.tf
Addednew file mode 100644+5 / −0 text lines
neovim/sample_files/test.tofu
Addednew file mode 100644+1 / −0 text lines
resource "null_resource" "test" {}neovim/sample_files/test.toml
Addednew file mode 100644+3 / −0 text lines
neovim/sample_files/test.xml
Addednew file mode 100644+4 / −0 text lines
neovim/sample_files/test.zig
Addednew file mode 100644+5 / −0 text lines
neovim/spell/de.utf-8.add
Deleteddeleted file mode 100644+0 / −3 text lines
neovim/spell/de.utf-8.add.spl
Deleteddeleted file mode 100644Binary size (old → new): 74 → 0 bytes.
neovim/spell/de.utf-8.spl
Deleteddeleted file mode 100644Binary size (old → new): 570932 → 0 bytes.
neovim/spell/en.utf-8.add
Deleteddeleted file mode 100644+0 / −1 text lines
stevearcneovim/spell/en.utf-8.add.spl
Deleteddeleted file mode 100644Binary size (old → new): 41 → 0 bytes.
neovim/spell/nerd.utf-8.add
Deleteddeleted file mode 100644+0 / −160 text lines
bugabinganeovimluaapinuguftpluginaitodopandocnushellltexnvimgithubvimpreviewpandocShirouEmiyaKKGispinsoftKKG5KKG6lspconfigneoconflspautopairscterm/!navicwinbarresessionconfigsBufNewFileLuaLSeditorconfigexrclocalrcsigncolumntogglersripgrepprequirepcallargsipairssetmetatablecolorschemecmdlinetreesittercmdpopupsneovideweztermfullscreencheckhealthplsstyluaeolkoolgrepprgmakeprgmodulepathFFIjdtlshrefDocumentUrisinnfreiAsciidocAsciidocFXGraalVMValidierungJUnit4NullabilityEclipseStoregRPCUUIDsFKsFIXMEsJSpecifyaercyazimagitgituskBugabinga'sinlynemdcatnuonLSPsgolangpresentermbartibrbwsearchMuratoridorkfilehxzellijdifftasticweechattarsnapmuxicepumatraefiktclocksbytehttmhandlrsddiskonautmdshast-grepJavaDocCiaoCiaoEntwicklerQuizToolchainRätselantwortenminidlnasystemdfiletypeLibcyberREPLBézierTailscaletailscalePopOsMailinaboxwlumastylixnixvimKrylowEntwicklerfrühstückProzessNixOsthymeleafhtmxPräsiProduktlandschaftioLog4J2VorhandRückhandbelagVorhandbelagFastarcNittakuGriffformNoppenTibharKopfgrößeAlfaviewSammelphaseSusannGruppenschulungenTeilnehmeranzahlStundenkontingenteHinduismusBuddhismusGlaubensregelnossjqwikvendoredTestbarkeitGlossarsubsidizationneovim/spell/nerd.utf-8.add.spl
Deleteddeleted file mode 100644Binary size (old → new): 2368 → 0 bytes.
neovim/spell/nerd.utf-8.spl
Deleteddeleted file mode 100644Binary size (old → new): 69071 → 0 bytes.